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