Remove Torch from the list of recommended Tor search engines. Fixes https://redmine...
[PrivacyBrowser.git] / app / src / main / java / com / stoutner / privacybrowser / activities / MainWebViewActivity.java
1 /*
2  * Copyright 2015-2017 Soren Stoutner <soren@stoutner.com>.
3  *
4  * Download cookie code contributed 2017 Hendrik Knackstedt.  Copyright assigned to Soren Stoutner <soren@stoutner.com>.
5  *
6  * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
7  *
8  * Privacy Browser is free software: you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation, either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * Privacy Browser is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with Privacy Browser.  If not, see <http://www.gnu.org/licenses/>.
20  */
21
22 package com.stoutner.privacybrowser.activities;
23
24 import android.annotation.SuppressLint;
25 import android.app.DialogFragment;
26 import android.app.DownloadManager;
27 import android.content.BroadcastReceiver;
28 import android.content.ClipData;
29 import android.content.ClipboardManager;
30 import android.content.Context;
31 import android.content.Intent;
32 import android.content.IntentFilter;
33 import android.content.SharedPreferences;
34 import android.content.res.Configuration;
35 import android.database.Cursor;
36 import android.graphics.Bitmap;
37 import android.graphics.drawable.BitmapDrawable;
38 import android.graphics.drawable.Drawable;
39 import android.net.Uri;
40 import android.net.http.SslCertificate;
41 import android.net.http.SslError;
42 import android.os.Build;
43 import android.os.Bundle;
44 import android.preference.PreferenceManager;
45 import android.print.PrintDocumentAdapter;
46 import android.print.PrintManager;
47 import android.support.annotation.NonNull;
48 import android.support.design.widget.CoordinatorLayout;
49 import android.support.design.widget.NavigationView;
50 import android.support.design.widget.Snackbar;
51 import android.support.v4.app.ActivityCompat;
52 import android.support.v4.content.ContextCompat;
53 import android.support.v4.view.GravityCompat;
54 import android.support.v4.widget.DrawerLayout;
55 import android.support.v4.widget.SwipeRefreshLayout;
56 import android.support.v7.app.ActionBar;
57 import android.support.v7.app.ActionBarDrawerToggle;
58 import android.support.v7.app.AppCompatActivity;
59 import android.support.v7.app.AppCompatDialogFragment;
60 import android.support.v7.widget.Toolbar;
61 import android.text.Editable;
62 import android.text.TextWatcher;
63 import android.util.Patterns;
64 import android.view.ContextMenu;
65 import android.view.GestureDetector;
66 import android.view.KeyEvent;
67 import android.view.Menu;
68 import android.view.MenuItem;
69 import android.view.MotionEvent;
70 import android.view.View;
71 import android.view.WindowManager;
72 import android.view.inputmethod.InputMethodManager;
73 import android.webkit.CookieManager;
74 import android.webkit.DownloadListener;
75 import android.webkit.SslErrorHandler;
76 import android.webkit.WebBackForwardList;
77 import android.webkit.WebChromeClient;
78 import android.webkit.WebResourceResponse;
79 import android.webkit.WebStorage;
80 import android.webkit.WebView;
81 import android.webkit.WebViewClient;
82 import android.webkit.WebViewDatabase;
83 import android.widget.EditText;
84 import android.widget.FrameLayout;
85 import android.widget.ImageView;
86 import android.widget.LinearLayout;
87 import android.widget.ProgressBar;
88 import android.widget.RelativeLayout;
89 import android.widget.TextView;
90
91 import com.stoutner.privacybrowser.BannerAd;
92 import com.stoutner.privacybrowser.BuildConfig;
93 import com.stoutner.privacybrowser.R;
94 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
95 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
96 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
97 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
98 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
99 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
100 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
101 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
102
103 import java.io.BufferedReader;
104 import java.io.ByteArrayInputStream;
105 import java.io.IOException;
106 import java.io.InputStreamReader;
107 import java.io.UnsupportedEncodingException;
108 import java.net.MalformedURLException;
109 import java.net.URL;
110 import java.net.URLDecoder;
111 import java.net.URLEncoder;
112 import java.util.HashMap;
113 import java.util.HashSet;
114 import java.util.Map;
115 import java.util.Set;
116
117 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
118 public class MainWebViewActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, CreateHomeScreenShortcutDialog.CreateHomeScreenSchortcutListener,
119         SslCertificateErrorDialog.SslCertificateErrorListener, DownloadFileDialog.DownloadFileListener, DownloadImageDialog.DownloadImageListener, UrlHistoryDialog.UrlHistoryListener {
120
121     // `appBar` is public static so it can be accessed from `OrbotProxyHelper`.  It is also used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applyAppSettings()`.
122     public static ActionBar appBar;
123
124     // `favoriteIconBitmap` is public static so it can be accessed from `CreateHomeScreenShortcutDialog`, `BookmarksActivity`, `CreateBookmarkDialog`, `CreateBookmarkFolderDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`, `ViewSslCertificateDialog`.
125     // It is also used in `onCreate()`, `onCreateHomeScreenShortcutCreate()`, and `applyDomainSettings`.
126     public static Bitmap favoriteIconBitmap;
127
128     // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`, `CreateBookmarkDialog`, and `AddDomainDialog`.
129     // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
130     public static String formattedUrlString;
131
132     // `sslCertificate` is public static so it can be accessed from `ViewSslCertificateDialog`.  It is also used in `onCreate()`.
133     public static SslCertificate sslCertificate;
134
135     // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`.  It is also used in `onCreate()`.
136     public static String orbotStatus;
137
138     // `webViewTitle` is public static so it can be accessed from `CreateBookmarkDialog` and `CreateHomeScreenShortcutDialog`.  It is also used in `onCreate()`.
139     public static String webViewTitle;
140
141
142     // `navigatingHistory` is used in `onCreate()`, `onNavigationItemSelected()`, and `applyDomainSettings()`.
143     private boolean navigatingHistory;
144
145     // `favoriteIconDefaultBitmap` is used in `onCreate()` and `applyDomainSettings`.
146     private Bitmap favoriteIconDefaultBitmap;
147
148     // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, and `onBackPressed()`.
149     private DrawerLayout drawerLayout;
150
151     // `rootCoordinatorLayout` is used in `onCreate()` and `applyAppSettings()`.
152     private CoordinatorLayout rootCoordinatorLayout;
153
154     // 'mainWebView' is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`, `findNextOnPage()`, `closeFindOnPage()`, and `loadUrlFromTextBox()`.
155     private WebView mainWebView;
156
157     // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
158     private FrameLayout fullScreenVideoFrameLayout;
159
160     // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu`, and `onRestart()`.
161     private SwipeRefreshLayout swipeRefreshLayout;
162
163     // `urlAppBarRelativeLayout` is used in `onCreate()` and `applyDomainSettings()`.
164     private RelativeLayout urlAppBarRelativeLayout;
165
166     // `favoriteIconImageView` is used in `onCreate()` and `applyDomainSettings()`
167     private ImageView favoriteIconImageView;
168
169     // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `loadUrlFromTextBox()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
170     private CookieManager cookieManager;
171
172     // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
173     private final Map<String, String> customHeaders = new HashMap<>();
174
175     // `javaScriptEnabled` is also used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `applyAppSettings()`.
176     // It is `Boolean` instead of `boolean` because `applyAppSettings()` needs to know if it is `null`.
177     private Boolean javaScriptEnabled;
178
179     // `firstPartyCookiesEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applyAppSettings()`.
180     private boolean firstPartyCookiesEnabled;
181
182     // `thirdPartyCookiesEnabled` used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
183     private boolean thirdPartyCookiesEnabled;
184
185     // `domStorageEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
186     private boolean domStorageEnabled;
187
188     // `saveFormDataEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
189     private boolean saveFormDataEnabled;
190
191     // `swipeToRefreshEnabled` is used in `onPrepareOptionsMenu()` and `applyAppSettings()`.
192     private boolean swipeToRefreshEnabled;
193
194     // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applyAppSettings()`.
195     private String homepage;
196
197     // `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 50:
991                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.fifty_percent);
992                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeFiftyPercent);
993                 break;
994
995             case 75:
996                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.seventy_five_percent);
997                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeSeventyFivePercent);
998                 break;
999
1000             case 100:
1001                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
1002                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
1003                 break;
1004
1005             case 125:
1006                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_twenty_five_percent);
1007                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredTwentyFivePercent);
1008                 break;
1009
1010             case 150:
1011                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_fifty_percent);
1012                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredFiftyPercent);
1013                 break;
1014
1015             case 175:
1016                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_seventy_five_percent);
1017                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredSeventyFivePercent);
1018                 break;
1019
1020             case 200:
1021                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.two_hundred_percent);
1022                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeTwoHundredPercent);
1023                 break;
1024
1025             default:
1026                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
1027                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
1028                 break;
1029         }
1030
1031         // Set the font size title and select the current size menu item.
1032         MenuItem fontSizeMenuItem = menu.findItem(R.id.fontSize);
1033         fontSizeMenuItem.setTitle(fontSizeTitle);
1034         selectedFontSizeMenuItem.setChecked(true);
1035
1036         // Run all the other default commands.
1037         super.onPrepareOptionsMenu(menu);
1038
1039         // `return true` displays the menu.
1040         return true;
1041     }
1042
1043     @Override
1044     // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1045     @SuppressLint("SetJavaScriptEnabled")
1046     // removeAllCookies is deprecated, but it is required for API < 21.
1047     @SuppressWarnings("deprecation")
1048     public boolean onOptionsItemSelected(MenuItem menuItem) {
1049         int menuItemId = menuItem.getItemId();
1050
1051         // Set the commands that relate to the menu entries.
1052         switch (menuItemId) {
1053             case R.id.toggleJavaScript:
1054                 // Switch the status of javaScriptEnabled.
1055                 javaScriptEnabled = !javaScriptEnabled;
1056
1057                 // Apply the new JavaScript status.
1058                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1059
1060                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1061                 updatePrivacyIcons(true);
1062
1063                 // Display a `Snackbar`.
1064                 if (javaScriptEnabled) {  // JavaScrip is enabled.
1065                     Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1066                 } else if (firstPartyCookiesEnabled) {  // JavaScript is disabled, but first-party cookies are enabled.
1067                     Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1068                 } else {  // Privacy mode.
1069                     Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1070                 }
1071
1072                 // Reload the WebView.
1073                 mainWebView.reload();
1074                 return true;
1075
1076             case R.id.toggleFirstPartyCookies:
1077                 // Switch the status of firstPartyCookiesEnabled.
1078                 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1079
1080                 // Update the menu checkbox.
1081                 menuItem.setChecked(firstPartyCookiesEnabled);
1082
1083                 // Apply the new cookie status.
1084                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1085
1086                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1087                 updatePrivacyIcons(true);
1088
1089                 // Display a `Snackbar`.
1090                 if (firstPartyCookiesEnabled) {  // First-party cookies are enabled.
1091                     Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1092                 } else if (javaScriptEnabled){  // JavaScript is still enabled.
1093                     Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1094                 } else {  // Privacy mode.
1095                     Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1096                 }
1097
1098                 // Reload the WebView.
1099                 mainWebView.reload();
1100                 return true;
1101
1102             case R.id.toggleThirdPartyCookies:
1103                 if (Build.VERSION.SDK_INT >= 21) {
1104                     // Switch the status of thirdPartyCookiesEnabled.
1105                     thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1106
1107                     // Update the menu checkbox.
1108                     menuItem.setChecked(thirdPartyCookiesEnabled);
1109
1110                     // Apply the new cookie status.
1111                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1112
1113                     // Display a `Snackbar`.
1114                     if (thirdPartyCookiesEnabled) {
1115                         Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1116                     } else {
1117                         Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1118                     }
1119
1120                     // Reload the WebView.
1121                     mainWebView.reload();
1122                 } // Else do nothing because SDK < 21.
1123                 return true;
1124
1125             case R.id.toggleDomStorage:
1126                 // Switch the status of domStorageEnabled.
1127                 domStorageEnabled = !domStorageEnabled;
1128
1129                 // Update the menu checkbox.
1130                 menuItem.setChecked(domStorageEnabled);
1131
1132                 // Apply the new DOM Storage status.
1133                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1134
1135                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1136                 updatePrivacyIcons(true);
1137
1138                 // Display a `Snackbar`.
1139                 if (domStorageEnabled) {
1140                     Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1141                 } else {
1142                     Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1143                 }
1144
1145                 // Reload the WebView.
1146                 mainWebView.reload();
1147                 return true;
1148
1149             case R.id.toggleSaveFormData:
1150                 // Switch the status of saveFormDataEnabled.
1151                 saveFormDataEnabled = !saveFormDataEnabled;
1152
1153                 // Update the menu checkbox.
1154                 menuItem.setChecked(saveFormDataEnabled);
1155
1156                 // Apply the new form data status.
1157                 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1158
1159                 // Display a `Snackbar`.
1160                 if (saveFormDataEnabled) {
1161                     Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1162                 } else {
1163                     Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1164                 }
1165
1166                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1167                 updatePrivacyIcons(true);
1168
1169                 // Reload the WebView.
1170                 mainWebView.reload();
1171                 return true;
1172
1173             case R.id.clearCookies:
1174                 if (Build.VERSION.SDK_INT < 21) {
1175                     cookieManager.removeAllCookie();
1176                 } else {
1177                     cookieManager.removeAllCookies(null);
1178                 }
1179                 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_SHORT).show();
1180                 return true;
1181
1182             case R.id.clearDomStorage:
1183                 WebStorage webStorage = WebStorage.getInstance();
1184                 webStorage.deleteAllData();
1185                 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_SHORT).show();
1186                 return true;
1187
1188             case R.id.clearFormData:
1189                 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1190                 mainWebViewDatabase.clearFormData();
1191                 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_SHORT).show();
1192                 return true;
1193
1194             case R.id.fontSizeFiftyPercent:
1195                 mainWebView.getSettings().setTextZoom(50);
1196                 return true;
1197
1198             case R.id.fontSizeSeventyFivePercent:
1199                 mainWebView.getSettings().setTextZoom(75);
1200                 return true;
1201
1202             case R.id.fontSizeOneHundredPercent:
1203                 mainWebView.getSettings().setTextZoom(100);
1204                 return true;
1205
1206             case R.id.fontSizeOneHundredTwentyFivePercent:
1207                 mainWebView.getSettings().setTextZoom(125);
1208                 return true;
1209
1210             case R.id.fontSizeOneHundredFiftyPercent:
1211                 mainWebView.getSettings().setTextZoom(150);
1212                 return true;
1213
1214             case R.id.fontSizeOneHundredSeventyFivePercent:
1215                 mainWebView.getSettings().setTextZoom(175);
1216                 return true;
1217
1218             case R.id.fontSizeTwoHundredPercent:
1219                 mainWebView.getSettings().setTextZoom(200);
1220                 return true;
1221
1222             case R.id.share:
1223                 Intent shareIntent = new Intent();
1224                 shareIntent.setAction(Intent.ACTION_SEND);
1225                 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
1226                 shareIntent.setType("text/plain");
1227                 startActivity(Intent.createChooser(shareIntent, "Share URL"));
1228                 return true;
1229
1230             case R.id.find_on_page:
1231                 // Hide the URL app bar.
1232                 supportAppBar.setVisibility(View.GONE);
1233
1234                 // Show the Find on Page `RelativeLayout`.
1235                 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1236
1237                 // Display the keyboard.  We have to wait 200 ms before running the command to work around a bug in Android.
1238                 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1239                 findOnPageEditText.postDelayed(new Runnable()
1240                 {
1241                     @Override
1242                     public void run()
1243                     {
1244                         // Set the focus on `findOnPageEditText`.
1245                         findOnPageEditText.requestFocus();
1246
1247                         // Display the keyboard.
1248                         inputMethodManager.showSoftInput(findOnPageEditText, 0);
1249                     }
1250                 }, 200);
1251                 return true;
1252
1253             case R.id.refresh:
1254                 mainWebView.reload();
1255                 return true;
1256
1257             case R.id.print:
1258                 // Get a `PrintManager` instance.
1259                 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1260
1261                 // Convert `mainWebView` to `printDocumentAdapter`.
1262                 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
1263
1264                 // Print the document.  The print attributes are `null`.
1265                 printManager.print(getResources().getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1266                 return true;
1267
1268             case R.id.addToHomescreen:
1269                 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
1270                 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
1271                 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.create_shortcut));
1272
1273                 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
1274                 return true;
1275
1276             default:
1277                 // Don't consume the event.
1278                 return super.onOptionsItemSelected(menuItem);
1279         }
1280     }
1281
1282     // removeAllCookies is deprecated, but it is required for API < 21.
1283     @SuppressWarnings("deprecation")
1284     @Override
1285     public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1286         int menuItemId = menuItem.getItemId();
1287
1288         switch (menuItemId) {
1289             case R.id.home:
1290                 loadUrl(homepage);
1291                 break;
1292
1293             case R.id.back:
1294                 if (mainWebView.canGoBack()) {
1295                     // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1296                     navigatingHistory = true;
1297
1298                     // Load the previous website in the history.
1299                     mainWebView.goBack();
1300                 }
1301                 break;
1302
1303             case R.id.forward:
1304                 if (mainWebView.canGoForward()) {
1305                     // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1306                     navigatingHistory = true;
1307
1308                     // Load the next website in the history.
1309                     mainWebView.goForward();
1310                 }
1311                 break;
1312
1313             case R.id.history:
1314                 // Get the `WebBackForwardList`.
1315                 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
1316
1317                 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`.  `this` is the `Context`.
1318                 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
1319                 urlHistoryDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.history));
1320                 break;
1321
1322             case R.id.bookmarks:
1323                 // Launch BookmarksActivity.
1324                 Intent bookmarksIntent = new Intent(this, BookmarksActivity.class);
1325                 startActivity(bookmarksIntent);
1326                 break;
1327
1328             case R.id.downloads:
1329                 // Launch the system Download Manager.
1330                 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1331
1332                 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1333                 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1334
1335                 startActivity(downloadManagerIntent);
1336                 break;
1337
1338             case R.id.settings:
1339                 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1340                 currentDomainName = "";
1341
1342                 // Launch `SettingsActivity`.
1343                 Intent settingsIntent = new Intent(this, SettingsActivity.class);
1344                 startActivity(settingsIntent);
1345                 break;
1346
1347             case R.id.domains:
1348                 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1349                 currentDomainName = "";
1350
1351                 // Launch `DomainsActivity`.
1352                 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1353                 startActivity(domainsIntent);
1354                 break;
1355
1356             case R.id.guide:
1357                 // Launch `GuideActivity`.
1358                 Intent guideIntent = new Intent(this, GuideActivity.class);
1359                 startActivity(guideIntent);
1360                 break;
1361
1362             case R.id.about:
1363                 // Launch `AboutActivity`.
1364                 Intent aboutIntent = new Intent(this, AboutActivity.class);
1365                 startActivity(aboutIntent);
1366                 break;
1367
1368             case R.id.clearAndExit:
1369                 // Clear cookies.  The commands changed slightly in API 21.
1370                 if (Build.VERSION.SDK_INT >= 21) {
1371                     cookieManager.removeAllCookies(null);
1372                 } else {
1373                     cookieManager.removeAllCookie();
1374                 }
1375
1376                 // Clear DOM storage.
1377                 WebStorage domStorage = WebStorage.getInstance();
1378                 domStorage.deleteAllData();
1379
1380                 // Clear form data.
1381                 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1382                 webViewDatabase.clearFormData();
1383
1384                 // Clear the cache.  `true` includes disk files.
1385                 mainWebView.clearCache(true);
1386
1387                 // Clear the back/forward history.
1388                 mainWebView.clearHistory();
1389
1390                 // Clear any SSL certificate preferences.
1391                 mainWebView.clearSslPreferences();
1392
1393                 // Clear `formattedUrlString`.
1394                 formattedUrlString = null;
1395
1396                 // Clear `customHeaders`.
1397                 customHeaders.clear();
1398
1399                 // Detach all views from `mainWebViewRelativeLayout`.
1400                 mainWebViewRelativeLayout.removeAllViews();
1401
1402                 // Destroy the internal state of `mainWebView`.
1403                 mainWebView.destroy();
1404
1405                 // Manually delete cache folders.
1406                 try {
1407                     // Delete the main `cache` folder.
1408                     privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1409
1410                     // 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`.
1411                     privacyBrowserRuntime.exec("rm -rf " + privacyBrowserRuntime + "/app_webview");
1412                 } catch (IOException e) {
1413                     // Do nothing if an error is thrown.
1414                 }
1415
1416                 // Close Privacy Browser.  `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
1417                 if (Build.VERSION.SDK_INT >= 21) {
1418                     finishAndRemoveTask();
1419                 } else {
1420                     finish();
1421                 }
1422
1423                 // Remove the terminated program from RAM.  The status code is `0`.
1424                 System.exit(0);
1425                 break;
1426
1427             default:
1428                 break;
1429         }
1430
1431         // Close the navigation drawer.
1432         drawerLayout.closeDrawer(GravityCompat.START);
1433         return true;
1434     }
1435
1436     @Override
1437     public void onPostCreate(Bundle savedInstanceState) {
1438         super.onPostCreate(savedInstanceState);
1439
1440         // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
1441         drawerToggle.syncState();
1442     }
1443
1444     @Override
1445     public void onConfigurationChanged(Configuration newConfig) {
1446         super.onConfigurationChanged(newConfig);
1447
1448         // Reload the ad for the free flavor if we are not in full screen mode.
1449         if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
1450             // Reload the ad.
1451             BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1452
1453             // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1454             adView = findViewById(R.id.adview);
1455         }
1456
1457         // `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
1458         // ActivityCompat.invalidateOptionsMenu(this);
1459     }
1460
1461     @Override
1462     public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
1463         // Store the `HitTestResult`.
1464         final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
1465
1466         // Create strings.
1467         final String imageUrl;
1468         final String linkUrl;
1469
1470         // Get a handle for the `ClipboardManager`.
1471         final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
1472
1473         switch (hitTestResult.getType()) {
1474             // `SRC_ANCHOR_TYPE` is a link.
1475             case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1476                 // Get the target URL.
1477                 linkUrl = hitTestResult.getExtra();
1478
1479                 // Set the target URL as the title of the `ContextMenu`.
1480                 menu.setHeaderTitle(linkUrl);
1481
1482                 // Add a `Load URL` entry.
1483                 menu.add(R.string.load_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1484                     @Override
1485                     public boolean onMenuItemClick(MenuItem item) {
1486                         loadUrl(linkUrl);
1487                         return false;
1488                     }
1489                 });
1490
1491                 // Add a `Copy URL` entry.
1492                 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1493                     @Override
1494                     public boolean onMenuItemClick(MenuItem item) {
1495                         // Save the link URL in a `ClipData`.
1496                         ClipData srcAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), linkUrl);
1497
1498                         // Set the `ClipData` as the clipboard's primary clip.
1499                         clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
1500                         return false;
1501                     }
1502                 });
1503
1504                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1505                 menu.add(R.string.cancel);
1506                 break;
1507
1508             case WebView.HitTestResult.EMAIL_TYPE:
1509                 // Get the target URL.
1510                 linkUrl = hitTestResult.getExtra();
1511
1512                 // Set the target URL as the title of the `ContextMenu`.
1513                 menu.setHeaderTitle(linkUrl);
1514
1515                 // Add a `Write Email` entry.
1516                 menu.add(R.string.write_email).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1517                     @Override
1518                     public boolean onMenuItemClick(MenuItem item) {
1519                         // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1520                         Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1521
1522                         // Parse the url and set it as the data for the `Intent`.
1523                         emailIntent.setData(Uri.parse("mailto:" + linkUrl));
1524
1525                         // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
1526                         emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1527
1528                         // Make it so.
1529                         startActivity(emailIntent);
1530                         return false;
1531                     }
1532                 });
1533
1534                 // Add a `Copy Email Address` entry.
1535                 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1536                     @Override
1537                     public boolean onMenuItemClick(MenuItem item) {
1538                         // Save the email address in a `ClipData`.
1539                         ClipData srcEmailTypeClipData = ClipData.newPlainText(getResources().getString(R.string.email_address), linkUrl);
1540
1541                         // Set the `ClipData` as the clipboard's primary clip.
1542                         clipboardManager.setPrimaryClip(srcEmailTypeClipData);
1543                         return false;
1544                     }
1545                 });
1546
1547                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1548                 menu.add(R.string.cancel);
1549                 break;
1550
1551             // `IMAGE_TYPE` is an image.
1552             case WebView.HitTestResult.IMAGE_TYPE:
1553                 // Get the image URL.
1554                 imageUrl = hitTestResult.getExtra();
1555
1556                 // Set the image URL as the title of the `ContextMenu`.
1557                 menu.setHeaderTitle(imageUrl);
1558
1559                 // Add a `View Image` entry.
1560                 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1561                     @Override
1562                     public boolean onMenuItemClick(MenuItem item) {
1563                         loadUrl(imageUrl);
1564                         return false;
1565                     }
1566                 });
1567
1568                 // Add a `Download Image` entry.
1569                 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1570                     @Override
1571                     public boolean onMenuItemClick(MenuItem item) {
1572                         // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
1573                         AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
1574                         downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1575                         return false;
1576                     }
1577                 });
1578
1579                 // Add a `Copy URL` entry.
1580                 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1581                     @Override
1582                     public boolean onMenuItemClick(MenuItem item) {
1583                         // Save the image URL in a `ClipData`.
1584                         ClipData srcImageTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1585
1586                         // Set the `ClipData` as the clipboard's primary clip.
1587                         clipboardManager.setPrimaryClip(srcImageTypeClipData);
1588                         return false;
1589                     }
1590                 });
1591
1592                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1593                 menu.add(R.string.cancel);
1594                 break;
1595
1596
1597             // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
1598             case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1599                 // Get the image URL.
1600                 imageUrl = hitTestResult.getExtra();
1601
1602                 // Set the image URL as the title of the `ContextMenu`.
1603                 menu.setHeaderTitle(imageUrl);
1604
1605                 // Add a `View Image` entry.
1606                 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1607                     @Override
1608                     public boolean onMenuItemClick(MenuItem item) {
1609                         loadUrl(imageUrl);
1610                         return false;
1611                     }
1612                 });
1613
1614                 // Add a `Download Image` entry.
1615                 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1616                     @Override
1617                     public boolean onMenuItemClick(MenuItem item) {
1618                         // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
1619                         AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
1620                         downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1621                         return false;
1622                     }
1623                 });
1624
1625                 // Add a `Copy URL` entry.
1626                 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1627                     @Override
1628                     public boolean onMenuItemClick(MenuItem item) {
1629                         // Save the image URL in a `ClipData`.
1630                         ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1631
1632                         // Set the `ClipData` as the clipboard's primary clip.
1633                         clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
1634                         return false;
1635                     }
1636                 });
1637
1638                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1639                 menu.add(R.string.cancel);
1640                 break;
1641         }
1642     }
1643
1644     @Override
1645     public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
1646         // Get shortcutNameEditText from the alert dialog.
1647         EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
1648
1649         // Create the bookmark shortcut based on formattedUrlString.
1650         Intent bookmarkShortcut = new Intent();
1651         bookmarkShortcut.setAction(Intent.ACTION_VIEW);
1652         bookmarkShortcut.setData(Uri.parse(formattedUrlString));
1653
1654         // Place the bookmark shortcut on the home screen.
1655         Intent placeBookmarkShortcut = new Intent();
1656         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
1657         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
1658         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIconBitmap);
1659         placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
1660         sendBroadcast(placeBookmarkShortcut);
1661     }
1662
1663     @Override
1664     public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
1665         // Download the image if it has an HTTP or HTTPS URI.
1666         if (imageUrl.startsWith("http")) {
1667             // Get a handle for the system `DOWNLOAD_SERVICE`.
1668             DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
1669
1670             // Parse `imageUrl`.
1671             DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
1672
1673             // Pass cookies to download manager if cookies are enabled.  This is required to download images from websites that require a login.
1674             if (firstPartyCookiesEnabled) {
1675                 // Get the cookies for `imageUrl`.
1676                 String cookies = cookieManager.getCookie(imageUrl);
1677
1678                 // Add the cookies to `downloadRequest`.  In the HTTP request header, cookies are named `Cookie`.
1679                 downloadRequest.addRequestHeader("Cookie", cookies);
1680             }
1681
1682             // Get the file name from `dialogFragment`.
1683             EditText downloadImageNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_image_name);
1684             String imageName = downloadImageNameEditText.getText().toString();
1685
1686             // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
1687             if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `imageName`.
1688                 downloadRequest.setDestinationInExternalFilesDir(this, "/", imageName);
1689             } else { // Only set the title using `imageName`.
1690                 downloadRequest.setTitle(imageName);
1691             }
1692
1693             // Allow `MediaScanner` to index the download if it is a media file.
1694             downloadRequest.allowScanningByMediaScanner();
1695
1696             // Add the URL as the description for the download.
1697             downloadRequest.setDescription(imageUrl);
1698
1699             // Show the download notification after the download is completed.
1700             downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
1701
1702             // Initiate the download.
1703             downloadManager.enqueue(downloadRequest);
1704         } else {  // The image is not an HTTP or HTTPS URI.
1705             Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
1706         }
1707     }
1708
1709     @Override
1710     public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
1711         // Download the file if it has an HTTP or HTTPS URI.
1712         if (downloadUrl.startsWith("http")) {
1713
1714             // Get a handle for the system `DOWNLOAD_SERVICE`.
1715             DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
1716
1717             // Parse `downloadUrl`.
1718             DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
1719
1720             // Pass cookies to download manager if cookies are enabled.  This is required to download files from websites that require a login.
1721             if (firstPartyCookiesEnabled) {
1722                 // Get the cookies for `downloadUrl`.
1723                 String cookies = cookieManager.getCookie(downloadUrl);
1724
1725                 // Add the cookies to `downloadRequest`.  In the HTTP request header, cookies are named `Cookie`.
1726                 downloadRequest.addRequestHeader("Cookie", cookies);
1727             }
1728
1729             // Get the file name from `dialogFragment`.
1730             EditText downloadFileNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_file_name);
1731             String fileName = downloadFileNameEditText.getText().toString();
1732
1733             // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
1734             if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download location to `/sdcard/Android/data/com.stoutner.privacybrowser.standard/files` named `fileName`.
1735                 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
1736             } else { // Only set the title using `fileName`.
1737                 downloadRequest.setTitle(fileName);
1738             }
1739
1740             // Allow `MediaScanner` to index the download if it is a media file.
1741             downloadRequest.allowScanningByMediaScanner();
1742
1743             // Add the URL as the description for the download.
1744             downloadRequest.setDescription(downloadUrl);
1745
1746             // Show the download notification after the download is completed.
1747             downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
1748
1749             // Initiate the download.
1750             downloadManager.enqueue(downloadRequest);
1751         } else {  // The download is not an HTTP or HTTPS URI.
1752             Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
1753         }
1754     }
1755
1756     public void viewSslCertificate(View view) {
1757         // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
1758         DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
1759         viewSslCertificateDialogFragment.show(getFragmentManager(), getResources().getString(R.string.view_ssl_certificate));
1760     }
1761
1762     @Override
1763     public void onSslErrorCancel() {
1764         sslErrorHandler.cancel();
1765     }
1766
1767     @Override
1768     public void onSslErrorProceed() {
1769         sslErrorHandler.proceed();
1770     }
1771
1772     @Override
1773     public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
1774         // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1775         navigatingHistory = true;
1776
1777         // Load the history entry.
1778         mainWebView.goBackOrForward(moveBackOrForwardSteps);
1779     }
1780
1781     @Override
1782     public void onClearHistory() {
1783         // Clear the history.
1784         mainWebView.clearHistory();
1785     }
1786
1787     // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
1788     @Override
1789     public void onBackPressed() {
1790         // Close the navigation drawer if it is available.  GravityCompat.START is the drawer on the left on Left-to-Right layout text.
1791         if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1792             drawerLayout.closeDrawer(GravityCompat.START);
1793         } else {
1794             // Load the previous URL if available.
1795             if (mainWebView.canGoBack()) {
1796                 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1797                 navigatingHistory = true;
1798
1799                 // Go back.
1800                 mainWebView.goBack();
1801             } else {
1802                 // Pass `onBackPressed()` to the system.
1803                 super.onBackPressed();
1804             }
1805         }
1806     }
1807
1808     @Override
1809     public void onPause() {
1810         // Pause `mainWebView`.
1811         mainWebView.onPause();
1812
1813         // Stop all JavaScript.
1814         mainWebView.pauseTimers();
1815
1816         // Pause the adView or it will continue to consume resources in the background on the free flavor.
1817         if (BuildConfig.FLAVOR.contentEquals("free")) {
1818             BannerAd.pauseAd(adView);
1819         }
1820
1821         super.onPause();
1822     }
1823
1824     @Override
1825     public void onResume() {  // `onResume()` also runs every time the app starts after `onCreate()` and `onStart()`.
1826         super.onResume();
1827
1828         // Resume JavaScript (if enabled).
1829         mainWebView.resumeTimers();
1830
1831         // Resume `mainWebView`.
1832         mainWebView.onResume();
1833
1834         // Resume the adView for the free flavor.
1835         if (BuildConfig.FLAVOR.contentEquals("free")) {
1836             BannerAd.resumeAd(adView);
1837         }
1838     }
1839
1840     @Override
1841     public void onRestart() {
1842         super.onRestart();
1843
1844         // Apply the settings from shared preferences, which might have been changed in `SettingsActivity`.
1845         applyAppSettings();
1846
1847         // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1848         updatePrivacyIcons(true);
1849
1850     }
1851
1852     private void loadUrlFromTextBox() throws UnsupportedEncodingException {
1853         // Get the text from urlTextBox and convert it to a string.  trim() removes white spaces from the beginning and end of the string.
1854         String unformattedUrlString = urlTextBox.getText().toString().trim();
1855
1856         // Check to see if `unformattedUrlString` is a valid URL.  Otherwise, convert it into a search.
1857         if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.contains("localhost"))) {
1858             // Add `http://` at the beginning if it is missing.  Otherwise the app will segfault.
1859             if (!unformattedUrlString.startsWith("http")) {
1860                 unformattedUrlString = "http://" + unformattedUrlString;
1861             }
1862
1863             // Initialize `unformattedUrl`.
1864             URL unformattedUrl = null;
1865
1866             // 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.
1867             try {
1868                 unformattedUrl = new URL(unformattedUrlString);
1869             } catch (MalformedURLException e) {
1870                 e.printStackTrace();
1871             }
1872
1873             // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
1874             final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
1875             final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
1876             final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
1877             final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
1878             final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
1879
1880             // Build the URI.
1881             Uri.Builder formattedUri = new Uri.Builder();
1882             formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
1883
1884             // Decode `formattedUri` as a `String` in `UTF-8`.
1885             formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
1886         } else {
1887             // Sanitize the search input and convert it to a search.
1888             final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
1889
1890             // Use the correct search URL.
1891             if (javaScriptEnabled) {  // JavaScript is enabled.
1892                 formattedUrlString = javaScriptEnabledSearchURL + encodedUrlString;
1893             } else { // JavaScript is disabled.
1894                 formattedUrlString = javaScriptDisabledSearchURL + encodedUrlString;
1895             }
1896         }
1897
1898         loadUrl(formattedUrlString);
1899
1900         // Hide the keyboard so we can see the webpage.  `0` indicates no additional flags.
1901         inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1902     }
1903
1904
1905     private void loadUrl(String url) {
1906         // Apply any custom domain settings.
1907         applyDomainSettings(url);
1908
1909         // Load the URL.
1910         mainWebView.loadUrl(url, customHeaders);
1911     }
1912
1913     // We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
1914     @SuppressWarnings("deprecation")
1915     private void applyDomainSettings(String url) {
1916         // Reset `navigatingHistory`.
1917         navigatingHistory = false;
1918
1919         // Parse the URL into a URI.
1920         Uri uri = Uri.parse(url);
1921
1922         // Extract the domain from `uri`.
1923         String hostName = uri.getHost();
1924
1925         // Initialize `loadingNewDomainName`.
1926         boolean loadingNewDomainName;
1927
1928         // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
1929         // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
1930         //noinspection SimplifiableIfStatement
1931         if ((hostName == null) || (currentDomainName == null)) {
1932             loadingNewDomainName = true;
1933         } else {  // Determine if `hostName` equals `currentDomainName`.
1934             loadingNewDomainName = !hostName.equals(currentDomainName);
1935         }
1936
1937         // 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.
1938         if (loadingNewDomainName) {
1939             // Set the new `hostname` as the `currentDomainName`.
1940             currentDomainName = hostName;
1941
1942             // Reset `favoriteIconBitmap` and display it in the `appbar`.
1943             favoriteIconBitmap = favoriteIconDefaultBitmap;
1944             favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
1945
1946             // Initialize the database handler.  `this` specifies the context.  The two `nulls` do not specify the database name or a `CursorFactory`.
1947             // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1948             DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1949
1950             // Get a full cursor from `domainsDatabaseHelper`.
1951             Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
1952
1953             // Initialize `domainSettingsSet`.
1954             Set<String> domainSettingsSet = new HashSet<>();
1955
1956             // Get the domain name column index.
1957             int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
1958
1959             // Populate `domainSettingsSet`.
1960             for (int i = 0; i < domainNameCursor.getCount(); i++) {
1961                 // Move `domainsCursor` to the current row.
1962                 domainNameCursor.moveToPosition(i);
1963
1964                 // Store the domain name in `domainSettingsSet`.
1965                 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
1966             }
1967
1968             // Close `domainNameCursor.
1969             domainNameCursor.close();
1970
1971             // Initialize variables to track if this domain has stored domain settings, and if so, under which name.
1972             boolean hostHasDomainSettings = false;
1973             String domainNameInDatabase = null;
1974
1975             // Check the hostname.
1976             if (domainSettingsSet.contains(hostName)) {
1977                 hostHasDomainSettings = true;
1978                 domainNameInDatabase = hostName;
1979             }
1980
1981             // If `hostName` is not `null`, check all the subdomains of `hostName` against wildcard domains in `domainCursor`.
1982             if (hostName != null) {
1983                 while (hostName.contains(".") && !hostHasDomainSettings) {  // Stop checking if we run out of  `.` or if we already know that `hostHasDomainSettings` is `true`.
1984                     if (domainSettingsSet.contains("*." + hostName)) {  // Check the host name prepended by `*.`.
1985                         hostHasDomainSettings = true;
1986                         domainNameInDatabase = "*." + hostName;
1987                     }
1988
1989                     // Strip out the lowest subdomain of `host`.
1990                     hostName = hostName.substring(hostName.indexOf(".") + 1);
1991                 }
1992             }
1993
1994             if (hostHasDomainSettings) {  // The url we are loading has custom domain settings.
1995                 // Get a cursor for the current host and move it to the first position.
1996                 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
1997                 currentHostDomainSettingsCursor.moveToFirst();
1998
1999                 // Get the settings from the cursor.
2000                 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
2001                 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
2002                 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
2003                 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
2004                 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
2005                 String userAgentString = (currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT)));
2006                 int fontSize = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE)));
2007
2008                 // Close `currentHostDomainSettingsCursor`.
2009                 currentHostDomainSettingsCursor.close();
2010
2011                 // Apply the domain settings.
2012                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2013                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2014                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2015                 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2016                 mainWebView.getSettings().setTextZoom(fontSize);
2017
2018                 // Set third-party cookies status if API >= 21.
2019                 if (Build.VERSION.SDK_INT >= 21) {
2020                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2021                 }
2022
2023                 // Set the user agent.
2024                 if (userAgentString.equals("WebView default user agent")) {
2025                     // Set the user agent to `""`, which uses the default value.
2026                     mainWebView.getSettings().setUserAgentString("");
2027                 } else {
2028                     // Use the selected user agent.
2029                     mainWebView.getSettings().setUserAgentString(userAgentString);
2030                 }
2031
2032                 // 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.
2033                 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_green));
2034             } else {  // The URL we are loading does not have custom domain settings.  Load the defaults.
2035                 // Get the shared preference values.  `this` references the current context.
2036                 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2037
2038                 // Store the values from `sharedPreferences` in variables.
2039                 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
2040                 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
2041                 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
2042                 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
2043                 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
2044                 String userAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
2045                 String customUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
2046                 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
2047
2048                 // Apply the default settings.
2049                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2050                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2051                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2052                 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2053                 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
2054
2055                 // Set third-party cookies status if API >= 21.
2056                 if (Build.VERSION.SDK_INT >= 21) {
2057                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2058                 }
2059
2060                 // Set the default user agent.
2061                 switch (userAgentString) {
2062                     case "WebView default user agent":
2063                         // Set the user agent to `""`, which uses the default value.
2064                         mainWebView.getSettings().setUserAgentString("");
2065                         break;
2066
2067                     case "Custom user agent":
2068                         // Set the custom user agent.
2069                         mainWebView.getSettings().setUserAgentString(customUserAgentString);
2070                         break;
2071
2072                     default:
2073                         // Use the selected user agent.
2074                         mainWebView.getSettings().setUserAgentString(userAgentString);
2075                         break;
2076                 }
2077
2078                 // Set a transparent background on `urlTextBox`.  We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2079                 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.url_bar_background_transparent));
2080             }
2081
2082             // Close `domainsDatabaseHelper`.
2083             domainsDatabaseHelper.close();
2084
2085             // Update the privacy icons, but only if `mainMenu` has already been populated.
2086             if (mainMenu != null) {
2087                 updatePrivacyIcons(true);
2088             }
2089         }
2090     }
2091
2092     public void findPreviousOnPage(View view) {
2093         // Go to the previous highlighted phrase on the page.  `false` goes backwards instead of forwards.
2094         mainWebView.findNext(false);
2095     }
2096
2097     public void findNextOnPage(View view) {
2098         // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2099         mainWebView.findNext(true);
2100     }
2101
2102     public void closeFindOnPage(View view) {
2103         // Delete the contents of `find_on_page_edittext`.
2104         findOnPageEditText.setText(null);
2105
2106         // Clear the highlighted phrases.
2107         mainWebView.clearMatches();
2108
2109         // Hide the Find on Page `RelativeLayout`.
2110         findOnPageLinearLayout.setVisibility(View.GONE);
2111
2112         // Show the URL app bar.
2113         supportAppBar.setVisibility(View.VISIBLE);
2114
2115         // Hide the keyboard so we can see the webpage.  `0` indicates no additional flags.
2116         inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2117     }
2118
2119     private void applyAppSettings() {
2120         // Get the shared preference values.  `this` references the current context.
2121         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2122
2123         // Store the values from `sharedPreferences` in variables.
2124         String javaScriptDisabledSearchString = sharedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=");
2125         String javaScriptDisabledSearchCustomURLString = sharedPreferences.getString("javascript_disabled_search_custom_url", "");
2126         String javaScriptEnabledSearchString = sharedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=");
2127         String javaScriptEnabledSearchCustomURLString = sharedPreferences.getString("javascript_enabled_search_custom_url", "");
2128         String homepageString = sharedPreferences.getString("homepage", "https://duckduckgo.com");
2129         String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
2130         String torJavaScriptDisabledSearchString = sharedPreferences.getString("tor_javascript_disabled_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
2131         String torJavaScriptDisabledSearchCustomURLString = sharedPreferences.getString("tor_javascript_disabled_search_custom_url", "");
2132         String torJavaScriptEnabledSearchString = sharedPreferences.getString("tor_javascript_enabled_search", "https://3g2upl4pq6kufc4m.onion/?q=");
2133         String torJavaScriptEnabledSearchCustomURLString = sharedPreferences.getString("tor_javascript_enabled_search_custom_url", "");
2134         adBlockerEnabled = sharedPreferences.getBoolean("block_ads", true);
2135         incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
2136         boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
2137         boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
2138         fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("enable_full_screen_browsing_mode", false);
2139         hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
2140         translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
2141         swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh", false);
2142
2143         // Set the homepage, search, and proxy options.
2144         if (proxyThroughOrbot) {  // Set the Tor options.
2145             // Set `torHomepageString` as `homepage`.
2146             homepage = torHomepageString;
2147
2148             // If formattedUrlString is null assign the homepage to it.
2149             if (formattedUrlString == null) {
2150                 formattedUrlString = homepage;
2151             }
2152
2153             // Set JavaScript disabled search.
2154             if (torJavaScriptDisabledSearchString.equals("Custom URL")) {  // Get the custom URL string.
2155                 javaScriptDisabledSearchURL = torJavaScriptDisabledSearchCustomURLString;
2156             } else {  // Use the string from the pre-built list.
2157                 javaScriptDisabledSearchURL = torJavaScriptDisabledSearchString;
2158             }
2159
2160             // Set JavaScript enabled search.
2161             if (torJavaScriptEnabledSearchString.equals("Custom URL")) {  // Get the custom URL string.
2162                 javaScriptEnabledSearchURL = torJavaScriptEnabledSearchCustomURLString;
2163             } else {  // Use the string from the pre-built list.
2164                 javaScriptEnabledSearchURL = torJavaScriptEnabledSearchString;
2165             }
2166
2167             // Set the proxy.  `this` refers to the current activity where an `AlertDialog` might be displayed.
2168             OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
2169
2170             // Display a message to the user if we are waiting on Orbot.
2171             if (!orbotStatus.equals("ON")) {
2172                 // Set `waitingForOrbot`.
2173                 waitingForOrbot = true;
2174
2175                 // Load a waiting page.  `null` specifies no encoding, which defaults to ASCII.
2176                 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
2177             }
2178         } else {  // Set the non-Tor options.
2179             // Set `homepageString` as `homepage`.
2180             homepage = homepageString;
2181
2182             // If formattedUrlString is null assign the homepage to it.
2183             if (formattedUrlString == null) {
2184                 formattedUrlString = homepage;
2185             }
2186
2187             // Set JavaScript disabled search.
2188             if (javaScriptDisabledSearchString.equals("Custom URL")) {  // Get the custom URL string.
2189                 javaScriptDisabledSearchURL = javaScriptDisabledSearchCustomURLString;
2190             } else {  // Use the string from the pre-built list.
2191                 javaScriptDisabledSearchURL = javaScriptDisabledSearchString;
2192             }
2193
2194             // Set JavaScript enabled search.
2195             if (javaScriptEnabledSearchString.equals("Custom URL")) {  // Get the custom URL string.
2196                 javaScriptEnabledSearchURL = javaScriptEnabledSearchCustomURLString;
2197             } else {  // Use the string from the pre-built list.
2198                 javaScriptEnabledSearchURL = javaScriptEnabledSearchString;
2199             }
2200
2201             // Reset the proxy to default.  The host is `""` and the port is `"0"`.
2202             OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
2203
2204             // Reset `waitingForOrbot.
2205             waitingForOrbot = false;
2206         }
2207
2208         // Set swipe to refresh.
2209         swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
2210
2211         // Set Do Not Track status.
2212         if (doNotTrackEnabled) {
2213             customHeaders.put("DNT", "1");
2214         } else {
2215             customHeaders.remove("DNT");
2216         }
2217
2218         // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
2219         if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
2220             if (hideSystemBarsOnFullscreen) {  // Hide everything.
2221                 // Remove the translucent navigation setting if it is currently flagged.
2222                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2223
2224                 // Remove the translucent status bar overlay.
2225                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2226
2227                 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
2228                 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
2229
2230                 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
2231                  * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
2232                  * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
2233                  */
2234                 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
2235             } else {  // Hide everything except the status and navigation bars.
2236                 // Add the translucent status flag if it is unset.
2237                 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2238
2239                 if (translucentNavigationBarOnFullscreen) {
2240                     // Set the navigation bar to be translucent.
2241                     getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2242                 } else {
2243                     // Set the navigation bar to be black.
2244                     getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2245                 }
2246             }
2247         } else {  // Switch to normal viewing mode.
2248             // Reset `inFullScreenBrowsingMode` to `false`.
2249             inFullScreenBrowsingMode = false;
2250
2251             // Show the `appBar`.
2252             appBar.show();
2253
2254             // Show the `BannerAd` in the free flavor.
2255             if (BuildConfig.FLAVOR.contentEquals("free")) {
2256                 // Reload the ad.  Because the screen may have rotated, we need to use `reloadAfterRotate`.
2257                 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2258
2259                 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2260                 adView = findViewById(R.id.adview);
2261             }
2262
2263             // Remove the translucent navigation bar flag if it is set.
2264             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2265
2266             // Add the translucent status flag if it is unset.  This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
2267             getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2268
2269             // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
2270             rootCoordinatorLayout.setSystemUiVisibility(0);
2271
2272             // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
2273             rootCoordinatorLayout.setFitsSystemWindows(true);
2274         }
2275     }
2276
2277     private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
2278         // Get handles for the icons.
2279         MenuItem privacyIcon = mainMenu.findItem(R.id.toggleJavaScript);
2280         MenuItem firstPartyCookiesIcon = mainMenu.findItem(R.id.toggleFirstPartyCookies);
2281         MenuItem domStorageIcon = mainMenu.findItem(R.id.toggleDomStorage);
2282         MenuItem formDataIcon = mainMenu.findItem(R.id.toggleSaveFormData);
2283
2284         // Update `privacyIcon`.
2285         if (javaScriptEnabled) {  // JavaScript is enabled.
2286             privacyIcon.setIcon(R.drawable.javascript_enabled);
2287         } else if (firstPartyCookiesEnabled) {  // JavaScript is disabled but cookies are enabled.
2288             privacyIcon.setIcon(R.drawable.warning);
2289         } else {  // All the dangerous features are disabled.
2290             privacyIcon.setIcon(R.drawable.privacy_mode);
2291         }
2292
2293         // Update `firstPartyCookiesIcon`.
2294         if (firstPartyCookiesEnabled) {  // First-party cookies are enabled.
2295             firstPartyCookiesIcon.setIcon(R.drawable.cookies_enabled);
2296         } else {  // First-party cookies are disabled.
2297             firstPartyCookiesIcon.setIcon(R.drawable.cookies_disabled);
2298         }
2299
2300         // Update `domStorageIcon`.
2301         if (javaScriptEnabled && domStorageEnabled) {  // Both JavaScript and DOM storage are enabled.
2302             domStorageIcon.setIcon(R.drawable.dom_storage_enabled);
2303         } else if (javaScriptEnabled) {  // JavaScript is enabled but DOM storage is disabled.
2304             domStorageIcon.setIcon(R.drawable.dom_storage_disabled);
2305         } else {  // JavaScript is disabled, so DOM storage is ghosted.
2306             domStorageIcon.setIcon(R.drawable.dom_storage_ghosted);
2307         }
2308
2309         // Update `formDataIcon`.
2310         if (saveFormDataEnabled) {  // Form data is enabled.
2311             formDataIcon.setIcon(R.drawable.form_data_enabled);
2312         } else {  // Form data is disabled.
2313             formDataIcon.setIcon(R.drawable.form_data_disabled);
2314         }
2315
2316         // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.  `this` references the current activity.
2317         if (runInvalidateOptionsMenu) {
2318             ActivityCompat.invalidateOptionsMenu(this);
2319         }
2320     }
2321 }