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