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