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