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