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