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