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