]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/activities/MainWebView.java
1700ba4c5c3a82d075cc3c4086024617148bfa61
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / activities / MainWebView.java
1 /**
2  * Copyright 2015-2017 Soren Stoutner <soren@stoutner.com>.
3  *
4  * Download cookie code contributed 2017 Hendrik Knackstedt.  Copyright assigned to Soren Stoutner <soren@stoutner.com>.
5  *
6  * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
7  *
8  * Privacy Browser is free software: you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation, either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * Privacy Browser is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with Privacy Browser.  If not, see <http://www.gnu.org/licenses/>.
20  */
21
22 package com.stoutner.privacybrowser.activities;
23
24 import android.annotation.SuppressLint;
25 import android.app.DialogFragment;
26 import android.app.DownloadManager;
27 import android.content.ClipData;
28 import android.content.ClipboardManager;
29 import android.content.Context;
30 import android.content.Intent;
31 import android.content.SharedPreferences;
32 import android.content.res.Configuration;
33 import android.graphics.Bitmap;
34 import android.graphics.drawable.BitmapDrawable;
35 import android.graphics.drawable.Drawable;
36 import android.net.Uri;
37 import android.net.http.SslCertificate;
38 import android.net.http.SslError;
39 import android.os.Build;
40 import android.os.Bundle;
41 import android.preference.PreferenceManager;
42 import android.print.PrintDocumentAdapter;
43 import android.print.PrintManager;
44 import android.support.annotation.NonNull;
45 import android.support.design.widget.CoordinatorLayout;
46 import android.support.design.widget.NavigationView;
47 import android.support.design.widget.Snackbar;
48 import android.support.v4.app.ActivityCompat;
49 import android.support.v4.content.ContextCompat;
50 import android.support.v4.view.GravityCompat;
51 import android.support.v4.widget.DrawerLayout;
52 import android.support.v4.widget.SwipeRefreshLayout;
53 import android.support.v7.app.ActionBar;
54 import android.support.v7.app.ActionBarDrawerToggle;
55 import android.support.v7.app.AppCompatActivity;
56 import android.support.v7.app.AppCompatDialogFragment;
57 import android.support.v7.widget.Toolbar;
58 import android.text.Editable;
59 import android.text.TextWatcher;
60 import android.util.Patterns;
61 import android.view.ContextMenu;
62 import android.view.GestureDetector;
63 import android.view.KeyEvent;
64 import android.view.Menu;
65 import android.view.MenuItem;
66 import android.view.MotionEvent;
67 import android.view.View;
68 import android.view.WindowManager;
69 import android.view.inputmethod.InputMethodManager;
70 import android.webkit.CookieManager;
71 import android.webkit.DownloadListener;
72 import android.webkit.SslErrorHandler;
73 import android.webkit.WebBackForwardList;
74 import android.webkit.WebChromeClient;
75 import android.webkit.WebResourceResponse;
76 import android.webkit.WebStorage;
77 import android.webkit.WebView;
78 import android.webkit.WebViewClient;
79 import android.webkit.WebViewDatabase;
80 import android.widget.EditText;
81 import android.widget.FrameLayout;
82 import android.widget.ImageView;
83 import android.widget.LinearLayout;
84 import android.widget.ProgressBar;
85 import android.widget.RelativeLayout;
86 import android.widget.TextView;
87
88 import com.stoutner.privacybrowser.BannerAd;
89 import com.stoutner.privacybrowser.BuildConfig;
90 import com.stoutner.privacybrowser.R;
91 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
92 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcut;
93 import com.stoutner.privacybrowser.dialogs.DownloadFile;
94 import com.stoutner.privacybrowser.dialogs.DownloadImage;
95 import com.stoutner.privacybrowser.dialogs.SslCertificateError;
96 import com.stoutner.privacybrowser.dialogs.UrlHistory;
97 import com.stoutner.privacybrowser.dialogs.ViewSslCertificate;
98
99 import java.io.BufferedReader;
100 import java.io.ByteArrayInputStream;
101 import java.io.IOException;
102 import java.io.InputStreamReader;
103 import java.io.UnsupportedEncodingException;
104 import java.net.MalformedURLException;
105 import java.net.URL;
106 import java.net.URLEncoder;
107 import java.util.HashMap;
108 import java.util.HashSet;
109 import java.util.Map;
110 import java.util.Set;
111
112 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
113 public class MainWebView extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, CreateHomeScreenShortcut.CreateHomeScreenSchortcutListener,
114         SslCertificateError.SslCertificateErrorListener, DownloadFile.DownloadFileListener, DownloadImage.DownloadImageListener, UrlHistory.UrlHistoryListener {
115
116     // `appBar` is public static so it can be accessed from `OrbotProxyHelper`.
117     // It is also used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applySettings()`.
118     public static ActionBar appBar;
119
120     // `favoriteIcon` is public static so it can be accessed from `CreateHomeScreenShortcut`, `Bookmarks`, `CreateBookmark`, `CreateBookmarkFolder`, and `EditBookmark`.
121     // It is also used in `onCreate()` and `onCreateHomeScreenShortcutCreate()`.
122     public static Bitmap favoriteIcon;
123
124     // `formattedUrlString` is public static so it can be accessed from `Bookmarks`.
125     // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
126     public static String formattedUrlString;
127
128     // `sslCertificate` is public static so it can be accessed from `ViewSslCertificate`.  It is also used in `onCreate()`.
129     public static SslCertificate sslCertificate;
130
131
132     // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, and `onBackPressed()`.
133     private DrawerLayout drawerLayout;
134
135     // `rootCoordinatorLayout` is used in `onCreate()` and `applySettings()`.
136     private CoordinatorLayout rootCoordinatorLayout;
137
138     // 'mainWebView' is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`, `findNextOnPage()`, `closeFindOnPage()`, and `loadUrlFromTextBox()`.
139     private WebView mainWebView;
140
141     // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
142     private FrameLayout fullScreenVideoFrameLayout;
143
144     // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu`, and `onRestart()`.
145     private SwipeRefreshLayout swipeRefreshLayout;
146
147     // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
148     private CookieManager cookieManager;
149
150     // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrlFromTextBox()`.
151     private final Map<String, String> customHeaders = new HashMap<>();
152
153     // `javaScriptEnabled` is also used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `applySettings()`.
154     // It is `Boolean` instead of `boolean` because `applySettings()` needs to know if it is `null`.
155     private Boolean javaScriptEnabled;
156
157     // `firstPartyCookiesEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applySettings()`.
158     private boolean firstPartyCookiesEnabled;
159
160     // `thirdPartyCookiesEnabled` used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
161     private boolean thirdPartyCookiesEnabled;
162
163     // `domStorageEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
164     private boolean domStorageEnabled;
165
166     // `saveFormDataEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
167     private boolean saveFormDataEnabled;
168
169     // `swipeToRefreshEnabled` is used in `onPrepareOptionsMenu()` and `applySettings()`.
170     private boolean swipeToRefreshEnabled;
171
172     // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applySettings()`.
173     private String homepage;
174
175     // `javaScriptDisabledSearchURL` is used in `loadURLFromTextBox()` and `applySettings()`.
176     private String javaScriptDisabledSearchURL;
177
178     // `javaScriptEnabledSearchURL` is used in `loadURLFromTextBox()` and `applySettings()`.
179     private String javaScriptEnabledSearchURL;
180
181     // `adBlockerEnabled` is used in `onCreate()` and `applySettings()`.
182     private boolean adBlockerEnabled;
183
184     // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applySettings()`.
185     private boolean fullScreenBrowsingModeEnabled;
186
187     // `inFullScreenBrowsingMode` is used in `onCreate()` and `applySettings()`.
188     private boolean inFullScreenBrowsingMode;
189
190     // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applySettings()`.
191     private boolean hideSystemBarsOnFullscreen;
192
193     // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applySettings()`.
194     private boolean translucentNavigationBarOnFullscreen;
195
196     // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
197     private LinearLayout findOnPageLinearLayout;
198
199     // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
200     private EditText findOnPageEditText;
201
202     // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
203     private Menu mainMenu;
204
205     // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
206     private ActionBarDrawerToggle drawerToggle;
207
208     // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
209     private Toolbar supportAppBar;
210
211     // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, and `loadUrlFromTextBox()`.
212     private EditText urlTextBox;
213
214     // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
215     private View adView;
216
217     // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
218     private SslErrorHandler sslErrorHandler;
219
220     // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
221     private InputMethodManager inputMethodManager;
222
223     // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
224     private RelativeLayout mainWebViewRelativeLayout;
225
226     @Override
227     // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.  The whole premise of Privacy Browser is built around an understanding of these dangers.
228     @SuppressLint("SetJavaScriptEnabled")
229     protected void onCreate(Bundle savedInstanceState) {
230         super.onCreate(savedInstanceState);
231         setContentView(R.layout.drawerlayout);
232
233         // Get a handle for `inputMethodManager`.
234         inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
235
236         // We need to use the `SupportActionBar` from `android.support.v7.app.ActionBar` until the minimum API is >= 21.
237         supportAppBar = (Toolbar) findViewById(R.id.app_bar);
238         setSupportActionBar(supportAppBar);
239         appBar = getSupportActionBar();
240
241         // This is needed to get rid of the Android Studio warning that `appBar` might be null.
242         assert appBar != null;
243
244         // Add the custom url_app_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
245         appBar.setCustomView(R.layout.url_app_bar);
246         appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
247
248         // Set the "go" button on the keyboard to load the URL in urlTextBox.
249         urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.urlTextBox);
250         urlTextBox.setOnKeyListener(new View.OnKeyListener() {
251             @Override
252             public boolean onKey(View v, int keyCode, KeyEvent event) {
253                 // If the event is a key-down event on the `enter` button, load the URL.
254                 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
255                     // Load the URL into the mainWebView and consume the event.
256                     try {
257                         loadUrlFromTextBox();
258                     } catch (UnsupportedEncodingException e) {
259                         e.printStackTrace();
260                     }
261                     // If the enter key was pressed, consume the event.
262                     return true;
263                 } else {
264                     // If any other key was pressed, do not consume the event.
265                     return false;
266                 }
267             }
268         });
269
270         // Get handles for views that need to be accessed.
271         drawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout);
272         rootCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.root_coordinatorlayout);
273         mainWebViewRelativeLayout = (RelativeLayout) findViewById(R.id.main_webview_relativelayout);
274         mainWebView = (WebView) findViewById(R.id.mainWebView);
275         findOnPageLinearLayout = (LinearLayout) findViewById(R.id.find_on_page_linearlayout);
276         findOnPageEditText = (EditText) findViewById(R.id.find_on_page_edittext);
277         fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.full_screen_video_framelayout);
278
279         // Create a double-tap listener to toggle full-screen mode.
280         final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
281             // Override `onDoubleTap()`.  All other events are handled using the default settings.
282             @Override
283             public boolean onDoubleTap(MotionEvent event) {
284                 if (fullScreenBrowsingModeEnabled) {  // Only process the double-tap if full screen browsing mode is enabled.
285                     // Toggle `inFullScreenBrowsingMode`.
286                     inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
287
288                     if (inFullScreenBrowsingMode) {  // Switch to full screen mode.
289                         // Hide the `appBar`.
290                         appBar.hide();
291
292                         // Hide the `BannerAd` in the free flavor.
293                         if (BuildConfig.FLAVOR.contentEquals("free")) {
294                             BannerAd.hideAd(adView);
295                         }
296
297                         // Modify the system bars.
298                         if (hideSystemBarsOnFullscreen) {  // Hide everything.
299                             // Remove the translucent overlays.
300                             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
301
302                             // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
303                             drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
304
305                             /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
306                              * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
307                              * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
308                              */
309                             rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
310
311                             // Set `rootCoordinatorLayout` to fill the whole screen.
312                             rootCoordinatorLayout.setFitsSystemWindows(false);
313                         } else {  // Hide everything except the status and navigation bars.
314                             // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
315                             rootCoordinatorLayout.setFitsSystemWindows(false);
316
317                             if (translucentNavigationBarOnFullscreen) {  // There is an Android Support Library bug that causes a scrim to print on the right side of the `Drawer Layout` when the navigation bar is displayed on the right of the screen.
318                                 // Set the navigation bar to be translucent.
319                                 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
320                             }
321                         }
322                     } else {  // Switch to normal viewing mode.
323                         // Show the `appBar`.
324                         appBar.show();
325
326                         // Show the `BannerAd` in the free flavor.
327                         if (BuildConfig.FLAVOR.contentEquals("free")) {
328                             // Reload the ad.  Because the screen may have rotated, we need to use `reloadAfterRotate`.
329                             BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
330
331                             // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
332                             adView = findViewById(R.id.adView);
333                         }
334
335                         // Remove the translucent navigation bar flag if it is set.
336                         getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
337
338                         // Add the translucent status flag if it is unset.  This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
339                         getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
340
341                         // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
342                         rootCoordinatorLayout.setSystemUiVisibility(0);
343
344                         // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
345                         rootCoordinatorLayout.setFitsSystemWindows(true);
346                     }
347
348                     // Consume the double-tap.
349                     return true;
350                 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
351                     return false;
352                 }
353             }
354         });
355
356         // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
357         mainWebView.setOnTouchListener(new View.OnTouchListener() {
358             @Override
359             public boolean onTouch(View v, MotionEvent event) {
360                 // Send the `event` to `gestureDetector`.
361                 return gestureDetector.onTouchEvent(event);
362             }
363         });
364
365         // Update `findOnPageCountTextView`.
366         mainWebView.setFindListener(new WebView.FindListener() {
367             // Get a handle for `findOnPageCountTextView`.
368             final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
369
370             @Override
371             public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
372                 if ((isDoneCounting) && (numberOfMatches == 0)) {  // There are no matches.
373                     // Set `findOnPageCountTextView` to `0/0`.
374                     findOnPageCountTextView.setText(R.string.zero_of_zero);
375                 } else if (isDoneCounting) {  // There are matches.
376                     // `activeMatchOrdinal` is zero-based.
377                     int activeMatch = activeMatchOrdinal + 1;
378
379                     // Set `findOnPageCountTextView`.
380                     findOnPageCountTextView.setText(activeMatch + "/" + numberOfMatches);
381                 }
382             }
383         });
384
385         // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
386         findOnPageEditText.addTextChangedListener(new TextWatcher() {
387             @Override
388             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
389                 // Do nothing.
390             }
391
392             @Override
393             public void onTextChanged(CharSequence s, int start, int before, int count) {
394                 // Do nothing.
395             }
396
397             @Override
398             public void afterTextChanged(Editable s) {
399                 // Search for the text in `mainWebView`.
400                 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
401             }
402         });
403
404         // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
405         findOnPageEditText.setOnKeyListener(new View.OnKeyListener() {
406             @Override
407             public boolean onKey(View v, int keyCode, KeyEvent event) {
408                 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {  // The `enter` key was pressed.
409                     // Hide the soft keyboard.  `0` indicates no additional flags.
410                     inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
411
412                     // Consume the event.
413                     return true;
414                 } else {  // A different key was pressed.
415                     // Do not consume the event.
416                     return false;
417                 }
418             }
419         });
420
421         // Implement swipe to refresh
422         swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
423         swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
424         swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
425             @Override
426             public void onRefresh() {
427                 mainWebView.reload();
428             }
429         });
430
431         // `DrawerTitle` identifies the `DrawerLayout` in accessibility mode.
432         drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
433
434         // Listen for touches on the navigation menu.
435         final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationview);
436         navigationView.setNavigationItemSelectedListener(this);
437
438         // Get handles for `navigationMenu` and the back and forward menu items.  The menu is zero-based, so items 1, 2, and 3 are the second, third, and fourth entries in the menu.
439         final Menu navigationMenu = navigationView.getMenu();
440         final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
441         final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
442         final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
443
444         // The `DrawerListener` allows us to update the Navigation Menu.
445         drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
446             @Override
447             public void onDrawerSlide(View drawerView, float slideOffset) {
448             }
449
450             @Override
451             public void onDrawerOpened(View drawerView) {
452             }
453
454             @Override
455             public void onDrawerClosed(View drawerView) {
456             }
457
458             @Override
459             public void onDrawerStateChanged(int newState) {
460                 // Update the `Back`, `Forward`, and `History` menu items every time the drawer opens.
461                 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
462                 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
463                 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
464
465                 // Hide the keyboard so we can see the navigation menu.  `0` indicates no additional flags.
466                 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
467             }
468         });
469
470         // drawerToggle creates the hamburger icon at the start of the AppBar.
471         drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
472
473         // Initialize `adServerSet`.
474         final Set<String> adServersSet = new HashSet<>();
475
476         // Load the list of ad servers into memory.
477         try {
478             // Load `pgl.yoyo.org_adservers.txt` into a `BufferedReader`.
479             BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(getAssets().open("pgl.yoyo.org_adservers.txt")));
480
481             // Create a string for storing each ad server.
482             String adServer;
483
484             // Populate `adServersSet`.
485             while ((adServer = bufferedReader.readLine()) != null) {
486                 adServersSet.add(adServer);
487             }
488
489             // Close `bufferedReader`.
490             bufferedReader.close();
491         } catch (IOException ioException) {
492             // We're pretty sure the asset exists, so we don't need to worry about the `IOException` ever being thrown.
493         }
494
495         mainWebView.setWebViewClient(new WebViewClient() {
496             // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
497             // We have to use the deprecated `shouldOverrideUrlLoading` until API >= 24.
498             @SuppressWarnings("deprecation")
499             @Override
500             public boolean shouldOverrideUrlLoading(WebView view, String url) {
501                 // Use an external email program if the link begins with `mailto:`.
502                 if (url.startsWith("mailto:")) {
503                     // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
504                     Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
505
506                     // Parse the url and set it as the data for the `Intent`.
507                     emailIntent.setData(Uri.parse(url));
508
509                     // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
510                     emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
511
512                     // Make it so.
513                     startActivity(emailIntent);
514                     return true;
515                 } else {  // Load the URL in Privacy Browser.
516                     mainWebView.loadUrl(url, customHeaders);
517                     return true;
518                 }
519             }
520
521             // Block ads.  We have to use the deprecated `shouldInterceptRequest` until minimum API >= 21.
522             @SuppressWarnings("deprecation")
523             @Override
524             public WebResourceResponse shouldInterceptRequest(WebView view, String url){
525                 if (adBlockerEnabled) {  // Block ads.
526                     // Extract the host from `url`.
527                     Uri requestUri = Uri.parse(url);
528                     String requestHost = requestUri.getHost();
529
530                     // Create a variable to track if this is an ad server.
531                     boolean requestHostIsAdServer = false;
532
533                     // Check all the subdomains of `requestHost` if it is not `null`.
534                     if (requestHost != null) {
535                         while (requestHost.contains(".")) {
536                             if (adServersSet.contains(requestHost)) {
537                                 requestHostIsAdServer = true;
538                             }
539
540                             // Strip out the lowest subdomain of `requestHost`.
541                             requestHost = requestHost.substring(requestHost.indexOf(".") + 1);
542                         }
543                     }
544
545                     if (requestHostIsAdServer) {  // It is an ad server.
546                         // Return an empty `WebResourceResponse`.
547                         return new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
548                     } else {  // It is not an ad server.
549                         // `return null` loads the requested resource.
550                         return null;
551                     }
552                 } else {  // Ad blocking is disabled.
553                     // `return null` loads the requested resource.
554                     return null;
555                 }
556             }
557
558             // Update the URL in urlTextBox when the page starts to load.
559             @Override
560             public void onPageStarted(WebView view, String url, Bitmap favicon) {
561                 // We need to update `formattedUrlString` at the beginning of the load, so that if the user toggles JavaScript during the load the new website is reloaded.
562                 formattedUrlString = url;
563
564                 // Display the loading URL is the URL text box.
565                 urlTextBox.setText(url);
566             }
567
568             // Update formattedUrlString and urlTextBox.  It is necessary to do this after the page finishes loading because the final URL can change during load.
569             @Override
570             public void onPageFinished(WebView view, String url) {
571                 formattedUrlString = url;
572
573                 // Only update urlTextBox if the user is not typing in it.
574                 if (!urlTextBox.hasFocus()) {
575                     urlTextBox.setText(formattedUrlString);
576                 }
577
578                 // Store the SSL certificate so it can be accessed from `ViewSslCertificate`.
579                 sslCertificate = mainWebView.getCertificate();
580             }
581
582             // Handle SSL Certificate errors.
583             @Override
584             public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
585                 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
586                 sslErrorHandler = handler;
587
588                 // Display the SSL error `AlertDialog`.
589                 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateError.displayDialog(error);
590                 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.ssl_certificate_error));
591             }
592         });
593
594         mainWebView.setWebChromeClient(new WebChromeClient() {
595             // Update the progress bar when a page is loading.
596             @Override
597             public void onProgressChanged(WebView view, int progress) {
598                 ProgressBar progressBar = (ProgressBar) appBar.getCustomView().findViewById(R.id.progressBar);
599                 progressBar.setProgress(progress);
600                 if (progress < 100) {
601                     progressBar.setVisibility(View.VISIBLE);
602                 } else {
603                     progressBar.setVisibility(View.GONE);
604
605                     //Stop the `SwipeToRefresh` indicator if it is running
606                     swipeRefreshLayout.setRefreshing(false);
607                 }
608             }
609
610             // Set the favorite icon when it changes.
611             @Override
612             public void onReceivedIcon(WebView view, Bitmap icon) {
613                 // Save a copy of the favorite icon for use if a shortcut is added to the home screen.
614                 favoriteIcon = icon;
615
616                 // Place the favorite icon in the appBar.
617                 ImageView imageViewFavoriteIcon = (ImageView) appBar.getCustomView().findViewById(R.id.favoriteIcon);
618                 imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
619             }
620
621             // Enter full screen video
622             @Override
623             public void onShowCustomView(View view, CustomViewCallback callback) {
624                 // Pause the ad if this is the free flavor.
625                 if (BuildConfig.FLAVOR.contentEquals("free")) {
626                     BannerAd.pauseAd(adView);
627                 }
628
629                 // Remove the translucent overlays.
630                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
631
632                 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
633                 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
634
635                 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
636                  * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
637                  * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
638                  */
639                 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
640
641                 // Set `rootCoordinatorLayout` to fill the entire screen.
642                 rootCoordinatorLayout.setFitsSystemWindows(false);
643
644                 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
645                 fullScreenVideoFrameLayout.addView(view);
646                 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
647             }
648
649             // Exit full screen video
650             public void onHideCustomView() {
651                 // Hide `fullScreenVideoFrameLayout`.
652                 fullScreenVideoFrameLayout.removeAllViews();
653                 fullScreenVideoFrameLayout.setVisibility(View.GONE);
654
655                 // Add the translucent status flag.  This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
656                 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
657
658                 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars.  This also clears the `SYSTEM_UI` flags.
659                 rootCoordinatorLayout.setFitsSystemWindows(true);
660
661                 // Show the ad if this is the free flavor.
662                 if (BuildConfig.FLAVOR.contentEquals("free")) {
663                     // Reload the ad.  Because the screen may have rotated, we need to use `reloadAfterRotate`.
664                     BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
665
666                     // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
667                     adView = findViewById(R.id.adView);
668                 }
669             }
670         });
671
672         // Register `mainWebView` for a context menu.  This is used to see link targets and download images.
673         registerForContextMenu(mainWebView);
674
675         // Allow the downloading of files.
676         mainWebView.setDownloadListener(new DownloadListener() {
677             @Override
678             public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
679                 // Show the `DownloadFile` `AlertDialog` and name this instance `@string/download`.
680                 AppCompatDialogFragment downloadFileDialogFragment = DownloadFile.fromUrl(url, contentDisposition, contentLength);
681                 downloadFileDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
682             }
683         });
684
685         // Allow pinch to zoom.
686         mainWebView.getSettings().setBuiltInZoomControls(true);
687
688         // Hide zoom controls.
689         mainWebView.getSettings().setDisplayZoomControls(false);
690
691         // Initialize cookieManager.
692         cookieManager = CookieManager.getInstance();
693
694         // Replace the header that `WebView` creates for `X-Requested-With` with a null value.  The default value is the application ID (com.stoutner.privacybrowser.standard).
695         customHeaders.put("X-Requested-With", "");
696
697         // Initialize the default preference values the first time the program is run.  `this` is the context.  `false` keeps this command from resetting any current preferences back to default.
698         PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
699
700         // Apply the settings from the shared preferences.
701         applySettings();
702
703         // Get the intent information that started the app.
704         final Intent intent = getIntent();
705
706         if (intent.getData() != null) {
707             // Get the intent data and convert it to a string.
708             final Uri intentUriData = intent.getData();
709             formattedUrlString = intentUriData.toString();
710         }
711
712         // If formattedUrlString is null assign the homepage to it.
713         if (formattedUrlString == null) {
714             formattedUrlString = homepage;
715         }
716
717         // Load the initial website.
718         mainWebView.loadUrl(formattedUrlString, customHeaders);
719
720         // If the favorite icon is null, load the default.
721         if (favoriteIcon == null) {
722             // We have to use `ContextCompat` until API >= 21.
723             Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
724             BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
725             favoriteIcon = favoriteIconBitmapDrawable.getBitmap();
726         }
727
728         // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
729         inFullScreenBrowsingMode = false;
730
731         // Initialize AdView for the free flavor and request an ad.  If this is not the free flavor BannerAd.requestAd() does nothing.
732         adView = findViewById(R.id.adView);
733         BannerAd.requestAd(adView);
734     }
735
736
737     @Override
738     protected void onNewIntent(Intent intent) {
739         // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
740         setIntent(intent);
741
742         if (intent.getData() != null) {
743             // Get the intent data and convert it to a string.
744             final Uri intentUriData = intent.getData();
745             formattedUrlString = intentUriData.toString();
746         }
747
748         // Close the navigation drawer if it is open.
749         if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
750             drawerLayout.closeDrawer(GravityCompat.START);
751         }
752
753         // Load the website.
754         mainWebView.loadUrl(formattedUrlString, customHeaders);
755
756         // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
757         mainWebView.requestFocus();
758     }
759
760     @Override
761     public boolean onCreateOptionsMenu(Menu menu) {
762         // Inflate the menu; this adds items to the action bar if it is present.
763         getMenuInflater().inflate(R.menu.webview_options_menu, menu);
764
765         // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
766         mainMenu = menu;
767
768         // Set the initial status of the privacy icons.  `false` does not call `invalidateOptionsMenu` as the last step.
769         updatePrivacyIcons(false);
770
771         // Get handles for the menu items.
772         MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
773         MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
774         MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
775         MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
776
777         // Only display third-Party Cookies if SDK >= 21
778         toggleThirdPartyCookies.setVisible(Build.VERSION.SDK_INT >= 21);
779
780         // Get the shared preference values.  `this` references the current context.
781         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
782
783         // Set the status of the additional app bar icons.  The default is `false`.
784         if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
785             toggleFirstPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
786             toggleDomStorage.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
787             toggleSaveFormData.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
788         } else { //Do not display the additional icons.
789             toggleFirstPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
790             toggleDomStorage.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
791             toggleSaveFormData.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
792         }
793
794         return true;
795     }
796
797     @Override
798     public boolean onPrepareOptionsMenu(Menu menu) {
799         // Get handles for the menu items.
800         MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
801         MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
802         MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
803         MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
804         MenuItem clearCookies = menu.findItem(R.id.clearCookies);
805         MenuItem clearFormData = menu.findItem(R.id.clearFormData);
806         MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
807
808         // Set the status of the menu item checkboxes.
809         toggleFirstPartyCookies.setChecked(firstPartyCookiesEnabled);
810         toggleThirdPartyCookies.setChecked(thirdPartyCookiesEnabled);
811         toggleDomStorage.setChecked(domStorageEnabled);
812         toggleSaveFormData.setChecked(saveFormDataEnabled);
813
814         // Enable third-party cookies if first-party cookies are enabled.
815         toggleThirdPartyCookies.setEnabled(firstPartyCookiesEnabled);
816
817         // Enable DOM Storage if JavaScript is enabled.
818         toggleDomStorage.setEnabled(javaScriptEnabled);
819
820         // Enable Clear Cookies if there are any.
821         clearCookies.setEnabled(cookieManager.hasCookies());
822
823         // Enable Clear Form Data is there is any.
824         WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
825         clearFormData.setEnabled(mainWebViewDatabase.hasFormData());
826
827         // Only show `Refresh` if `swipeToRefresh` is disabled.
828         refreshMenuItem.setVisible(!swipeToRefreshEnabled);
829
830         // Initialize font size variables.
831         int fontSize = mainWebView.getSettings().getTextZoom();
832         String fontSizeTitle;
833         MenuItem selectedFontSizeMenuItem;
834
835         // Prepare the font size title and current size menu item.
836         switch (fontSize) {
837             case 50:
838                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.fifty_percent);
839                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeFiftyPercent);
840                 break;
841
842             case 75:
843                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.seventy_five_percent);
844                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeSeventyFivePercent);
845                 break;
846
847             case 100:
848                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
849                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
850                 break;
851
852             case 125:
853                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_twenty_five_percent);
854                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredTwentyFivePercent);
855                 break;
856
857             case 150:
858                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_fifty_percent);
859                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredFiftyPercent);
860                 break;
861
862             case 175:
863                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_seventy_five_percent);
864                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredSeventyFivePercent);
865                 break;
866
867             case 200:
868                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.two_hundred_percent);
869                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeTwoHundredPercent);
870                 break;
871
872             default:
873                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
874                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
875                 break;
876         }
877
878         // Set the font size title and select the current size menu item.
879         MenuItem fontSizeMenuItem = menu.findItem(R.id.fontSize);
880         fontSizeMenuItem.setTitle(fontSizeTitle);
881         selectedFontSizeMenuItem.setChecked(true);
882
883         // Run all the other default commands.
884         super.onPrepareOptionsMenu(menu);
885
886         // `return true` displays the menu.
887         return true;
888     }
889
890     @Override
891     // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
892     @SuppressLint("SetJavaScriptEnabled")
893     // removeAllCookies is deprecated, but it is required for API < 21.
894     @SuppressWarnings("deprecation")
895     public boolean onOptionsItemSelected(MenuItem menuItem) {
896         int menuItemId = menuItem.getItemId();
897
898         // Set the commands that relate to the menu entries.
899         switch (menuItemId) {
900             case R.id.toggleJavaScript:
901                 // Switch the status of javaScriptEnabled.
902                 javaScriptEnabled = !javaScriptEnabled;
903
904                 // Apply the new JavaScript status.
905                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
906
907                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
908                 updatePrivacyIcons(true);
909
910                 // Display a `Snackbar`.
911                 if (javaScriptEnabled) {  // JavaScrip is enabled.
912                     Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
913                 } else if (firstPartyCookiesEnabled) {  // JavaScript is disabled, but first-party cookies are enabled.
914                     Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
915                 } else {  // Privacy mode.
916                     Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
917                 }
918
919                 // Reload the WebView.
920                 mainWebView.reload();
921                 return true;
922
923             case R.id.toggleFirstPartyCookies:
924                 // Switch the status of firstPartyCookiesEnabled.
925                 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
926
927                 // Update the menu checkbox.
928                 menuItem.setChecked(firstPartyCookiesEnabled);
929
930                 // Apply the new cookie status.
931                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
932
933                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
934                 updatePrivacyIcons(true);
935
936                 // Display a `Snackbar`.
937                 if (firstPartyCookiesEnabled) {  // First-party cookies are enabled.
938                     Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
939                 } else if (javaScriptEnabled){  // JavaScript is still enabled.
940                     Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
941                 } else {  // Privacy mode.
942                     Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
943                 }
944
945                 // Reload the WebView.
946                 mainWebView.reload();
947                 return true;
948
949             case R.id.toggleThirdPartyCookies:
950                 if (Build.VERSION.SDK_INT >= 21) {
951                     // Switch the status of thirdPartyCookiesEnabled.
952                     thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
953
954                     // Update the menu checkbox.
955                     menuItem.setChecked(thirdPartyCookiesEnabled);
956
957                     // Apply the new cookie status.
958                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
959
960                     // Display a `Snackbar`.
961                     if (thirdPartyCookiesEnabled) {
962                         Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
963                     } else {
964                         Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
965                     }
966
967                     // Reload the WebView.
968                     mainWebView.reload();
969                 } // Else do nothing because SDK < 21.
970                 return true;
971
972             case R.id.toggleDomStorage:
973                 // Switch the status of domStorageEnabled.
974                 domStorageEnabled = !domStorageEnabled;
975
976                 // Update the menu checkbox.
977                 menuItem.setChecked(domStorageEnabled);
978
979                 // Apply the new DOM Storage status.
980                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
981
982                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
983                 updatePrivacyIcons(true);
984
985                 // Display a `Snackbar`.
986                 if (domStorageEnabled) {
987                     Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
988                 } else {
989                     Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
990                 }
991
992                 // Reload the WebView.
993                 mainWebView.reload();
994                 return true;
995
996             case R.id.toggleSaveFormData:
997                 // Switch the status of saveFormDataEnabled.
998                 saveFormDataEnabled = !saveFormDataEnabled;
999
1000                 // Update the menu checkbox.
1001                 menuItem.setChecked(saveFormDataEnabled);
1002
1003                 // Apply the new form data status.
1004                 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1005
1006                 // Display a `Snackbar`.
1007                 if (saveFormDataEnabled) {
1008                     Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1009                 } else {
1010                     Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1011                 }
1012
1013                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1014                 updatePrivacyIcons(true);
1015
1016                 // Reload the WebView.
1017                 mainWebView.reload();
1018                 return true;
1019
1020             case R.id.clearCookies:
1021                 if (Build.VERSION.SDK_INT < 21) {
1022                     cookieManager.removeAllCookie();
1023                 } else {
1024                     cookieManager.removeAllCookies(null);
1025                 }
1026                 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_deleted, Snackbar.LENGTH_SHORT).show();
1027                 return true;
1028
1029             case R.id.clearDomStorage:
1030                 WebStorage webStorage = WebStorage.getInstance();
1031                 webStorage.deleteAllData();
1032                 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_deleted, Snackbar.LENGTH_SHORT).show();
1033                 return true;
1034
1035             case R.id.clearFormData:
1036                 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1037                 mainWebViewDatabase.clearFormData();
1038                 Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_deleted, Snackbar.LENGTH_SHORT).show();
1039                 return true;
1040
1041             case R.id.fontSizeFiftyPercent:
1042                 mainWebView.getSettings().setTextZoom(50);
1043                 return true;
1044
1045             case R.id.fontSizeSeventyFivePercent:
1046                 mainWebView.getSettings().setTextZoom(75);
1047                 return true;
1048
1049             case R.id.fontSizeOneHundredPercent:
1050                 mainWebView.getSettings().setTextZoom(100);
1051                 return true;
1052
1053             case R.id.fontSizeOneHundredTwentyFivePercent:
1054                 mainWebView.getSettings().setTextZoom(125);
1055                 return true;
1056
1057             case R.id.fontSizeOneHundredFiftyPercent:
1058                 mainWebView.getSettings().setTextZoom(150);
1059                 return true;
1060
1061             case R.id.fontSizeOneHundredSeventyFivePercent:
1062                 mainWebView.getSettings().setTextZoom(175);
1063                 return true;
1064
1065             case R.id.fontSizeTwoHundredPercent:
1066                 mainWebView.getSettings().setTextZoom(200);
1067                 return true;
1068
1069             case R.id.find_on_page:
1070                 // Hide the URL app bar.
1071                 supportAppBar.setVisibility(View.GONE);
1072
1073                 // Show the Find on Page `RelativeLayout`.
1074                 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1075
1076                 // Display the keyboard.  We have to wait 200 ms before running the command to work around a bug in Android.
1077                 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1078                 findOnPageEditText.postDelayed(new Runnable()
1079                 {
1080                     @Override
1081                     public void run()
1082                     {
1083                         // Set the focus on `findOnPageEditText`.
1084                         findOnPageEditText.requestFocus();
1085
1086                         // Display the keyboard.
1087                         inputMethodManager.showSoftInput(findOnPageEditText, 0);
1088                     }
1089                 }, 200);
1090                 return true;
1091
1092             case R.id.share:
1093                 Intent shareIntent = new Intent();
1094                 shareIntent.setAction(Intent.ACTION_SEND);
1095                 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
1096                 shareIntent.setType("text/plain");
1097                 startActivity(Intent.createChooser(shareIntent, "Share URL"));
1098                 return true;
1099
1100             case R.id.addToHomescreen:
1101                 // Show the `CreateHomeScreenShortcut` `AlertDialog` and name this instance `R.string.create_shortcut`.
1102                 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcut();
1103                 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.create_shortcut));
1104
1105                 //Everything else will be handled by `CreateHomeScreenShortcut` and the associated listener below.
1106                 return true;
1107
1108             case R.id.print:
1109                 // Get a `PrintManager` instance.
1110                 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1111
1112                 // Convert `mainWebView` to `printDocumentAdapter`.
1113                 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
1114
1115                 // Print the document.  The print attributes are `null`.
1116                 printManager.print(getResources().getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1117                 return true;
1118
1119             case R.id.refresh:
1120                 mainWebView.reload();
1121                 return true;
1122
1123             default:
1124                 // Don't consume the event.
1125                 return super.onOptionsItemSelected(menuItem);
1126         }
1127     }
1128
1129     // removeAllCookies is deprecated, but it is required for API < 21.
1130     @SuppressWarnings("deprecation")
1131     @Override
1132     public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1133         int menuItemId = menuItem.getItemId();
1134
1135         switch (menuItemId) {
1136             case R.id.home:
1137                 mainWebView.loadUrl(homepage, customHeaders);
1138                 break;
1139
1140             case R.id.back:
1141                 if (mainWebView.canGoBack()) {
1142                     mainWebView.goBack();
1143                 }
1144                 break;
1145
1146             case R.id.forward:
1147                 if (mainWebView.canGoForward()) {
1148                     mainWebView.goForward();
1149                 }
1150                 break;
1151
1152             case R.id.history:
1153                 // Gte the `WebBackForwardList`.
1154                 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
1155
1156                 // Show the `UrlHistory` `AlertDialog` and name this instance `R.string.history`.  `this` is the `Context`.
1157                 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistory.loadBackForwardList(this, webBackForwardList);
1158                 urlHistoryDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.history));
1159                 break;
1160
1161             case R.id.bookmarks:
1162                 // Launch Bookmarks.
1163                 Intent bookmarksIntent = new Intent(this, Bookmarks.class);
1164                 startActivity(bookmarksIntent);
1165                 break;
1166
1167             case R.id.downloads:
1168                 // Launch the system Download Manager.
1169                 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1170
1171                 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1172                 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1173
1174                 startActivity(downloadManagerIntent);
1175                 break;
1176
1177             case R.id.settings:
1178                 // Launch `Settings`.
1179                 Intent settingsIntent = new Intent(this, Settings.class);
1180                 startActivity(settingsIntent);
1181                 break;
1182
1183             /*
1184             case R.id.domains:
1185                 // Launch `DomainsList`.
1186                 Intent domainsIntent = new Intent(this, DomainsList.class);
1187                 startActivity(domainsIntent);
1188                 break;
1189             */
1190
1191             case R.id.guide:
1192                 // Launch `Guide`.
1193                 Intent guideIntent = new Intent(this, Guide.class);
1194                 startActivity(guideIntent);
1195                 break;
1196
1197             case R.id.about:
1198                 // Launch `About`.
1199                 Intent aboutIntent = new Intent(this, About.class);
1200                 startActivity(aboutIntent);
1201                 break;
1202
1203             case R.id.clearAndExit:
1204                 // Clear cookies.  The commands changed slightly in API 21.
1205                 if (Build.VERSION.SDK_INT >= 21) {
1206                     cookieManager.removeAllCookies(null);
1207                 } else {
1208                     cookieManager.removeAllCookie();
1209                 }
1210
1211                 // Clear DOM storage.
1212                 WebStorage domStorage = WebStorage.getInstance();
1213                 domStorage.deleteAllData();
1214
1215                 // Clear form data.
1216                 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1217                 webViewDatabase.clearFormData();
1218
1219                 // Clear cache.  The argument of "true" includes disk files.
1220                 mainWebView.clearCache(true);
1221
1222                 // Clear the back/forward history.
1223                 mainWebView.clearHistory();
1224
1225                 // Clear any SSL certificate preferences.
1226                 mainWebView.clearSslPreferences();
1227
1228                 // Clear `formattedUrlString`.
1229                 formattedUrlString = null;
1230
1231                 // Clear `customHeaders`.
1232                 customHeaders.clear();
1233
1234                 // Detach all views from `mainWebViewRelativeLayout`.
1235                 mainWebViewRelativeLayout.removeAllViews();
1236
1237                 // Destroy the internal state of `mainWebView`.
1238                 mainWebView.destroy();
1239
1240                 // Manually delete the `app_webview` folder, which contains an additional `WebView` cache.  See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
1241                 Runtime runtime = Runtime.getRuntime();
1242                 String dataDirString = getApplicationInfo().dataDir;  // `dataDir` will vary, but will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
1243                 try {
1244                     runtime.exec("rm -rf " + dataDirString + "/app_webview");
1245                 } catch (IOException e) {
1246                     // Do nothing if the files do not exist.
1247                 }
1248
1249                 // Close Privacy Browser.  `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
1250                 if (Build.VERSION.SDK_INT >= 21) {
1251                     finishAndRemoveTask();
1252                 } else {
1253                     finish();
1254                 }
1255
1256                 // Remove the terminated program from RAM.  The status code is `0`.
1257                 System.exit(0);
1258                 break;
1259
1260             default:
1261                 break;
1262         }
1263
1264         // Close the navigation drawer.
1265         drawerLayout.closeDrawer(GravityCompat.START);
1266         return true;
1267     }
1268
1269     @Override
1270     public void onPostCreate(Bundle savedInstanceState) {
1271         super.onPostCreate(savedInstanceState);
1272
1273         // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
1274         drawerToggle.syncState();
1275     }
1276
1277     @Override
1278     public void onConfigurationChanged(Configuration newConfig) {
1279         super.onConfigurationChanged(newConfig);
1280
1281         // Reload the ad for the free flavor if we are not in full screen mode.
1282         if (BuildConfig.FLAVOR.contentEquals("free") && adView.isShown() && !fullScreenVideoFrameLayout.isShown()) {
1283             // Reload the ad.
1284             BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1285
1286             // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1287             adView = findViewById(R.id.adView);
1288         }
1289
1290         // `invalidateOptionsMenu` should recalculate the number of action buttons from the menu to display on the app bar, but it doesn't because of the this bug:  https://code.google.com/p/android/issues/detail?id=20493#c8
1291         // ActivityCompat.invalidateOptionsMenu(this);
1292     }
1293
1294     @Override
1295     public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
1296         // Store the `HitTestResult`.
1297         final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
1298
1299         // Create strings.
1300         final String imageUrl;
1301         final String linkUrl;
1302
1303         // Get a handle for the `ClipboardManager`.
1304         final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
1305
1306         switch (hitTestResult.getType()) {
1307             // `SRC_ANCHOR_TYPE` is a link.
1308             case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1309                 // Get the target URL.
1310                 linkUrl = hitTestResult.getExtra();
1311
1312                 // Set the target URL as the title of the `ContextMenu`.
1313                 menu.setHeaderTitle(linkUrl);
1314
1315                 // Add a `Load URL` entry.
1316                 menu.add(R.string.load_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1317                     @Override
1318                     public boolean onMenuItemClick(MenuItem item) {
1319                         mainWebView.loadUrl(linkUrl, customHeaders);
1320                         return false;
1321                     }
1322                 });
1323
1324                 // Add a `Copy URL` entry.
1325                 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1326                     @Override
1327                     public boolean onMenuItemClick(MenuItem item) {
1328                         // Save the link URL in a `ClipData`.
1329                         ClipData srcAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), linkUrl);
1330
1331                         // Set the `ClipData` as the clipboard's primary clip.
1332                         clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
1333                         return false;
1334                     }
1335                 });
1336
1337                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1338                 menu.add(R.string.cancel);
1339                 break;
1340
1341             case WebView.HitTestResult.EMAIL_TYPE:
1342                 // Get the target URL.
1343                 linkUrl = hitTestResult.getExtra();
1344
1345                 // Set the target URL as the title of the `ContextMenu`.
1346                 menu.setHeaderTitle(linkUrl);
1347
1348                 // Add a `Write Email` entry.
1349                 menu.add(R.string.write_email).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1350                     @Override
1351                     public boolean onMenuItemClick(MenuItem item) {
1352                         // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1353                         Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1354
1355                         // Parse the url and set it as the data for the `Intent`.
1356                         emailIntent.setData(Uri.parse("mailto:" + linkUrl));
1357
1358                         // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
1359                         emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1360
1361                         // Make it so.
1362                         startActivity(emailIntent);
1363                         return false;
1364                     }
1365                 });
1366
1367                 // Add a `Copy Email Address` entry.
1368                 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1369                     @Override
1370                     public boolean onMenuItemClick(MenuItem item) {
1371                         // Save the email address in a `ClipData`.
1372                         ClipData srcEmailTypeClipData = ClipData.newPlainText(getResources().getString(R.string.email_address), linkUrl);
1373
1374                         // Set the `ClipData` as the clipboard's primary clip.
1375                         clipboardManager.setPrimaryClip(srcEmailTypeClipData);
1376                         return false;
1377                     }
1378                 });
1379
1380                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1381                 menu.add(R.string.cancel);
1382                 break;
1383
1384             // `IMAGE_TYPE` is an image.
1385             case WebView.HitTestResult.IMAGE_TYPE:
1386                 // Get the image URL.
1387                 imageUrl = hitTestResult.getExtra();
1388
1389                 // Set the image URL as the title of the `ContextMenu`.
1390                 menu.setHeaderTitle(imageUrl);
1391
1392                 // Add a `View Image` entry.
1393                 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1394                     @Override
1395                     public boolean onMenuItemClick(MenuItem item) {
1396                         mainWebView.loadUrl(imageUrl, customHeaders);
1397                         return false;
1398                     }
1399                 });
1400
1401                 // Add a `Download Image` entry.
1402                 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1403                     @Override
1404                     public boolean onMenuItemClick(MenuItem item) {
1405                         // Show the `DownloadImage` `AlertDialog` and name this instance `@string/download`.
1406                         AppCompatDialogFragment downloadImageDialogFragment = DownloadImage.imageUrl(imageUrl);
1407                         downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1408                         return false;
1409                     }
1410                 });
1411
1412                 // Add a `Copy URL` entry.
1413                 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1414                     @Override
1415                     public boolean onMenuItemClick(MenuItem item) {
1416                         // Save the image URL in a `ClipData`.
1417                         ClipData srcImageTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1418
1419                         // Set the `ClipData` as the clipboard's primary clip.
1420                         clipboardManager.setPrimaryClip(srcImageTypeClipData);
1421                         return false;
1422                     }
1423                 });
1424
1425                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1426                 menu.add(R.string.cancel);
1427                 break;
1428
1429
1430             // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
1431             case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1432                 // Get the image URL.
1433                 imageUrl = hitTestResult.getExtra();
1434
1435                 // Set the image URL as the title of the `ContextMenu`.
1436                 menu.setHeaderTitle(imageUrl);
1437
1438                 // Add a `View Image` entry.
1439                 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1440                     @Override
1441                     public boolean onMenuItemClick(MenuItem item) {
1442                         mainWebView.loadUrl(imageUrl, customHeaders);
1443                         return false;
1444                     }
1445                 });
1446
1447                 // Add a `Download Image` entry.
1448                 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1449                     @Override
1450                     public boolean onMenuItemClick(MenuItem item) {
1451                         // Show the `DownloadImage` `AlertDialog` and name this instance `@string/download`.
1452                         AppCompatDialogFragment downloadImageDialogFragment = DownloadImage.imageUrl(imageUrl);
1453                         downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1454                         return false;
1455                     }
1456                 });
1457
1458                 // Add a `Copy URL` entry.
1459                 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1460                     @Override
1461                     public boolean onMenuItemClick(MenuItem item) {
1462                         // Save the image URL in a `ClipData`.
1463                         ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1464
1465                         // Set the `ClipData` as the clipboard's primary clip.
1466                         clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
1467                         return false;
1468                     }
1469                 });
1470
1471                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1472                 menu.add(R.string.cancel);
1473                 break;
1474         }
1475     }
1476
1477     @Override
1478     public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
1479         // Get shortcutNameEditText from the alert dialog.
1480         EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
1481
1482         // Create the bookmark shortcut based on formattedUrlString.
1483         Intent bookmarkShortcut = new Intent();
1484         bookmarkShortcut.setAction(Intent.ACTION_VIEW);
1485         bookmarkShortcut.setData(Uri.parse(formattedUrlString));
1486
1487         // Place the bookmark shortcut on the home screen.
1488         Intent placeBookmarkShortcut = new Intent();
1489         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
1490         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
1491         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
1492         placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
1493         sendBroadcast(placeBookmarkShortcut);
1494     }
1495
1496     @Override
1497     public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
1498         // Download the image if it has an HTTP or HTTPS URI.
1499         if (imageUrl.startsWith("http")) {
1500             // Get a handle for the system `DOWNLOAD_SERVICE`.
1501             DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
1502
1503             // Parse `imageUrl`.
1504             DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
1505
1506             // Pass cookies to download manager if cookies are enabled.  This is required to download images from websites that require a login.
1507             if (firstPartyCookiesEnabled) {
1508                 // Get the cookies for `imageUrl`.
1509                 String cookies = cookieManager.getCookie(imageUrl);
1510
1511                 // Add the cookies to `downloadRequest`.  In the HTTP request header, cookies are named `Cookie`.
1512                 downloadRequest.addRequestHeader("Cookie", cookies);
1513             }
1514
1515             // Get the file name from `dialogFragment`.
1516             EditText downloadImageNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_image_name);
1517             String imageName = downloadImageNameEditText.getText().toString();
1518
1519             // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
1520             if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `imageName`.
1521                 downloadRequest.setDestinationInExternalFilesDir(this, "/", imageName);
1522             } else { // Only set the title using `imageName`.
1523                 downloadRequest.setTitle(imageName);
1524             }
1525
1526             // Allow `MediaScanner` to index the download if it is a media file.
1527             downloadRequest.allowScanningByMediaScanner();
1528
1529             // Add the URL as the description for the download.
1530             downloadRequest.setDescription(imageUrl);
1531
1532             // Show the download notification after the download is completed.
1533             downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
1534
1535             // Initiate the download.
1536             downloadManager.enqueue(downloadRequest);
1537         } else {  // The image is not an HTTP or HTTPS URI.
1538             Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
1539         }
1540     }
1541
1542     @Override
1543     public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
1544         // Download the file if it has an HTTP or HTTPS URI.
1545         if (downloadUrl.startsWith("http")) {
1546
1547             // Get a handle for the system `DOWNLOAD_SERVICE`.
1548             DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
1549
1550             // Parse `downloadUrl`.
1551             DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
1552
1553             // Pass cookies to download manager if cookies are enabled.  This is required to download files from websites that require a login.
1554             if (firstPartyCookiesEnabled) {
1555                 // Get the cookies for `downloadUrl`.
1556                 String cookies = cookieManager.getCookie(downloadUrl);
1557
1558                 // Add the cookies to `downloadRequest`.  In the HTTP request header, cookies are named `Cookie`.
1559                 downloadRequest.addRequestHeader("Cookie", cookies);
1560             }
1561
1562             // Get the file name from `dialogFragment`.
1563             EditText downloadFileNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_file_name);
1564             String fileName = downloadFileNameEditText.getText().toString();
1565
1566             // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
1567             if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download location to `/sdcard/Android/data/com.stoutner.privacybrowser.standard/files` named `fileName`.
1568                 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
1569             } else { // Only set the title using `fileName`.
1570                 downloadRequest.setTitle(fileName);
1571             }
1572
1573             // Allow `MediaScanner` to index the download if it is a media file.
1574             downloadRequest.allowScanningByMediaScanner();
1575
1576             // Add the URL as the description for the download.
1577             downloadRequest.setDescription(downloadUrl);
1578
1579             // Show the download notification after the download is completed.
1580             downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
1581
1582             // Initiate the download.
1583             downloadManager.enqueue(downloadRequest);
1584         } else {  // The download is not an HTTP or HTTPS URI.
1585             Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
1586         }
1587     }
1588
1589     public void viewSslCertificate(View view) {
1590         // Show the `ViewSslCertificate` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
1591         DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificate();
1592         viewSslCertificateDialogFragment.show(getFragmentManager(), getResources().getString(R.string.view_ssl_certificate));
1593     }
1594
1595     @Override
1596     public void onSslErrorCancel() {
1597         sslErrorHandler.cancel();
1598     }
1599
1600     @Override
1601     public void onSslErrorProceed() {
1602         sslErrorHandler.proceed();
1603     }
1604
1605     @Override
1606     public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
1607         // Load the history entry.
1608         mainWebView.goBackOrForward(moveBackOrForwardSteps);
1609     }
1610
1611     @Override
1612     public void onClearHistory() {
1613         // Clear the history.
1614         mainWebView.clearHistory();
1615     }
1616
1617     // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
1618     @Override
1619     public void onBackPressed() {
1620         // Close the navigation drawer if it is available.  GravityCompat.START is the drawer on the left on Left-to-Right layout text.
1621         if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1622             drawerLayout.closeDrawer(GravityCompat.START);
1623         } else {
1624             // Load the previous URL if available.
1625             if (mainWebView.canGoBack()) {
1626                 mainWebView.goBack();
1627             } else {
1628                 // Pass `onBackPressed()` to the system.
1629                 super.onBackPressed();
1630             }
1631         }
1632     }
1633
1634     @Override
1635     public void onPause() {
1636         // Pause `mainWebView`.
1637         mainWebView.onPause();
1638
1639         // Stop all JavaScript.
1640         mainWebView.pauseTimers();
1641
1642         // Pause the adView or it will continue to consume resources in the background on the free flavor.
1643         if (BuildConfig.FLAVOR.contentEquals("free")) {
1644             BannerAd.pauseAd(adView);
1645         }
1646
1647         super.onPause();
1648     }
1649
1650     @Override
1651     public void onResume() {
1652         super.onResume();
1653
1654         // Resume JavaScript (if enabled).
1655         mainWebView.resumeTimers();
1656
1657         // Resume `mainWebView`.
1658         mainWebView.onResume();
1659
1660         // Resume the adView for the free flavor.
1661         if (BuildConfig.FLAVOR.contentEquals("free")) {
1662             BannerAd.resumeAd(adView);
1663         }
1664     }
1665
1666     @Override
1667     public void onRestart() {
1668         super.onRestart();
1669
1670         // Apply the settings from shared preferences, which might have been changed in `Settings`.
1671         applySettings();
1672
1673         // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1674         updatePrivacyIcons(true);
1675
1676     }
1677
1678     private void loadUrlFromTextBox() throws UnsupportedEncodingException {
1679         // Get the text from urlTextBox and convert it to a string.  trim() removes white spaces from the beginning and end of the string.
1680         String unformattedUrlString = urlTextBox.getText().toString().trim();
1681
1682         URL unformattedUrl = null;
1683         Uri.Builder formattedUri = new Uri.Builder();
1684
1685         // Check to see if unformattedUrlString is a valid URL.  Otherwise, convert it into a Duck Duck Go search.
1686         if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
1687             // Add http:// at the beginning if it is missing.  Otherwise the app will segfault.
1688             if (!unformattedUrlString.startsWith("http")) {
1689                 unformattedUrlString = "http://" + unformattedUrlString;
1690             }
1691
1692             // Convert unformattedUrlString to a URL, then to a URI, and then back to a string, which sanitizes the input and adds in any missing components.
1693             try {
1694                 unformattedUrl = new URL(unformattedUrlString);
1695             } catch (MalformedURLException e) {
1696                 e.printStackTrace();
1697             }
1698
1699             // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
1700             final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
1701             final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
1702             final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
1703             final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
1704             final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
1705
1706             formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
1707             formattedUrlString = formattedUri.build().toString();
1708         } else {
1709             // Sanitize the search input and convert it to a DuckDuckGo search.
1710             final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
1711
1712             // Use the correct search URL.
1713             if (javaScriptEnabled) {  // JavaScript is enabled.
1714                 formattedUrlString = javaScriptEnabledSearchURL + encodedUrlString;
1715             } else { // JavaScript is disabled.
1716                 formattedUrlString = javaScriptDisabledSearchURL + encodedUrlString;
1717             }
1718         }
1719
1720         mainWebView.loadUrl(formattedUrlString, customHeaders);
1721
1722         // Hide the keyboard so we can see the webpage.  `0` indicates no additional flags.
1723         inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1724     }
1725
1726     public void findPreviousOnPage(View view) {
1727         // Go to the previous highlighted phrase on the page.  `false` goes backwards instead of forwards.
1728         mainWebView.findNext(false);
1729     }
1730
1731     public void findNextOnPage(View view) {
1732         // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
1733         mainWebView.findNext(true);
1734     }
1735
1736     public void closeFindOnPage(View view) {
1737         // Delete the contents of `find_on_page_edittext`.
1738         findOnPageEditText.setText(null);
1739
1740         // Clear the highlighted phrases.
1741         mainWebView.clearMatches();
1742
1743         // Hide the Find on Page `RelativeLayout`.
1744         findOnPageLinearLayout.setVisibility(View.GONE);
1745
1746         // Show the URL app bar.
1747         supportAppBar.setVisibility(View.VISIBLE);
1748
1749         // Hide the keyboard so we can see the webpage.  `0` indicates no additional flags.
1750         inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1751     }
1752
1753     private void applySettings() {
1754         // Get the shared preference values.  `this` references the current context.
1755         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1756
1757         // Store the values from `sharedPreferences` in variables.
1758         String userAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
1759         String customUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
1760         String javaScriptDisabledSearchString = sharedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=");
1761         String javaScriptDisabledCustomSearchString = sharedPreferences.getString("javascript_disabled_search_custom_url", "");
1762         String javaScriptEnabledSearchString = sharedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=");
1763         String javaScriptEnabledCustomSearchString = sharedPreferences.getString("javascript_enabled_search_custom_url", "");
1764         String homepageString = sharedPreferences.getString("homepage", "https://www.duckduckgo.com");
1765         String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
1766         swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh_enabled", false);
1767         adBlockerEnabled = sharedPreferences.getBoolean("block_ads", true);
1768         boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
1769         boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
1770         fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("enable_full_screen_browsing_mode", false);
1771         hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
1772         translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
1773
1774         // Because they can be modified on-the-fly by the user, these default settings are only applied when the program first runs.
1775         if (javaScriptEnabled == null) {  // If `javaScriptEnabled` is null the program is just starting.
1776             // Get the values from `sharedPreferences`.
1777             javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
1778             firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
1779             thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
1780             domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
1781             saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
1782
1783             // Apply the default settings.
1784             mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1785             cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1786             mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1787             mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1788             mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
1789
1790             // Set third-party cookies status if API >= 21.
1791             if (Build.VERSION.SDK_INT >= 21) {
1792                 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1793             }
1794         }
1795
1796         // Apply the other settings from `sharedPreferences`.
1797         homepage = homepageString;
1798         swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
1799
1800         // Set the user agent initial status.
1801         switch (userAgentString) {
1802             case "Default user agent":
1803                 // Set the user agent to `""`, which uses the default value.
1804                 mainWebView.getSettings().setUserAgentString("");
1805                 break;
1806
1807             case "Custom user agent":
1808                 // Set the custom user agent.
1809                 mainWebView.getSettings().setUserAgentString(customUserAgentString);
1810                 break;
1811
1812             default:
1813                 // Use the selected user agent.
1814                 mainWebView.getSettings().setUserAgentString(userAgentString);
1815                 break;
1816         }
1817
1818         // Set JavaScript disabled search.
1819         if (javaScriptDisabledSearchString.equals("Custom URL")) {  // Get the custom URL string.
1820             javaScriptDisabledSearchURL = javaScriptDisabledCustomSearchString;
1821         } else {  // Use the string from the pre-built list.
1822             javaScriptDisabledSearchURL = javaScriptDisabledSearchString;
1823         }
1824
1825         // Set JavaScript enabled search.
1826         if (javaScriptEnabledSearchString.equals("Custom URL")) {  // Get the custom URL string.
1827             javaScriptEnabledSearchURL = javaScriptEnabledCustomSearchString;
1828         } else {  // Use the string from the pre-built list.
1829             javaScriptEnabledSearchURL = javaScriptEnabledSearchString;
1830         }
1831
1832         // Set Do Not Track status.
1833         if (doNotTrackEnabled) {
1834             customHeaders.put("DNT", "1");
1835         } else {
1836             customHeaders.remove("DNT");
1837         }
1838
1839         // Set Orbot proxy status.
1840         if (proxyThroughOrbot) {
1841             // Set the proxy.  `this` refers to the current activity where an `AlertDialog` might be displayed.
1842             OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
1843         } else {  // Reset the proxy to default.  The host is `""` and the port is `"0"`.
1844             OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
1845         }
1846
1847         // If we are in full screen mode update the `SYSTEM_UI` flags.
1848         if (inFullScreenBrowsingMode) {
1849             if (hideSystemBarsOnFullscreen) {  // Hide everything.
1850                 // Remove the translucent navigation setting if it is currently flagged.
1851                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1852
1853                 // Remove the translucent status bar overlay.
1854                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1855
1856                 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1857                 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1858
1859                 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1860                  * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1861                  * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
1862                  */
1863                 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1864             } else {  // Hide everything except the status and navigation bars.
1865                 // Add the translucent status flag if it is unset.
1866                 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1867
1868                 if (translucentNavigationBarOnFullscreen) {
1869                     // Set the navigation bar to be translucent.
1870                     getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1871                 } else {
1872                     // Set the navigation bar to be black.
1873                     getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1874                 }
1875             }
1876         }
1877     }
1878
1879     private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
1880         // Get handles for the icons.
1881         MenuItem privacyIcon = mainMenu.findItem(R.id.toggleJavaScript);
1882         MenuItem firstPartyCookiesIcon = mainMenu.findItem(R.id.toggleFirstPartyCookies);
1883         MenuItem domStorageIcon = mainMenu.findItem(R.id.toggleDomStorage);
1884         MenuItem formDataIcon = mainMenu.findItem(R.id.toggleSaveFormData);
1885
1886         // Update `privacyIcon`.
1887         if (javaScriptEnabled) {  // JavaScript is enabled.
1888             privacyIcon.setIcon(R.drawable.javascript_enabled);
1889         } else if (firstPartyCookiesEnabled) {  // JavaScript is disabled but cookies are enabled.
1890             privacyIcon.setIcon(R.drawable.warning);
1891         } else {  // All the dangerous features are disabled.
1892             privacyIcon.setIcon(R.drawable.privacy_mode);
1893         }
1894
1895         // Update `firstPartyCookiesIcon`.
1896         if (firstPartyCookiesEnabled) {  // First-party cookies are enabled.
1897             firstPartyCookiesIcon.setIcon(R.drawable.cookies_enabled);
1898         } else {  // First-party cookies are disabled.
1899             firstPartyCookiesIcon.setIcon(R.drawable.cookies_disabled);
1900         }
1901
1902         // Update `domStorageIcon`.
1903         if (javaScriptEnabled && domStorageEnabled) {  // Both JavaScript and DOM storage are enabled.
1904             domStorageIcon.setIcon(R.drawable.dom_storage_enabled);
1905         } else if (javaScriptEnabled) {  // JavaScript is enabled but DOM storage is disabled.
1906             domStorageIcon.setIcon(R.drawable.dom_storage_disabled);
1907         } else {  // JavaScript is disabled, so DOM storage is ghosted.
1908             domStorageIcon.setIcon(R.drawable.dom_storage_ghosted);
1909         }
1910
1911         // Update `formDataIcon`.
1912         if (saveFormDataEnabled) {  // Form data is enabled.
1913             formDataIcon.setIcon(R.drawable.form_data_enabled);
1914         } else {  // Form data is disabled.
1915             formDataIcon.setIcon(R.drawable.form_data_disabled);
1916         }
1917
1918         // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.  `this` references the current activity.
1919         if (runInvalidateOptionsMenu) {
1920             ActivityCompat.invalidateOptionsMenu(this);
1921         }
1922     }
1923 }