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