]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/activities/MainWebViewActivity.java
Add option to remove Twitter AMP redirects. https://redmine.stoutner.com/issues/417
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / activities / MainWebViewActivity.java
1 /*
2  * Copyright © 2015-2019 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.Manifest;
25 import android.annotation.SuppressLint;
26 import android.app.Activity;
27 import android.app.DownloadManager;
28 import android.app.SearchManager;
29 import android.content.ActivityNotFoundException;
30 import android.content.BroadcastReceiver;
31 import android.content.ClipData;
32 import android.content.ClipboardManager;
33 import android.content.Context;
34 import android.content.Intent;
35 import android.content.IntentFilter;
36 import android.content.SharedPreferences;
37 import android.content.pm.PackageManager;
38 import android.content.res.Configuration;
39 import android.database.Cursor;
40 import android.graphics.Bitmap;
41 import android.graphics.BitmapFactory;
42 import android.graphics.Typeface;
43 import android.graphics.drawable.BitmapDrawable;
44 import android.graphics.drawable.Drawable;
45 import android.net.Uri;
46 import android.net.http.SslCertificate;
47 import android.net.http.SslError;
48 import android.os.Build;
49 import android.os.Bundle;
50 import android.os.Environment;
51 import android.os.Handler;
52 import android.preference.PreferenceManager;
53 import android.print.PrintDocumentAdapter;
54 import android.print.PrintManager;
55 import android.text.Editable;
56 import android.text.Spanned;
57 import android.text.TextWatcher;
58 import android.text.style.ForegroundColorSpan;
59 import android.util.Patterns;
60 import android.view.ContextMenu;
61 import android.view.GestureDetector;
62 import android.view.KeyEvent;
63 import android.view.Menu;
64 import android.view.MenuItem;
65 import android.view.MotionEvent;
66 import android.view.View;
67 import android.view.ViewGroup;
68 import android.view.WindowManager;
69 import android.view.inputmethod.InputMethodManager;
70 import android.webkit.CookieManager;
71 import android.webkit.HttpAuthHandler;
72 import android.webkit.SslErrorHandler;
73 import android.webkit.ValueCallback;
74 import android.webkit.WebChromeClient;
75 import android.webkit.WebResourceResponse;
76 import android.webkit.WebSettings;
77 import android.webkit.WebStorage;
78 import android.webkit.WebView;
79 import android.webkit.WebViewClient;
80 import android.webkit.WebViewDatabase;
81 import android.widget.ArrayAdapter;
82 import android.widget.CursorAdapter;
83 import android.widget.EditText;
84 import android.widget.FrameLayout;
85 import android.widget.ImageView;
86 import android.widget.LinearLayout;
87 import android.widget.ListView;
88 import android.widget.ProgressBar;
89 import android.widget.RadioButton;
90 import android.widget.RelativeLayout;
91 import android.widget.TextView;
92
93 import androidx.annotation.NonNull;
94 import androidx.appcompat.app.ActionBar;
95 import androidx.appcompat.app.ActionBarDrawerToggle;
96 import androidx.appcompat.app.AppCompatActivity;
97 import androidx.appcompat.widget.Toolbar;
98 import androidx.coordinatorlayout.widget.CoordinatorLayout;
99 import androidx.core.app.ActivityCompat;
100 import androidx.core.content.ContextCompat;
101 import androidx.core.view.GravityCompat;
102 import androidx.drawerlayout.widget.DrawerLayout;
103 import androidx.fragment.app.DialogFragment;
104 import androidx.fragment.app.FragmentManager;
105 import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
106 import androidx.viewpager.widget.ViewPager;
107
108 import com.google.android.material.appbar.AppBarLayout;
109 import com.google.android.material.floatingactionbutton.FloatingActionButton;
110 import com.google.android.material.navigation.NavigationView;
111 import com.google.android.material.snackbar.Snackbar;
112 import com.google.android.material.tabs.TabLayout;
113
114 import com.stoutner.privacybrowser.BuildConfig;
115 import com.stoutner.privacybrowser.R;
116 import com.stoutner.privacybrowser.adapters.WebViewPagerAdapter;
117 import com.stoutner.privacybrowser.asynctasks.GetHostIpAddresses;
118 import com.stoutner.privacybrowser.dialogs.AdConsentDialog;
119 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
120 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
121 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
122 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
123 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
124 import com.stoutner.privacybrowser.dialogs.DownloadLocationPermissionDialog;
125 import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
126 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
127 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
128 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
129 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
130 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
131 import com.stoutner.privacybrowser.fragments.WebViewTabFragment;
132 import com.stoutner.privacybrowser.helpers.AdHelper;
133 import com.stoutner.privacybrowser.helpers.BlockListHelper;
134 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
135 import com.stoutner.privacybrowser.helpers.CheckPinnedMismatchHelper;
136 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
137 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
138 import com.stoutner.privacybrowser.views.NestedScrollWebView;
139
140 import java.io.ByteArrayInputStream;
141 import java.io.ByteArrayOutputStream;
142 import java.io.File;
143 import java.io.IOException;
144 import java.io.UnsupportedEncodingException;
145 import java.net.MalformedURLException;
146 import java.net.URL;
147 import java.net.URLDecoder;
148 import java.net.URLEncoder;
149 import java.util.ArrayList;
150 import java.util.Date;
151 import java.util.HashMap;
152 import java.util.HashSet;
153 import java.util.List;
154 import java.util.Map;
155 import java.util.Set;
156
157 // AppCompatActivity from android.support.v7.app.AppCompatActivity must be used to have access to the SupportActionBar until the minimum API is >= 21.
158 public class MainWebViewActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener,
159         DownloadFileDialog.DownloadFileListener, DownloadImageDialog.DownloadImageListener, DownloadLocationPermissionDialog.DownloadLocationPermissionDialogListener, EditBookmarkDialog.EditBookmarkListener,
160         EditBookmarkFolderDialog.EditBookmarkFolderListener, NavigationView.OnNavigationItemSelectedListener, WebViewTabFragment.NewTabListener {
161
162     // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`.  It is also used in `onCreate()`, `onResume()`, and `applyProxyThroughOrbot()`.
163     public static String orbotStatus;
164
165     // The WebView pager adapter is accessed from `HttpAuthenticationDialog`, `PinnedMismatchDialog`, and `SslCertificateErrorDialog`.  It is also used in `onCreate()`, `onResume()`, and `addTab()`.
166     public static WebViewPagerAdapter webViewPagerAdapter;
167
168     // The load URL on restart variables are public static so they can be accessed from `BookmarksActivity`.  They are used in `onRestart()`.
169     public static boolean loadUrlOnRestart;
170     public static String urlToLoadOnRestart;
171
172     // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`.  It is also used in `onRestart()`.
173     public static boolean restartFromBookmarksActivity;
174
175     // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`.  It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`,
176     // `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
177     public static String currentBookmarksFolder;
178
179     // The user agent constants are public static so they can be accessed from `SettingsFragment`, `DomainsActivity`, and `DomainSettingsFragment`.
180     public final static int UNRECOGNIZED_USER_AGENT = -1;
181     public final static int SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1;
182     public final static int SETTINGS_CUSTOM_USER_AGENT = 12;
183     public final static int DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0;
184     public final static int DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2;
185     public final static int DOMAINS_CUSTOM_USER_AGENT = 13;
186
187
188
189     // The current WebView is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
190     // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, `applyProxyThroughOrbot()`, and `applyDomainSettings()`.
191     private NestedScrollWebView currentWebView;
192
193     // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
194     private final Map<String, String> customHeaders = new HashMap<>();
195
196     // The search URL is set in `applyProxyThroughOrbot()` and used in `onCreate()`, `onNewIntent()`, `loadURLFromTextBox()`, and `initializeWebView()`.
197     private String searchURL;
198
199     // The options menu is set in `onCreateOptionsMenu()` and used in `onOptionsItemSelected()`, `updatePrivacyIcons()`, and `initializeWebView()`.
200     private Menu optionsMenu;
201
202     // The blocklists are populated in `onCreate()` and accessed from `initializeWebView()`.
203     private ArrayList<List<String[]>> easyList;
204     private ArrayList<List<String[]>> easyPrivacy;
205     private ArrayList<List<String[]>> fanboysAnnoyanceList;
206     private ArrayList<List<String[]>> fanboysSocialList;
207     private ArrayList<List<String[]>> ultraPrivacy;
208
209     // `webViewDefaultUserAgent` is used in `onCreate()` and `onPrepareOptionsMenu()`.
210     private String webViewDefaultUserAgent;
211
212     // `proxyThroughOrbot` is used in `onRestart()`, `onOptionsItemSelected()`, `applyAppSettings()`, and `applyProxyThroughOrbot()`.
213     private boolean proxyThroughOrbot;
214
215     // The incognito mode is set in `applyAppSettings()` and used in `initializeWebView()`.
216     private boolean incognitoModeEnabled;
217
218     // The full screen browsing mode tracker is set it `applyAppSettings()` and used in `initializeWebView()`.
219     private boolean fullScreenBrowsingModeEnabled;
220
221     // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
222     private boolean inFullScreenBrowsingMode;
223
224     // The app bar trackers are set in `applyAppSettings()` and used in `initializeWebView()`.
225     private boolean hideAppBar;
226     private boolean scrollAppBar;
227
228     // The loading new intent tracker is set in `onNewIntent()` and used in `setCurrentWebView()`.
229     private boolean loadingNewIntent;
230
231     // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
232     private boolean reapplyDomainSettingsOnRestart;
233
234     // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
235     private boolean reapplyAppSettingsOnRestart;
236
237     // `displayingFullScreenVideo` is used in `onCreate()` and `onResume()`.
238     private boolean displayingFullScreenVideo;
239
240     // `orbotStatusBroadcastReceiver` is used in `onCreate()` and `onDestroy()`.
241     private BroadcastReceiver orbotStatusBroadcastReceiver;
242
243     // `waitingForOrbot` is used in `onCreate()`, `onResume()`, and `applyProxyThroughOrbot()`.
244     private boolean waitingForOrbot;
245
246     // The action bar drawer toggle is initialized in `onCreate()` and used in `onResume()`.
247     private ActionBarDrawerToggle actionBarDrawerToggle;
248
249     // The color spans are used in `onCreate()` and `highlightUrlText()`.
250     private ForegroundColorSpan redColorSpan;
251     private ForegroundColorSpan initialGrayColorSpan;
252     private ForegroundColorSpan finalGrayColorSpan;
253
254     // The drawer header padding variables are used in `onCreate()` and `onConfigurationChanged()`.
255     private int drawerHeaderPaddingLeftAndRight;
256     private int drawerHeaderPaddingTop;
257     private int drawerHeaderPaddingBottom;
258
259     // `bookmarksDatabaseHelper` is used in `onCreate()`, `onDestroy`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`,
260     // and `loadBookmarksFolder()`.
261     private BookmarksDatabaseHelper bookmarksDatabaseHelper;
262
263     // `bookmarksCursor` is used in `onDestroy()`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
264     private Cursor bookmarksCursor;
265
266     // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
267     private CursorAdapter bookmarksCursorAdapter;
268
269     // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
270     private String oldFolderNameString;
271
272     // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
273     private ValueCallback<Uri[]> fileChooserCallback;
274
275     // The default progress view offsets are set in `onCreate()` and used in `initializeWebView()`.
276     private int defaultProgressViewStartOffset;
277     private int defaultProgressViewEndOffset;
278
279     // The swipe refresh layout top padding is used when exiting full screen browsing mode.  It is used in an inner class in `initializeWebView()`.
280     private int swipeRefreshLayoutPaddingTop;
281
282     // The URL sanitizers are set in `applyAppSettings()` and used in `sanitizeUrl()`.
283     private boolean sanitizeGoogleAnalytics;
284     private boolean sanitizeFacebookClickIds;
285     private boolean sanitizeTwitterAmpRedirects;
286
287     // The download strings are used in `onCreate()`, `onRequestPermissionResult()` and `initializeWebView()`.
288     private String downloadUrl;
289     private String downloadContentDisposition;
290     private long downloadContentLength;
291
292     // `downloadImageUrl` is used in `onCreateContextMenu()` and `onRequestPermissionResult()`.
293     private String downloadImageUrl;
294
295     // The request codes are used in `onCreate()`, `onCreateContextMenu()`, `onCloseDownloadLocationPermissionDialog()`, `onRequestPermissionResult()`, and `initializeWebView()`.
296     private final int DOWNLOAD_FILE_REQUEST_CODE = 1;
297     private final int DOWNLOAD_IMAGE_REQUEST_CODE = 2;
298
299     @Override
300     // Remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
301     @SuppressLint("ClickableViewAccessibility")
302     protected void onCreate(Bundle savedInstanceState) {
303         // Get a handle for the shared preferences.
304         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
305
306         // Get the theme and screenshot preferences.
307         boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
308         boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
309
310         // Disable screenshots if not allowed.
311         if (!allowScreenshots) {
312             getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
313         }
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_framelayout);
327
328         // Get a handle for the input method.
329         InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
330
331         // Remove the lint warning below that the input method manager might be null.
332         assert inputMethodManager != null;
333
334         // Get a handle for the toolbar.
335         Toolbar toolbar = findViewById(R.id.toolbar);
336
337         // Set the action bar.  `SupportActionBar` must be used until the minimum API is >= 21.
338         setSupportActionBar(toolbar);
339
340         // Get a handle for the action bar.
341         ActionBar actionBar = getSupportActionBar();
342
343         // This is needed to get rid of the Android Studio warning that the action bar might be null.
344         assert actionBar != null;
345
346         // Add the custom layout, which shows the URL text bar.
347         actionBar.setCustomView(R.layout.url_app_bar);
348         actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
349
350         // Initialize the foreground color spans for highlighting the URLs.  We have to use the deprecated `getColor()` until API >= 23.
351         redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
352         initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
353         finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
354
355         // Get handles for the URL views.
356         EditText urlEditText = findViewById(R.id.url_edittext);
357
358         // Remove the formatting from `urlTextBar` when the user is editing the text.
359         urlEditText.setOnFocusChangeListener((View v, boolean hasFocus) -> {
360             if (hasFocus) {  // The user is editing the URL text box.
361                 // Remove the highlighting.
362                 urlEditText.getText().removeSpan(redColorSpan);
363                 urlEditText.getText().removeSpan(initialGrayColorSpan);
364                 urlEditText.getText().removeSpan(finalGrayColorSpan);
365             } else {  // The user has stopped editing the URL text box.
366                 // Move to the beginning of the string.
367                 urlEditText.setSelection(0);
368
369                 // Reapply the highlighting.
370                 highlightUrlText();
371             }
372         });
373
374         // Set the go button on the keyboard to load the URL in `urlTextBox`.
375         urlEditText.setOnKeyListener((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                 loadUrlFromTextBox();
380
381                 // If the enter key was pressed, consume the event.
382                 return true;
383             } else {
384                 // If any other key was pressed, do not consume the event.
385                 return false;
386             }
387         });
388
389         // Initialize the Orbot status and the waiting for Orbot trackers.
390         orbotStatus = "unknown";
391         waitingForOrbot = false;
392
393         // Create an Orbot status `BroadcastReceiver`.
394         orbotStatusBroadcastReceiver = new BroadcastReceiver() {
395             @Override
396             public void onReceive(Context context, Intent intent) {
397                 // Store the content of the status message in `orbotStatus`.
398                 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
399
400                 // If Privacy Browser is waiting on Orbot, load the website now that Orbot is connected.
401                 if (orbotStatus.equals("ON") && waitingForOrbot) {
402                     // Reset the waiting for Orbot status.
403                     waitingForOrbot = false;
404
405                     // Get the intent that started the app.
406                     Intent launchingIntent = getIntent();
407
408                     // Get the information from the intent.
409                     String launchingIntentAction = launchingIntent.getAction();
410                     Uri launchingIntentUriData = launchingIntent.getData();
411
412                     // If the intent action is a web search, perform the search.
413                     if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) {
414                         // Create an encoded URL string.
415                         String encodedUrlString;
416
417                         // Sanitize the search input and convert it to a search.
418                         try {
419                             encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
420                         } catch (UnsupportedEncodingException exception) {
421                             encodedUrlString = "";
422                         }
423
424                         // Load the completed search URL.
425                         loadUrl(searchURL + encodedUrlString);
426                     } else if (launchingIntentUriData != null){  // Check to see if the intent contains a new URL.
427                         // Load the URL from the intent.
428                         loadUrl(launchingIntentUriData.toString());
429                     } else {  // The is no URL in the intent.
430                         // Select the homepage based on the proxy through Orbot status.
431                         if (proxyThroughOrbot) {
432                             // Load the Tor homepage.
433                             loadUrl(sharedPreferences.getString("tor_homepage", getString(R.string.tor_homepage_default_value)));
434                         } else {
435                             // Load the normal homepage.
436                             loadUrl(sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
437                         }
438                     }
439                 }
440             }
441         };
442
443         // Register `orbotStatusBroadcastReceiver` on `this` context.
444         this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
445
446         // Instantiate the blocklist helper.
447         BlockListHelper blockListHelper = new BlockListHelper();
448
449         // Parse the block lists.
450         easyList = blockListHelper.parseBlockList(getAssets(), "blocklists/easylist.txt");
451         easyPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/easyprivacy.txt");
452         fanboysAnnoyanceList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-annoyance.txt");
453         fanboysSocialList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-social.txt");
454         ultraPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/ultraprivacy.txt");
455
456         // Get handles for views that need to be modified.
457         DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
458         NavigationView navigationView = findViewById(R.id.navigationview);
459         TabLayout tabLayout = findViewById(R.id.tablayout);
460         SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
461         ViewPager webViewPager = findViewById(R.id.webviewpager);
462         ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
463         FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
464         FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
465         FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
466         EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
467
468         // Listen for touches on the navigation menu.
469         navigationView.setNavigationItemSelectedListener(this);
470
471         // Get handles for the navigation menu and the back and forward menu items.  The menu is zero-based.
472         Menu navigationMenu = navigationView.getMenu();
473         MenuItem navigationBackMenuItem = navigationMenu.getItem(2);
474         MenuItem navigationForwardMenuItem = navigationMenu.getItem(3);
475         MenuItem navigationHistoryMenuItem = navigationMenu.getItem(4);
476         MenuItem navigationRequestsMenuItem = navigationMenu.getItem(5);
477
478         // Initialize the web view pager adapter.
479         webViewPagerAdapter = new WebViewPagerAdapter(getSupportFragmentManager());
480
481         // Set the pager adapter on the web view pager.
482         webViewPager.setAdapter(webViewPagerAdapter);
483
484         // Store up to 100 tabs in memory.
485         webViewPager.setOffscreenPageLimit(100);
486
487         // Update the web view pager every time a tab is modified.
488         webViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
489             @Override
490             public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
491                 // Do nothing.
492             }
493
494             @Override
495             public void onPageSelected(int position) {
496                 // Close the find on page bar if it is open.
497                 closeFindOnPage(null);
498
499                 // Set the current WebView.
500                 setCurrentWebView(position);
501
502                 // Select the corresponding tab if it does not match the currently selected page.  This will happen if the page was scrolled via swiping in the view pager or by creating a new tab.
503                 if (tabLayout.getSelectedTabPosition() != position) {
504                     // Create a handler to select the tab.
505                     Handler selectTabHandler = new Handler();
506
507                     // Create a runnable select the new tab.
508                     Runnable selectTabRunnable = () -> {
509                         // Get a handle for the tab.
510                         TabLayout.Tab tab = tabLayout.getTabAt(position);
511
512                         // Assert that the tab is not null.
513                         assert tab != null;
514
515                         // Select the tab.
516                         tab.select();
517                     };
518
519                     // Select the tab layout after 100 milliseconds, which leaves enough time for a new tab to be created.
520                     selectTabHandler.postDelayed(selectTabRunnable, 100);
521                 }
522             }
523
524             @Override
525             public void onPageScrollStateChanged(int state) {
526                 // Do nothing.
527             }
528         });
529
530         // Display the View SSL Certificate dialog when the currently selected tab is reselected.
531         tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
532             @Override
533             public void onTabSelected(TabLayout.Tab tab) {
534                 // Select the same page in the view pager.
535                 webViewPager.setCurrentItem(tab.getPosition());
536             }
537
538             @Override
539             public void onTabUnselected(TabLayout.Tab tab) {
540                 // Do nothing.
541             }
542
543             @Override
544             public void onTabReselected(TabLayout.Tab tab) {
545                 // Instantiate the View SSL Certificate dialog.
546                 DialogFragment viewSslCertificateDialogFragment = ViewSslCertificateDialog.displayDialog(currentWebView.getWebViewFragmentId());
547
548                 // Display the View SSL Certificate dialog.
549                 viewSslCertificateDialogFragment.show(getSupportFragmentManager(), getString(R.string.view_ssl_certificate));
550             }
551         });
552
553         // Add the first tab.
554         addTab(null);
555
556         // Set the bookmarks drawer resources according to the theme.  This can't be done in the layout due to compatibility issues with the `DrawerLayout` support widget.
557         // The deprecated `getResources().getDrawable()` must be used until the minimum API >= 21 and and `getResources().getColor()` must be used until the minimum API >= 23.
558         if (darkTheme) {
559             launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
560             createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
561             createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
562             bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
563         } else {
564             launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
565             createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
566             createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
567             bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
568         }
569
570         // Set the launch bookmarks activity FAB to launch the bookmarks activity.
571         launchBookmarksActivityFab.setOnClickListener(v -> {
572             // Get a copy of the favorite icon bitmap.
573             Bitmap favoriteIconBitmap = currentWebView.getFavoriteOrDefaultIcon();
574
575             // Create a favorite icon byte array output stream.
576             ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
577
578             // Convert the favorite icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
579             favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
580
581             // Convert the favorite icon byte array stream to a byte array.
582             byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
583
584             // Create an intent to launch the bookmarks activity.
585             Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
586
587             // Add the extra information to the intent.
588             bookmarksIntent.putExtra("current_url", currentWebView.getUrl());
589             bookmarksIntent.putExtra("current_title", currentWebView.getTitle());
590             bookmarksIntent.putExtra("current_folder", currentBookmarksFolder);
591             bookmarksIntent.putExtra("favorite_icon_byte_array", favoriteIconByteArray);
592
593             // Make it so.
594             startActivity(bookmarksIntent);
595         });
596
597         // Set the create new bookmark folder FAB to display an alert dialog.
598         createBookmarkFolderFab.setOnClickListener(v -> {
599             // Create a create bookmark folder dialog.
600             DialogFragment createBookmarkFolderDialog = CreateBookmarkFolderDialog.createBookmarkFolder(currentWebView.getFavoriteOrDefaultIcon());
601
602             // Show the create bookmark folder dialog.
603             createBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.create_folder));
604         });
605
606         // Set the create new bookmark FAB to display an alert dialog.
607         createBookmarkFab.setOnClickListener(view -> {
608             // Instantiate the create bookmark dialog.
609             DialogFragment createBookmarkDialog = CreateBookmarkDialog.createBookmark(currentWebView.getUrl(), currentWebView.getTitle(), currentWebView.getFavoriteOrDefaultIcon());
610
611             // Display the create bookmark dialog.
612             createBookmarkDialog.show(getSupportFragmentManager(), getString(R.string.create_bookmark));
613         });
614
615         // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
616         findOnPageEditText.addTextChangedListener(new TextWatcher() {
617             @Override
618             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
619                 // Do nothing.
620             }
621
622             @Override
623             public void onTextChanged(CharSequence s, int start, int before, int count) {
624                 // Do nothing.
625             }
626
627             @Override
628             public void afterTextChanged(Editable s) {
629                 // Search for the text in the WebView if it is not null.  Sometimes on resume after a period of non-use the WebView will be null.
630                 if (currentWebView != null) {
631                     currentWebView.findAllAsync(findOnPageEditText.getText().toString());
632                 }
633             }
634         });
635
636         // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
637         findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
638             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {  // The `enter` key was pressed.
639                 // Hide the soft keyboard.
640                 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
641
642                 // Consume the event.
643                 return true;
644             } else {  // A different key was pressed.
645                 // Do not consume the event.
646                 return false;
647             }
648         });
649
650         // Implement swipe to refresh.
651         swipeRefreshLayout.setOnRefreshListener(() -> currentWebView.reload());
652
653         // Store the default progress view offsets for use later in `initializeWebView()`.
654         defaultProgressViewStartOffset = swipeRefreshLayout.getProgressViewStartOffset();
655         defaultProgressViewEndOffset = swipeRefreshLayout.getProgressViewEndOffset();
656
657         // Set the swipe to refresh color according to the theme.
658         if (darkTheme) {
659             swipeRefreshLayout.setColorSchemeResources(R.color.blue_800);
660             swipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.gray_850);
661         } else {
662             swipeRefreshLayout.setColorSchemeResources(R.color.blue_500);
663         }
664
665         // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
666         drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
667         drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
668
669         // Initialize the bookmarks database helper.  The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
670         bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
671
672         // Initialize `currentBookmarksFolder`.  `""` is the home folder in the database.
673         currentBookmarksFolder = "";
674
675         // Load the home folder, which is `""` in the database.
676         loadBookmarksFolder();
677
678         bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
679             // Convert the id from long to int to match the format of the bookmarks database.
680             int databaseID = (int) id;
681
682             // Get the bookmark cursor for this ID and move it to the first row.
683             Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseID);
684             bookmarkCursor.moveToFirst();
685
686             // Act upon the bookmark according to the type.
687             if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {  // The selected bookmark is a folder.
688                 // Store the new folder name in `currentBookmarksFolder`.
689                 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
690
691                 // Load the new folder.
692                 loadBookmarksFolder();
693             } else {  // The selected bookmark is not a folder.
694                 // Load the bookmark URL.
695                 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
696
697                 // Close the bookmarks drawer.
698                 drawerLayout.closeDrawer(GravityCompat.END);
699             }
700
701             // Close the `Cursor`.
702             bookmarkCursor.close();
703         });
704
705         bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
706             // Convert the database ID from `long` to `int`.
707             int databaseId = (int) id;
708
709             // Find out if the selected bookmark is a folder.
710             boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
711
712             if (isFolder) {
713                 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
714                 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
715
716                 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
717                 DialogFragment editBookmarkFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId, currentWebView.getFavoriteOrDefaultIcon());
718                 editBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.edit_folder));
719             } else {
720                 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
721                 DialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId, currentWebView.getFavoriteOrDefaultIcon());
722                 editBookmarkDialog.show(getSupportFragmentManager(), getString(R.string.edit_bookmark));
723             }
724
725             // Consume the event.
726             return true;
727         });
728
729         // Get the status bar pixel size.
730         int statusBarResourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
731         int statusBarPixelSize = getResources().getDimensionPixelSize(statusBarResourceId);
732
733         // Get the resource density.
734         float screenDensity = getResources().getDisplayMetrics().density;
735
736         // Calculate the drawer header padding.  This is used to move the text in the drawer headers below any cutouts.
737         drawerHeaderPaddingLeftAndRight = (int) (15 * screenDensity);
738         drawerHeaderPaddingTop = statusBarPixelSize + (int) (4 * screenDensity);
739         drawerHeaderPaddingBottom = (int) (8 * screenDensity);
740
741         // The drawer listener is used to update the navigation menu.`
742         drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
743             @Override
744             public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
745             }
746
747             @Override
748             public void onDrawerOpened(@NonNull View drawerView) {
749             }
750
751             @Override
752             public void onDrawerClosed(@NonNull View drawerView) {
753             }
754
755             @Override
756             public void onDrawerStateChanged(int newState) {
757                 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) {  // A drawer is opening or closing.
758                     // Get handles for the drawer headers.
759                     TextView navigationHeaderTextView = findViewById(R.id.navigationText);
760                     TextView bookmarksHeaderTextView = findViewById(R.id.bookmarks_title_textview);
761
762                     // Apply the navigation header paddings if the view is not null (sometimes it is null if another activity has already started).  This moves the text in the header below any cutouts.
763                     if (navigationHeaderTextView != null) {
764                         navigationHeaderTextView.setPadding(drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingTop, drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingBottom);
765                     }
766
767                     // Apply the bookmarks header paddings if the view is not null (sometimes it is null if another activity has already started).  This moves the text in the header below any cutouts.
768                     if (bookmarksHeaderTextView != null) {
769                         bookmarksHeaderTextView.setPadding(drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingTop, drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingBottom);
770                     }
771
772                     // Update the navigation menu items.
773                     navigationBackMenuItem.setEnabled(currentWebView.canGoBack());
774                     navigationForwardMenuItem.setEnabled(currentWebView.canGoForward());
775                     navigationHistoryMenuItem.setEnabled((currentWebView.canGoBack() || currentWebView.canGoForward()));
776                     navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
777
778                     // Hide the keyboard (if displayed).
779                     inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
780
781                     // Clear the focus from from the URL text box and the WebView.  This removes any text selection markers and context menus, which otherwise draw above the open drawers.
782                     urlEditText.clearFocus();
783                     currentWebView.clearFocus();
784                 }
785             }
786         });
787
788         // Create the hamburger icon at the start of the AppBar.
789         actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
790
791         // 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).
792         customHeaders.put("X-Requested-With", "");
793
794         // Initialize the default preference values the first time the program is run.  `false` keeps this command from resetting any current preferences back to default.
795         PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
796
797         // Inflate a bare WebView to get the default user agent.  It is not used to render content on the screen.
798         @SuppressLint("InflateParams") View webViewLayout = getLayoutInflater().inflate(R.layout.bare_webview, null, false);
799
800         // Get a handle for the WebView.
801         WebView bareWebView = webViewLayout.findViewById(R.id.bare_webview);
802
803         // Store the default user agent.
804         webViewDefaultUserAgent = bareWebView.getSettings().getUserAgentString();
805
806         // Destroy the bare WebView.
807         bareWebView.destroy();
808     }
809
810     @Override
811     protected void onNewIntent(Intent intent) {
812         // Get the information from the intent.
813         String intentAction = intent.getAction();
814         Uri intentUriData = intent.getData();
815
816         // Determine if this is a web search.
817         boolean isWebSearch = ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH));
818
819         // Only process the URI if it contains data or it is a web search.  If the user pressed the desktop icon after the app was already running the URI will be null.
820         if (intentUriData != null || isWebSearch) {
821             // Get the shared preferences.
822             SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
823
824             // Create a URL string.
825             String url;
826
827             // If the intent action is a web search, perform the search.
828             if (isWebSearch) {
829                 // Create an encoded URL string.
830                 String encodedUrlString;
831
832                 // Sanitize the search input and convert it to a search.
833                 try {
834                     encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
835                 } catch (UnsupportedEncodingException exception) {
836                     encodedUrlString = "";
837                 }
838
839                 // Add the base search URL.
840                 url = searchURL + encodedUrlString;
841             } else {  // The intent should contain a URL.
842                 // Set the intent data as the URL.
843                 url = intentUriData.toString();
844             }
845
846             // Add a new tab if specified in the preferences.
847             if (sharedPreferences.getBoolean("open_intents_in_new_tab", true)) {  // Load the URL in a new tab.
848                 // Set the loading new intent flag.
849                 loadingNewIntent = true;
850
851                 // Add a new tab.
852                 addNewTab(url);
853             } else {  // Load the URL in the current tab.
854                 // Make it so.
855                 loadUrl(url);
856             }
857
858             // Get a handle for the drawer layout.
859             DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
860
861             // Close the navigation drawer if it is open.
862             if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
863                 drawerLayout.closeDrawer(GravityCompat.START);
864             }
865
866             // Close the bookmarks drawer if it is open.
867             if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
868                 drawerLayout.closeDrawer(GravityCompat.END);
869             }
870         }
871     }
872
873     @Override
874     public void onRestart() {
875         // Run the default commands.
876         super.onRestart();
877
878         // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
879         if (proxyThroughOrbot) {
880             // Request Orbot to start.  If Orbot is already running no hard will be caused by this request.
881             Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
882
883             // Send the intent to the Orbot package.
884             orbotIntent.setPackage("org.torproject.android");
885
886             // Make it so.
887             sendBroadcast(orbotIntent);
888         }
889
890         // Apply the app settings if returning from the Settings activity.
891         if (reapplyAppSettingsOnRestart) {
892             // Reset the reapply app settings on restart tracker.
893             reapplyAppSettingsOnRestart = false;
894
895             // Apply the app settings.
896             applyAppSettings();
897         }
898
899         // Apply the domain settings if returning from the settings or domains activity.
900         if (reapplyDomainSettingsOnRestart) {
901             // Reset the reapply domain settings on restart tracker.
902             reapplyDomainSettingsOnRestart = false;
903
904             // Reapply the domain settings for each tab.
905             for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
906                 // Get the WebView tab fragment.
907                 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
908
909                 // Get the fragment view.
910                 View fragmentView = webViewTabFragment.getView();
911
912                 // Only reload the WebViews if they exist.
913                 if (fragmentView != null) {
914                     // Get the nested scroll WebView from the tab fragment.
915                     NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
916
917                     // Reset the current domain name so the domain settings will be reapplied.
918                     nestedScrollWebView.resetCurrentDomainName();
919
920                     // Reapply the domain settings if the URL is not null, which can happen if an empty tab is active when returning from settings.
921                     if (nestedScrollWebView.getUrl() != null) {
922                         applyDomainSettings(nestedScrollWebView, nestedScrollWebView.getUrl(), false, true);
923                     }
924                 }
925             }
926         }
927
928         // Load the URL on restart (used when loading a bookmark).
929         if (loadUrlOnRestart) {
930             // Load the specified URL.
931             loadUrl(urlToLoadOnRestart);
932
933             // Reset the load on restart tracker.
934             loadUrlOnRestart = false;
935         }
936
937         // Update the bookmarks drawer if returning from the Bookmarks activity.
938         if (restartFromBookmarksActivity) {
939             // Get a handle for the drawer layout.
940             DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
941
942             // Close the bookmarks drawer.
943             drawerLayout.closeDrawer(GravityCompat.END);
944
945             // Reload the bookmarks drawer.
946             loadBookmarksFolder();
947
948             // Reset `restartFromBookmarksActivity`.
949             restartFromBookmarksActivity = false;
950         }
951
952         // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.  This can be important if the screen was rotated.
953         updatePrivacyIcons(true);
954     }
955
956     // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
957     @Override
958     public void onResume() {
959         // Run the default commands.
960         super.onResume();
961
962         for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
963             // Get the WebView tab fragment.
964             WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
965
966             // Get the fragment view.
967             View fragmentView = webViewTabFragment.getView();
968
969             // Only resume the WebViews if they exist (they won't when the app is first created).
970             if (fragmentView != null) {
971                 // Get the nested scroll WebView from the tab fragment.
972                 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
973
974                 // Resume the nested scroll WebView JavaScript timers.
975                 nestedScrollWebView.resumeTimers();
976
977                 // Resume the nested scroll WebView.
978                 nestedScrollWebView.onResume();
979             }
980         }
981
982         // Display a message to the user if waiting for Orbot.
983         if (waitingForOrbot && !orbotStatus.equals("ON")) {
984             // Disable the wide view port so that the waiting for Orbot text is displayed correctly.
985             currentWebView.getSettings().setUseWideViewPort(false);
986
987             // Load a waiting page.  `null` specifies no encoding, which defaults to ASCII.
988             currentWebView.loadData("<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>", "text/html", null);
989         }
990
991         if (displayingFullScreenVideo || inFullScreenBrowsingMode) {
992             // Get a handle for the root frame layouts.
993             FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
994
995             // Remove the translucent status flag.  This is necessary so the root frame layout can fill the entire screen.
996             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
997
998             /* Hide the system bars.
999              * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1000              * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
1001              * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1002              * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1003              */
1004             rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
1005                     View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1006         } else if (BuildConfig.FLAVOR.contentEquals("free")) {  // Resume the adView for the free flavor.
1007             // Resume the ad.
1008             AdHelper.resumeAd(findViewById(R.id.adview));
1009         }
1010     }
1011
1012     @Override
1013     public void onPause() {
1014         // Run the default commands.
1015         super.onPause();
1016
1017         for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
1018             // Get the WebView tab fragment.
1019             WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
1020
1021             // Get the fragment view.
1022             View fragmentView = webViewTabFragment.getView();
1023
1024             // Only pause the WebViews if they exist (they won't when the app is first created).
1025             if (fragmentView != null) {
1026                 // Get the nested scroll WebView from the tab fragment.
1027                 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
1028
1029                 // Pause the nested scroll WebView.
1030                 nestedScrollWebView.onPause();
1031
1032                 // Pause the nested scroll WebView JavaScript timers.
1033                 nestedScrollWebView.pauseTimers();
1034             }
1035         }
1036
1037         // Pause the ad or it will continue to consume resources in the background on the free flavor.
1038         if (BuildConfig.FLAVOR.contentEquals("free")) {
1039             // Pause the ad.
1040             AdHelper.pauseAd(findViewById(R.id.adview));
1041         }
1042     }
1043
1044     @Override
1045     public void onDestroy() {
1046         // Unregister the Orbot status broadcast receiver.
1047         this.unregisterReceiver(orbotStatusBroadcastReceiver);
1048
1049         // Close the bookmarks cursor and database.
1050         bookmarksCursor.close();
1051         bookmarksDatabaseHelper.close();
1052
1053         // Run the default commands.
1054         super.onDestroy();
1055     }
1056
1057     @Override
1058     public boolean onCreateOptionsMenu(Menu menu) {
1059         // Inflate the menu.  This adds items to the action bar if it is present.
1060         getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1061
1062         // Store a handle for the options menu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons()`.
1063         optionsMenu = menu;
1064
1065         // Set the initial status of the privacy icons.  `false` does not call `invalidateOptionsMenu` as the last step.
1066         updatePrivacyIcons(false);
1067
1068         // Get handles for the menu items.
1069         MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1070         MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1071         MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1072         MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);  // Form data can be removed once the minimum API >= 26.
1073         MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);  // Form data can be removed once the minimum API >= 26.
1074         MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1075         MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
1076
1077         // Only display third-party cookies if API >= 21
1078         toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1079
1080         // Only display the form data menu items if the API < 26.
1081         toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1082         clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1083
1084         // Disable the clear form data menu item if the API >= 26 so that the status of the main Clear Data is calculated correctly.
1085         clearFormDataMenuItem.setEnabled(Build.VERSION.SDK_INT < 26);
1086
1087         // Only show Ad Consent if this is the free flavor.
1088         adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
1089
1090         // Get the shared preferences.
1091         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1092
1093         // Get the dark theme and app bar preferences..
1094         boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
1095         boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
1096
1097         // Set the status of the additional app bar icons.  Setting the refresh menu item to `SHOW_AS_ACTION_ALWAYS` makes it appear even on small devices like phones.
1098         if (displayAdditionalAppBarIcons) {
1099             toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1100             toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1101             refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
1102         } else { //Do not display the additional icons.
1103             toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1104             toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1105             refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1106         }
1107
1108         // Replace Refresh with Stop if a URL is already loading.
1109         if (currentWebView != null && currentWebView.getProgress() != 100) {
1110             // Set the title.
1111             refreshMenuItem.setTitle(R.string.stop);
1112
1113             // If the icon is displayed in the AppBar, set it according to the theme.
1114             if (displayAdditionalAppBarIcons) {
1115                 if (darkTheme) {
1116                     refreshMenuItem.setIcon(R.drawable.close_dark);
1117                 } else {
1118                     refreshMenuItem.setIcon(R.drawable.close_light);
1119                 }
1120             }
1121         }
1122
1123         return true;
1124     }
1125
1126     @Override
1127     public boolean onPrepareOptionsMenu(Menu menu) {
1128         // Get handles for the menu items.
1129         MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
1130         MenuItem firstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1131         MenuItem thirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1132         MenuItem domStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1133         MenuItem saveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);  // Form data can be removed once the minimum API >= 26.
1134         MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
1135         MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1136         MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1137         MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);  // Form data can be removed once the minimum API >= 26.
1138         MenuItem blocklistsMenuItem = menu.findItem(R.id.blocklists);
1139         MenuItem easyListMenuItem = menu.findItem(R.id.easylist);
1140         MenuItem easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
1141         MenuItem fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
1142         MenuItem fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
1143         MenuItem ultraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
1144         MenuItem blockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
1145         MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1146         MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
1147         MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1148         MenuItem nightModeMenuItem = menu.findItem(R.id.night_mode);
1149         MenuItem proxyThroughOrbotMenuItem = menu.findItem(R.id.proxy_through_orbot);
1150
1151         // Get a handle for the cookie manager.
1152         CookieManager cookieManager = CookieManager.getInstance();
1153
1154         // Initialize the current user agent string and the font size.
1155         String currentUserAgent = getString(R.string.user_agent_privacy_browser);
1156         int fontSize = 100;
1157
1158         // Set items that require the current web view to be populated.  It will be null when the program is first opened, as `onPrepareOptionsMenu()` is called before the first WebView is initialized.
1159         if (currentWebView != null) {
1160             // Set the add or edit domain text.
1161             if (currentWebView.getDomainSettingsApplied()) {
1162                 addOrEditDomain.setTitle(R.string.edit_domain_settings);
1163             } else {
1164                 addOrEditDomain.setTitle(R.string.add_domain_settings);
1165             }
1166
1167             // Get the current user agent from the WebView.
1168             currentUserAgent = currentWebView.getSettings().getUserAgentString();
1169
1170             // Get the current font size from the
1171             fontSize = currentWebView.getSettings().getTextZoom();
1172
1173             // Set the status of the menu item checkboxes.
1174             domStorageMenuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1175             saveFormDataMenuItem.setChecked(currentWebView.getSettings().getSaveFormData());  // Form data can be removed once the minimum API >= 26.
1176             easyListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST));
1177             easyPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY));
1178             fanboysAnnoyanceListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1179             fanboysSocialBlockingListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1180             ultraPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY));
1181             blockAllThirdPartyRequestsMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1182             swipeToRefreshMenuItem.setChecked(currentWebView.getSwipeToRefresh());
1183             displayImagesMenuItem.setChecked(currentWebView.getSettings().getLoadsImagesAutomatically());
1184             nightModeMenuItem.setChecked(currentWebView.getNightMode());
1185
1186             // Initialize the display names for the blocklists with the number of blocked requests.
1187             blocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
1188             easyListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASY_LIST) + " - " + getString(R.string.easylist));
1189             easyPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASY_PRIVACY) + " - " + getString(R.string.easyprivacy));
1190             fanboysAnnoyanceListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " + getString(R.string.fanboys_annoyance_list));
1191             fanboysSocialBlockingListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " + getString(R.string.fanboys_social_blocking_list));
1192             ultraPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRA_PRIVACY) + " - " + getString(R.string.ultraprivacy));
1193             blockAllThirdPartyRequestsMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " + getString(R.string.block_all_third_party_requests));
1194
1195             // Only modify third-party cookies if the API >= 21.
1196             if (Build.VERSION.SDK_INT >= 21) {
1197                 // Set the status of the third-party cookies checkbox.
1198                 thirdPartyCookiesMenuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
1199
1200                 // Enable third-party cookies if first-party cookies are enabled.
1201                 thirdPartyCookiesMenuItem.setEnabled(cookieManager.acceptCookie());
1202             }
1203
1204             // Enable DOM Storage if JavaScript is enabled.
1205             domStorageMenuItem.setEnabled(currentWebView.getSettings().getJavaScriptEnabled());
1206         }
1207
1208         // Set the status of the menu item checkboxes.
1209         firstPartyCookiesMenuItem.setChecked(cookieManager.acceptCookie());
1210         proxyThroughOrbotMenuItem.setChecked(proxyThroughOrbot);
1211
1212         // Enable Clear Cookies if there are any.
1213         clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1214
1215         // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
1216         String privateDataDirectoryString = getApplicationInfo().dataDir;
1217
1218         // Get a count of the number of files in the Local Storage directory.
1219         File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1220         int localStorageDirectoryNumberOfFiles = 0;
1221         if (localStorageDirectory.exists()) {
1222             localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1223         }
1224
1225         // Get a count of the number of files in the IndexedDB directory.
1226         File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1227         int indexedDBDirectoryNumberOfFiles = 0;
1228         if (indexedDBDirectory.exists()) {
1229             indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1230         }
1231
1232         // Enable Clear DOM Storage if there is any.
1233         clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1234
1235         // Enable Clear Form Data is there is any.  This can be removed once the minimum API >= 26.
1236         if (Build.VERSION.SDK_INT < 26) {
1237             // Get the WebView database.
1238             WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1239
1240             // Enable the clear form data menu item if there is anything to clear.
1241             clearFormDataMenuItem.setEnabled(webViewDatabase.hasFormData());
1242         }
1243
1244         // Enable Clear Data if any of the submenu items are enabled.
1245         clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
1246
1247         // Disable Fanboy's Social Blocking List menu item if Fanboy's Annoyance List is checked.
1248         fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListMenuItem.isChecked());
1249
1250         // Select the current user agent menu item.  A switch statement cannot be used because the user agents are not compile time constants.
1251         if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) {  // Privacy Browser.
1252             menu.findItem(R.id.user_agent_privacy_browser).setChecked(true);
1253         } else if (currentUserAgent.equals(webViewDefaultUserAgent)) {  // WebView Default.
1254             menu.findItem(R.id.user_agent_webview_default).setChecked(true);
1255         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) {  // Firefox on Android.
1256             menu.findItem(R.id.user_agent_firefox_on_android).setChecked(true);
1257         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) {  // Chrome on Android.
1258             menu.findItem(R.id.user_agent_chrome_on_android).setChecked(true);
1259         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) {  // Safari on iOS.
1260             menu.findItem(R.id.user_agent_safari_on_ios).setChecked(true);
1261         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) {  // Firefox on Linux.
1262             menu.findItem(R.id.user_agent_firefox_on_linux).setChecked(true);
1263         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) {  // Chromium on Linux.
1264             menu.findItem(R.id.user_agent_chromium_on_linux).setChecked(true);
1265         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) {  // Firefox on Windows.
1266             menu.findItem(R.id.user_agent_firefox_on_windows).setChecked(true);
1267         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) {  // Chrome on Windows.
1268             menu.findItem(R.id.user_agent_chrome_on_windows).setChecked(true);
1269         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) {  // Edge on Windows.
1270             menu.findItem(R.id.user_agent_edge_on_windows).setChecked(true);
1271         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) {  // Internet Explorer on Windows.
1272             menu.findItem(R.id.user_agent_internet_explorer_on_windows).setChecked(true);
1273         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) {  // Safari on macOS.
1274             menu.findItem(R.id.user_agent_safari_on_macos).setChecked(true);
1275         } else {  // Custom user agent.
1276             menu.findItem(R.id.user_agent_custom).setChecked(true);
1277         }
1278
1279         // Instantiate the font size title and the selected font size menu item.
1280         String fontSizeTitle;
1281         MenuItem selectedFontSizeMenuItem;
1282
1283         // Prepare the font size title and current size menu item.
1284         switch (fontSize) {
1285             case 25:
1286                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
1287                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1288                 break;
1289
1290             case 50:
1291                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
1292                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1293                 break;
1294
1295             case 75:
1296                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
1297                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1298                 break;
1299
1300             case 100:
1301                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1302                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1303                 break;
1304
1305             case 125:
1306                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
1307                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1308                 break;
1309
1310             case 150:
1311                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
1312                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1313                 break;
1314
1315             case 175:
1316                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
1317                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1318                 break;
1319
1320             case 200:
1321                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
1322                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1323                 break;
1324
1325             default:
1326                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1327                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1328                 break;
1329         }
1330
1331         // Set the font size title and select the current size menu item.
1332         fontSizeMenuItem.setTitle(fontSizeTitle);
1333         selectedFontSizeMenuItem.setChecked(true);
1334
1335         // Run all the other default commands.
1336         super.onPrepareOptionsMenu(menu);
1337
1338         // Display the menu.
1339         return true;
1340     }
1341
1342     @Override
1343     // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1344     @SuppressLint("SetJavaScriptEnabled")
1345     public boolean onOptionsItemSelected(MenuItem menuItem) {
1346         // Reenter full screen browsing mode if it was interrupted by the options menu.  <https://redmine.stoutner.com/issues/389>
1347         if (inFullScreenBrowsingMode) {
1348             // Remove the translucent status flag.  This is necessary so the root frame layout can fill the entire screen.
1349             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1350
1351             FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
1352
1353             /* Hide the system bars.
1354              * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1355              * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
1356              * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1357              * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1358              */
1359             rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
1360                     View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1361         }
1362
1363         // Get the selected menu item ID.
1364         int menuItemId = menuItem.getItemId();
1365
1366         // Get a handle for the shared preferences.
1367         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1368
1369         // Get a handle for the cookie manager.
1370         CookieManager cookieManager = CookieManager.getInstance();
1371
1372         // Run the commands that correlate to the selected menu item.
1373         switch (menuItemId) {
1374             case R.id.toggle_javascript:
1375                 // Toggle the JavaScript status.
1376                 currentWebView.getSettings().setJavaScriptEnabled(!currentWebView.getSettings().getJavaScriptEnabled());
1377
1378                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1379                 updatePrivacyIcons(true);
1380
1381                 // Display a `Snackbar`.
1382                 if (currentWebView.getSettings().getJavaScriptEnabled()) {  // JavaScrip is enabled.
1383                     Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1384                 } else if (cookieManager.acceptCookie()) {  // JavaScript is disabled, but first-party cookies are enabled.
1385                     Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1386                 } else {  // Privacy mode.
1387                     Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1388                 }
1389
1390                 // Reload the current WebView.
1391                 currentWebView.reload();
1392                 return true;
1393
1394             case R.id.add_or_edit_domain:
1395                 if (currentWebView.getDomainSettingsApplied()) {  // Edit the current domain settings.
1396                     // Reapply the domain settings on returning to `MainWebViewActivity`.
1397                     reapplyDomainSettingsOnRestart = true;
1398
1399                     // Create an intent to launch the domains activity.
1400                     Intent domainsIntent = new Intent(this, DomainsActivity.class);
1401
1402                     // Add the extra information to the intent.
1403                     domainsIntent.putExtra("load_domain", currentWebView.getDomainSettingsDatabaseId());
1404                     domainsIntent.putExtra("close_on_back", true);
1405                     domainsIntent.putExtra("current_url", currentWebView.getUrl());
1406
1407                     // Get the current certificate.
1408                     SslCertificate sslCertificate = currentWebView.getCertificate();
1409
1410                     // Check to see if the SSL certificate is populated.
1411                     if (sslCertificate != null) {
1412                         // Extract the certificate to strings.
1413                         String issuedToCName = sslCertificate.getIssuedTo().getCName();
1414                         String issuedToOName = sslCertificate.getIssuedTo().getOName();
1415                         String issuedToUName = sslCertificate.getIssuedTo().getUName();
1416                         String issuedByCName = sslCertificate.getIssuedBy().getCName();
1417                         String issuedByOName = sslCertificate.getIssuedBy().getOName();
1418                         String issuedByUName = sslCertificate.getIssuedBy().getUName();
1419                         long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1420                         long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1421
1422                         // Add the certificate to the intent.
1423                         domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1424                         domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1425                         domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1426                         domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1427                         domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1428                         domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1429                         domainsIntent.putExtra("ssl_start_date", startDateLong);
1430                         domainsIntent.putExtra("ssl_end_date", endDateLong);
1431                     }
1432
1433                     // Check to see if the current IP addresses have been received.
1434                     if (currentWebView.hasCurrentIpAddresses()) {
1435                         // Add the current IP addresses to the intent.
1436                         domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1437                     }
1438
1439                     // Make it so.
1440                     startActivity(domainsIntent);
1441                 } else {  // Add a new domain.
1442                     // Apply the new domain settings on returning to `MainWebViewActivity`.
1443                     reapplyDomainSettingsOnRestart = true;
1444
1445                     // Get the current domain
1446                     Uri currentUri = Uri.parse(currentWebView.getUrl());
1447                     String currentDomain = currentUri.getHost();
1448
1449                     // Initialize the database handler.  The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1450                     DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1451
1452                     // Create the domain and store the database ID.
1453                     int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1454
1455                     // Create an intent to launch the domains activity.
1456                     Intent domainsIntent = new Intent(this, DomainsActivity.class);
1457
1458                     // Add the extra information to the intent.
1459                     domainsIntent.putExtra("load_domain", newDomainDatabaseId);
1460                     domainsIntent.putExtra("close_on_back", true);
1461                     domainsIntent.putExtra("current_url", currentWebView.getUrl());
1462
1463                     // Get the current certificate.
1464                     SslCertificate sslCertificate = currentWebView.getCertificate();
1465
1466                     // Check to see if the SSL certificate is populated.
1467                     if (sslCertificate != null) {
1468                         // Extract the certificate to strings.
1469                         String issuedToCName = sslCertificate.getIssuedTo().getCName();
1470                         String issuedToOName = sslCertificate.getIssuedTo().getOName();
1471                         String issuedToUName = sslCertificate.getIssuedTo().getUName();
1472                         String issuedByCName = sslCertificate.getIssuedBy().getCName();
1473                         String issuedByOName = sslCertificate.getIssuedBy().getOName();
1474                         String issuedByUName = sslCertificate.getIssuedBy().getUName();
1475                         long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1476                         long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1477
1478                         // Add the certificate to the intent.
1479                         domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1480                         domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1481                         domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1482                         domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1483                         domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1484                         domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1485                         domainsIntent.putExtra("ssl_start_date", startDateLong);
1486                         domainsIntent.putExtra("ssl_end_date", endDateLong);
1487                     }
1488
1489                     // Check to see if the current IP addresses have been received.
1490                     if (currentWebView.hasCurrentIpAddresses()) {
1491                         // Add the current IP addresses to the intent.
1492                         domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1493                     }
1494
1495                     // Make it so.
1496                     startActivity(domainsIntent);
1497                 }
1498                 return true;
1499
1500             case R.id.toggle_first_party_cookies:
1501                 // Switch the first-party cookie status.
1502                 cookieManager.setAcceptCookie(!cookieManager.acceptCookie());
1503
1504                 // Store the first-party cookie status.
1505                 currentWebView.setAcceptFirstPartyCookies(cookieManager.acceptCookie());
1506
1507                 // Update the menu checkbox.
1508                 menuItem.setChecked(cookieManager.acceptCookie());
1509
1510                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1511                 updatePrivacyIcons(true);
1512
1513                 // Display a snackbar.
1514                 if (cookieManager.acceptCookie()) {  // First-party cookies are enabled.
1515                     Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1516                 } else if (currentWebView.getSettings().getJavaScriptEnabled()) {  // JavaScript is still enabled.
1517                     Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1518                 } else {  // Privacy mode.
1519                     Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1520                 }
1521
1522                 // Reload the current WebView.
1523                 currentWebView.reload();
1524                 return true;
1525
1526             case R.id.toggle_third_party_cookies:
1527                 if (Build.VERSION.SDK_INT >= 21) {
1528                     // Switch the status of thirdPartyCookiesEnabled.
1529                     cookieManager.setAcceptThirdPartyCookies(currentWebView, !cookieManager.acceptThirdPartyCookies(currentWebView));
1530
1531                     // Update the menu checkbox.
1532                     menuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
1533
1534                     // Display a snackbar.
1535                     if (cookieManager.acceptThirdPartyCookies(currentWebView)) {
1536                         Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1537                     } else {
1538                         Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1539                     }
1540
1541                     // Reload the current WebView.
1542                     currentWebView.reload();
1543                 } // Else do nothing because SDK < 21.
1544                 return true;
1545
1546             case R.id.toggle_dom_storage:
1547                 // Toggle the status of domStorageEnabled.
1548                 currentWebView.getSettings().setDomStorageEnabled(!currentWebView.getSettings().getDomStorageEnabled());
1549
1550                 // Update the menu checkbox.
1551                 menuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1552
1553                 // Update the privacy icon.  `true` refreshes the app bar icons.
1554                 updatePrivacyIcons(true);
1555
1556                 // Display a snackbar.
1557                 if (currentWebView.getSettings().getDomStorageEnabled()) {
1558                     Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1559                 } else {
1560                     Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1561                 }
1562
1563                 // Reload the current WebView.
1564                 currentWebView.reload();
1565                 return true;
1566
1567             // Form data can be removed once the minimum API >= 26.
1568             case R.id.toggle_save_form_data:
1569                 // Switch the status of saveFormDataEnabled.
1570                 currentWebView.getSettings().setSaveFormData(!currentWebView.getSettings().getSaveFormData());
1571
1572                 // Update the menu checkbox.
1573                 menuItem.setChecked(currentWebView.getSettings().getSaveFormData());
1574
1575                 // Display a snackbar.
1576                 if (currentWebView.getSettings().getSaveFormData()) {
1577                     Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1578                 } else {
1579                     Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1580                 }
1581
1582                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1583                 updatePrivacyIcons(true);
1584
1585                 // Reload the current WebView.
1586                 currentWebView.reload();
1587                 return true;
1588
1589             case R.id.clear_cookies:
1590                 Snackbar.make(findViewById(R.id.webviewpager), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1591                         .setAction(R.string.undo, v -> {
1592                             // Do nothing because everything will be handled by `onDismissed()` below.
1593                         })
1594                         .addCallback(new Snackbar.Callback() {
1595                             @SuppressLint("SwitchIntDef")  // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1596                             @Override
1597                             public void onDismissed(Snackbar snackbar, int event) {
1598                                 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) {  // The snackbar was dismissed without the undo button being pushed.
1599                                     // Delete the cookies, which command varies by SDK.
1600                                     if (Build.VERSION.SDK_INT < 21) {
1601                                         cookieManager.removeAllCookie();
1602                                     } else {
1603                                         cookieManager.removeAllCookies(null);
1604                                     }
1605                                 }
1606                             }
1607                         })
1608                         .show();
1609                 return true;
1610
1611             case R.id.clear_dom_storage:
1612                 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1613                         .setAction(R.string.undo, v -> {
1614                             // Do nothing because everything will be handled by `onDismissed()` below.
1615                         })
1616                         .addCallback(new Snackbar.Callback() {
1617                             @SuppressLint("SwitchIntDef")  // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1618                             @Override
1619                             public void onDismissed(Snackbar snackbar, int event) {
1620                                 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) {  // The snackbar was dismissed without the undo button being pushed.
1621                                     // Delete the DOM Storage.
1622                                     WebStorage webStorage = WebStorage.getInstance();
1623                                     webStorage.deleteAllData();
1624
1625                                     // Initialize a handler to manually delete the DOM storage files and directories.
1626                                     Handler deleteDomStorageHandler = new Handler();
1627
1628                                     // Setup a runnable to manually delete the DOM storage files and directories.
1629                                     Runnable deleteDomStorageRunnable = () -> {
1630                                         try {
1631                                             // Get a handle for the runtime.
1632                                             Runtime runtime = Runtime.getRuntime();
1633
1634                                             // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
1635                                             // which links to `/data/data/com.stoutner.privacybrowser.standard`.
1636                                             String privateDataDirectoryString = getApplicationInfo().dataDir;
1637
1638                                             // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1639                                             Process deleteLocalStorageProcess = runtime.exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1640
1641                                             // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1642                                             Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1643                                             Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1644                                             Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1645                                             Process deleteDatabasesProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1646
1647                                             // Wait for the processes to finish.
1648                                             deleteLocalStorageProcess.waitFor();
1649                                             deleteIndexProcess.waitFor();
1650                                             deleteQuotaManagerProcess.waitFor();
1651                                             deleteQuotaManagerJournalProcess.waitFor();
1652                                             deleteDatabasesProcess.waitFor();
1653                                         } catch (Exception exception) {
1654                                             // Do nothing if an error is thrown.
1655                                         }
1656                                     };
1657
1658                                     // Manually delete the DOM storage files after 200 milliseconds.
1659                                     deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200);
1660                                 }
1661                             }
1662                         })
1663                         .show();
1664                 return true;
1665
1666             // Form data can be remove once the minimum API >= 26.
1667             case R.id.clear_form_data:
1668                 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1669                         .setAction(R.string.undo, v -> {
1670                             // Do nothing because everything will be handled by `onDismissed()` below.
1671                         })
1672                         .addCallback(new Snackbar.Callback() {
1673                             @SuppressLint("SwitchIntDef")  // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1674                             @Override
1675                             public void onDismissed(Snackbar snackbar, int event) {
1676                                 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) {  // The snackbar was dismissed without the undo button being pushed.
1677                                     // Delete the form data.
1678                                     WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1679                                     mainWebViewDatabase.clearFormData();
1680                                 }
1681                             }
1682                         })
1683                         .show();
1684                 return true;
1685
1686             case R.id.easylist:
1687                 // Toggle the EasyList status.
1688                 currentWebView.enableBlocklist(NestedScrollWebView.EASY_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST));
1689
1690                 // Update the menu checkbox.
1691                 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST));
1692
1693                 // Reload the current WebView.
1694                 currentWebView.reload();
1695                 return true;
1696
1697             case R.id.easyprivacy:
1698                 // Toggle the EasyPrivacy status.
1699                 currentWebView.enableBlocklist(NestedScrollWebView.EASY_PRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY));
1700
1701                 // Update the menu checkbox.
1702                 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY));
1703
1704                 // Reload the current WebView.
1705                 currentWebView.reload();
1706                 return true;
1707
1708             case R.id.fanboys_annoyance_list:
1709                 // Toggle Fanboy's Annoyance List status.
1710                 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1711
1712                 // Update the menu checkbox.
1713                 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1714
1715                 // Update the staus of Fanboy's Social Blocking List.
1716                 MenuItem fanboysSocialBlockingListMenuItem = optionsMenu.findItem(R.id.fanboys_social_blocking_list);
1717                 fanboysSocialBlockingListMenuItem.setEnabled(!currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1718
1719                 // Reload the current WebView.
1720                 currentWebView.reload();
1721                 return true;
1722
1723             case R.id.fanboys_social_blocking_list:
1724                 // Toggle Fanboy's Social Blocking List status.
1725                 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1726
1727                 // Update the menu checkbox.
1728                 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1729
1730                 // Reload the current WebView.
1731                 currentWebView.reload();
1732                 return true;
1733
1734             case R.id.ultraprivacy:
1735                 // Toggle the UltraPrivacy status.
1736                 currentWebView.enableBlocklist(NestedScrollWebView.ULTRA_PRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY));
1737
1738                 // Update the menu checkbox.
1739                 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY));
1740
1741                 // Reload the current WebView.
1742                 currentWebView.reload();
1743                 return true;
1744
1745             case R.id.block_all_third_party_requests:
1746                 //Toggle the third-party requests blocker status.
1747                 currentWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, !currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1748
1749                 // Update the menu checkbox.
1750                 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1751
1752                 // Reload the current WebView.
1753                 currentWebView.reload();
1754                 return true;
1755
1756             case R.id.user_agent_privacy_browser:
1757                 // Update the user agent.
1758                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
1759
1760                 // Reload the current WebView.
1761                 currentWebView.reload();
1762                 return true;
1763
1764             case R.id.user_agent_webview_default:
1765                 // Update the user agent.
1766                 currentWebView.getSettings().setUserAgentString("");
1767
1768                 // Reload the current WebView.
1769                 currentWebView.reload();
1770                 return true;
1771
1772             case R.id.user_agent_firefox_on_android:
1773                 // Update the user agent.
1774                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
1775
1776                 // Reload the current WebView.
1777                 currentWebView.reload();
1778                 return true;
1779
1780             case R.id.user_agent_chrome_on_android:
1781                 // Update the user agent.
1782                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
1783
1784                 // Reload the current WebView.
1785                 currentWebView.reload();
1786                 return true;
1787
1788             case R.id.user_agent_safari_on_ios:
1789                 // Update the user agent.
1790                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
1791
1792                 // Reload the current WebView.
1793                 currentWebView.reload();
1794                 return true;
1795
1796             case R.id.user_agent_firefox_on_linux:
1797                 // Update the user agent.
1798                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
1799
1800                 // Reload the current WebView.
1801                 currentWebView.reload();
1802                 return true;
1803
1804             case R.id.user_agent_chromium_on_linux:
1805                 // Update the user agent.
1806                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
1807
1808                 // Reload the current WebView.
1809                 currentWebView.reload();
1810                 return true;
1811
1812             case R.id.user_agent_firefox_on_windows:
1813                 // Update the user agent.
1814                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
1815
1816                 // Reload the current WebView.
1817                 currentWebView.reload();
1818                 return true;
1819
1820             case R.id.user_agent_chrome_on_windows:
1821                 // Update the user agent.
1822                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
1823
1824                 // Reload the current WebView.
1825                 currentWebView.reload();
1826                 return true;
1827
1828             case R.id.user_agent_edge_on_windows:
1829                 // Update the user agent.
1830                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
1831
1832                 // Reload the current WebView.
1833                 currentWebView.reload();
1834                 return true;
1835
1836             case R.id.user_agent_internet_explorer_on_windows:
1837                 // Update the user agent.
1838                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
1839
1840                 // Reload the current WebView.
1841                 currentWebView.reload();
1842                 return true;
1843
1844             case R.id.user_agent_safari_on_macos:
1845                 // Update the user agent.
1846                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
1847
1848                 // Reload the current WebView.
1849                 currentWebView.reload();
1850                 return true;
1851
1852             case R.id.user_agent_custom:
1853                 // Update the user agent.
1854                 currentWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
1855
1856                 // Reload the current WebView.
1857                 currentWebView.reload();
1858                 return true;
1859
1860             case R.id.font_size_twenty_five_percent:
1861                 currentWebView.getSettings().setTextZoom(25);
1862                 return true;
1863
1864             case R.id.font_size_fifty_percent:
1865                 currentWebView.getSettings().setTextZoom(50);
1866                 return true;
1867
1868             case R.id.font_size_seventy_five_percent:
1869                 currentWebView.getSettings().setTextZoom(75);
1870                 return true;
1871
1872             case R.id.font_size_one_hundred_percent:
1873                 currentWebView.getSettings().setTextZoom(100);
1874                 return true;
1875
1876             case R.id.font_size_one_hundred_twenty_five_percent:
1877                 currentWebView.getSettings().setTextZoom(125);
1878                 return true;
1879
1880             case R.id.font_size_one_hundred_fifty_percent:
1881                 currentWebView.getSettings().setTextZoom(150);
1882                 return true;
1883
1884             case R.id.font_size_one_hundred_seventy_five_percent:
1885                 currentWebView.getSettings().setTextZoom(175);
1886                 return true;
1887
1888             case R.id.font_size_two_hundred_percent:
1889                 currentWebView.getSettings().setTextZoom(200);
1890                 return true;
1891
1892             case R.id.swipe_to_refresh:
1893                 // Toggle the stored status of swipe to refresh.
1894                 currentWebView.setSwipeToRefresh(!currentWebView.getSwipeToRefresh());
1895
1896                 // Get a handle for the swipe refresh layout.
1897                 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
1898
1899                 // Update the swipe refresh layout.
1900                 if (currentWebView.getSwipeToRefresh()) {  // Swipe to refresh is enabled.
1901                     if (Build.VERSION.SDK_INT >= 23) {  // For API >= 23, the status of the scroll refresh listener is continuously updated by the on scroll change listener.
1902                         // Only enable the swipe refresh layout if the WebView is scrolled to the top.
1903                         swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
1904                     } else {  // For API < 23, the swipe refresh layout is always enabled.
1905                         // Enable the swipe refresh layout.
1906                         swipeRefreshLayout.setEnabled(true);
1907                     }
1908                 } else {  // Swipe to refresh is disabled.
1909                     // Disable the swipe refresh layout.
1910                     swipeRefreshLayout.setEnabled(false);
1911                 }
1912                 return true;
1913
1914             case R.id.display_images:
1915                 if (currentWebView.getSettings().getLoadsImagesAutomatically()) {  // Images are currently loaded automatically.
1916                     // Disable loading of images.
1917                     currentWebView.getSettings().setLoadsImagesAutomatically(false);
1918
1919                     // Reload the website to remove existing images.
1920                     currentWebView.reload();
1921                 } else {  // Images are not currently loaded automatically.
1922                     // Enable loading of images.  Missing images will be loaded without the need for a reload.
1923                     currentWebView.getSettings().setLoadsImagesAutomatically(true);
1924                 }
1925                 return true;
1926
1927             case R.id.night_mode:
1928                 // Toggle night mode.
1929                 currentWebView.setNightMode(!currentWebView.getNightMode());
1930
1931                 // Enable or disable JavaScript according to night mode, the global preference, and any domain settings.
1932                 if (currentWebView.getNightMode()) {  // Night mode is enabled, which requires JavaScript.
1933                     // Enable JavaScript.
1934                     currentWebView.getSettings().setJavaScriptEnabled(true);
1935                 } else if (currentWebView.getDomainSettingsApplied()) {  // Night mode is disabled and domain settings are applied.  Set JavaScript according to the domain settings.
1936                     // Apply the JavaScript preference that was stored the last time domain settings were loaded.
1937                     currentWebView.getSettings().setJavaScriptEnabled(currentWebView.getDomainSettingsJavaScriptEnabled());
1938                 } else {  // Night mode is disabled and domain settings are not applied.  Set JavaScript according to the global preference.
1939                     // Apply the JavaScript preference.
1940                     currentWebView.getSettings().setJavaScriptEnabled(sharedPreferences.getBoolean("javascript", false));
1941                 }
1942
1943                 // Update the privacy icons.
1944                 updatePrivacyIcons(false);
1945
1946                 // Reload the website.
1947                 currentWebView.reload();
1948                 return true;
1949
1950             case R.id.find_on_page:
1951                 // Get a handle for the views.
1952                 Toolbar toolbar = findViewById(R.id.toolbar);
1953                 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
1954                 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
1955
1956                 // Set the minimum height of the find on page linear layout to match the toolbar.
1957                 findOnPageLinearLayout.setMinimumHeight(toolbar.getHeight());
1958
1959                 // Hide the toolbar.
1960                 toolbar.setVisibility(View.GONE);
1961
1962                 // Show the find on page linear layout.
1963                 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1964
1965                 // Display the keyboard.  The app must wait 200 ms before running the command to work around a bug in Android.
1966                 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1967                 findOnPageEditText.postDelayed(() -> {
1968                     // Set the focus on `findOnPageEditText`.
1969                     findOnPageEditText.requestFocus();
1970
1971                     // Get a handle for the input method manager.
1972                     InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1973
1974                     // Remove the lint warning below that the input method manager might be null.
1975                     assert inputMethodManager != null;
1976
1977                     // Display the keyboard.  `0` sets no input flags.
1978                     inputMethodManager.showSoftInput(findOnPageEditText, 0);
1979                 }, 200);
1980                 return true;
1981
1982             case R.id.view_source:
1983                 // Create an intent to launch the view source activity.
1984                 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
1985
1986                 // Add the variables to the intent.
1987                 viewSourceIntent.putExtra("user_agent", currentWebView.getSettings().getUserAgentString());
1988                 viewSourceIntent.putExtra("current_url", currentWebView.getUrl());
1989
1990                 // Make it so.
1991                 startActivity(viewSourceIntent);
1992                 return true;
1993
1994             case R.id.share_url:
1995                 // Setup the share string.
1996                 String shareString = currentWebView.getTitle() + " – " + currentWebView.getUrl();
1997
1998                 // Create the share intent.
1999                 Intent shareIntent = new Intent(Intent.ACTION_SEND);
2000                 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
2001                 shareIntent.setType("text/plain");
2002
2003                 // Make it so.
2004                 startActivity(Intent.createChooser(shareIntent, getString(R.string.share_url)));
2005                 return true;
2006
2007             case R.id.print:
2008                 // Get a print manager instance.
2009                 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
2010
2011                 // Remove the lint error below that print manager might be null.
2012                 assert printManager != null;
2013
2014                 // Create a print document adapter from the current WebView.
2015                 PrintDocumentAdapter printDocumentAdapter = currentWebView.createPrintDocumentAdapter();
2016
2017                 // Print the document.
2018                 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
2019                 return true;
2020
2021             case R.id.open_with_app:
2022                 openWithApp(currentWebView.getUrl());
2023                 return true;
2024
2025             case R.id.open_with_browser:
2026                 openWithBrowser(currentWebView.getUrl());
2027                 return true;
2028
2029             case R.id.add_to_homescreen:
2030                 // Instantiate the create home screen shortcut dialog.
2031                 DialogFragment createHomeScreenShortcutDialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView.getTitle(), currentWebView.getUrl(),
2032                         currentWebView.getFavoriteOrDefaultIcon());
2033
2034                 // Show the create home screen shortcut dialog.
2035                 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2036                 return true;
2037
2038             case R.id.proxy_through_orbot:
2039                 // Toggle the proxy through Orbot variable.
2040                 proxyThroughOrbot = !proxyThroughOrbot;
2041
2042                 // Apply the proxy through Orbot settings.
2043                 applyProxyThroughOrbot(true);
2044                 return true;
2045
2046             case R.id.refresh:
2047                 if (menuItem.getTitle().equals(getString(R.string.refresh))) {  // The refresh button was pushed.
2048                     // Reload the current WebView.
2049                     currentWebView.reload();
2050                 } else {  // The stop button was pushed.
2051                     // Stop the loading of the WebView.
2052                     currentWebView.stopLoading();
2053                 }
2054                 return true;
2055
2056             case R.id.ad_consent:
2057                 // Display the ad consent dialog.
2058                 DialogFragment adConsentDialogFragment = new AdConsentDialog();
2059                 adConsentDialogFragment.show(getSupportFragmentManager(), getString(R.string.ad_consent));
2060                 return true;
2061
2062             default:
2063                 // Don't consume the event.
2064                 return super.onOptionsItemSelected(menuItem);
2065         }
2066     }
2067
2068     // removeAllCookies is deprecated, but it is required for API < 21.
2069     @Override
2070     public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2071         // Get the menu item ID.
2072         int menuItemId = menuItem.getItemId();
2073
2074         // Get a handle for the shared preferences.
2075         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2076
2077         // Run the commands that correspond to the selected menu item.
2078         switch (menuItemId) {
2079             case R.id.clear_and_exit:
2080                 // Clear and exit Privacy Browser.
2081                 clearAndExit();
2082                 break;
2083
2084             case R.id.home:
2085                 // Select the homepage based on the proxy through Orbot status.
2086                 if (proxyThroughOrbot) {
2087                     // Load the Tor homepage.
2088                     loadUrl(sharedPreferences.getString("tor_homepage", getString(R.string.tor_homepage_default_value)));
2089                 } else {
2090                     // Load the normal homepage.
2091                     loadUrl(sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
2092                 }
2093                 break;
2094
2095             case R.id.back:
2096                 if (currentWebView.canGoBack()) {
2097                     // Reset the current domain name so that navigation works if third-party requests are blocked.
2098                     currentWebView.resetCurrentDomainName();
2099
2100                     // Set navigating history so that the domain settings are applied when the new URL is loaded.
2101                     currentWebView.setNavigatingHistory(true);
2102
2103                     // Load the previous website in the history.
2104                     currentWebView.goBack();
2105                 }
2106                 break;
2107
2108             case R.id.forward:
2109                 if (currentWebView.canGoForward()) {
2110                     // Reset the current domain name so that navigation works if third-party requests are blocked.
2111                     currentWebView.resetCurrentDomainName();
2112
2113                     // Set navigating history so that the domain settings are applied when the new URL is loaded.
2114                     currentWebView.setNavigatingHistory(true);
2115
2116                     // Load the next website in the history.
2117                     currentWebView.goForward();
2118                 }
2119                 break;
2120
2121             case R.id.history:
2122                 // Instantiate the URL history dialog.
2123                 DialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(currentWebView.getWebViewFragmentId());
2124
2125                 // Show the URL history dialog.
2126                 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2127                 break;
2128
2129             case R.id.requests:
2130                 // Populate the resource requests.
2131                 RequestsActivity.resourceRequests = currentWebView.getResourceRequests();
2132
2133                 // Create an intent to launch the Requests activity.
2134                 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2135
2136                 // Add the block third-party requests status to the intent.
2137                 requestsIntent.putExtra("block_all_third_party_requests", currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
2138
2139                 // Make it so.
2140                 startActivity(requestsIntent);
2141                 break;
2142
2143             case R.id.downloads:
2144                 // Launch the system Download Manager.
2145                 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2146
2147                 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2148                 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2149
2150                 startActivity(downloadManagerIntent);
2151                 break;
2152
2153             case R.id.domains:
2154                 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2155                 reapplyDomainSettingsOnRestart = true;
2156
2157                 // Launch the domains activity.
2158                 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2159
2160                 // Add the extra information to the intent.
2161                 domainsIntent.putExtra("current_url", currentWebView.getUrl());
2162
2163                 // Get the current certificate.
2164                 SslCertificate sslCertificate = currentWebView.getCertificate();
2165
2166                 // Check to see if the SSL certificate is populated.
2167                 if (sslCertificate != null) {
2168                     // Extract the certificate to strings.
2169                     String issuedToCName = sslCertificate.getIssuedTo().getCName();
2170                     String issuedToOName = sslCertificate.getIssuedTo().getOName();
2171                     String issuedToUName = sslCertificate.getIssuedTo().getUName();
2172                     String issuedByCName = sslCertificate.getIssuedBy().getCName();
2173                     String issuedByOName = sslCertificate.getIssuedBy().getOName();
2174                     String issuedByUName = sslCertificate.getIssuedBy().getUName();
2175                     long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
2176                     long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
2177
2178                     // Add the certificate to the intent.
2179                     domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
2180                     domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
2181                     domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
2182                     domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
2183                     domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
2184                     domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
2185                     domainsIntent.putExtra("ssl_start_date", startDateLong);
2186                     domainsIntent.putExtra("ssl_end_date", endDateLong);
2187                 }
2188
2189                 // Check to see if the current IP addresses have been received.
2190                 if (currentWebView.hasCurrentIpAddresses()) {
2191                     // Add the current IP addresses to the intent.
2192                     domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
2193                 }
2194
2195                 // Make it so.
2196                 startActivity(domainsIntent);
2197                 break;
2198
2199             case R.id.settings:
2200                 // Set the flag to reapply app settings on restart when returning from Settings.
2201                 reapplyAppSettingsOnRestart = true;
2202
2203                 // Set the flag to reapply the domain settings on restart when returning from Settings.
2204                 reapplyDomainSettingsOnRestart = true;
2205
2206                 // Launch the settings activity.
2207                 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2208                 startActivity(settingsIntent);
2209                 break;
2210
2211             case R.id.import_export:
2212                 // Launch the import/export activity.
2213                 Intent importExportIntent = new Intent (this, ImportExportActivity.class);
2214                 startActivity(importExportIntent);
2215                 break;
2216
2217             case R.id.logcat:
2218                 // Launch the logcat activity.
2219                 Intent logcatIntent = new Intent(this, LogcatActivity.class);
2220                 startActivity(logcatIntent);
2221                 break;
2222
2223             case R.id.guide:
2224                 // Launch `GuideActivity`.
2225                 Intent guideIntent = new Intent(this, GuideActivity.class);
2226                 startActivity(guideIntent);
2227                 break;
2228
2229             case R.id.about:
2230                 // Create an intent to launch the about activity.
2231                 Intent aboutIntent = new Intent(this, AboutActivity.class);
2232
2233                 // Create a string array for the blocklist versions.
2234                 String[] blocklistVersions = new String[] {easyList.get(0).get(0)[0], easyPrivacy.get(0).get(0)[0], fanboysAnnoyanceList.get(0).get(0)[0], fanboysSocialList.get(0).get(0)[0],
2235                         ultraPrivacy.get(0).get(0)[0]};
2236
2237                 // Add the blocklist versions to the intent.
2238                 aboutIntent.putExtra("blocklist_versions", blocklistVersions);
2239
2240                 // Make it so.
2241                 startActivity(aboutIntent);
2242                 break;
2243         }
2244
2245         // Get a handle for the drawer layout.
2246         DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
2247
2248         // Close the navigation drawer.
2249         drawerLayout.closeDrawer(GravityCompat.START);
2250         return true;
2251     }
2252
2253     @Override
2254     public void onPostCreate(Bundle savedInstanceState) {
2255         // Run the default commands.
2256         super.onPostCreate(savedInstanceState);
2257
2258         // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished.  This creates the navigation drawer icon.
2259         actionBarDrawerToggle.syncState();
2260     }
2261
2262     @Override
2263     public void onConfigurationChanged(Configuration newConfig) {
2264         // Run the default commands.
2265         super.onConfigurationChanged(newConfig);
2266
2267         // Get the status bar pixel size.
2268         int statusBarResourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
2269         int statusBarPixelSize = getResources().getDimensionPixelSize(statusBarResourceId);
2270
2271         // Get the resource density.
2272         float screenDensity = getResources().getDisplayMetrics().density;
2273
2274         // Recalculate the drawer header padding.
2275         drawerHeaderPaddingLeftAndRight = (int) (15 * screenDensity);
2276         drawerHeaderPaddingTop = statusBarPixelSize + (int) (4 * screenDensity);
2277         drawerHeaderPaddingBottom = (int) (8 * screenDensity);
2278
2279         // Reload the ad for the free flavor if not in full screen mode.
2280         if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2281             // Reload the ad.  The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2282             AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
2283         }
2284
2285         // `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:
2286         // https://code.google.com/p/android/issues/detail?id=20493#c8
2287         // ActivityCompat.invalidateOptionsMenu(this);
2288     }
2289
2290     @Override
2291     public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2292         // Store the hit test result.
2293         final WebView.HitTestResult hitTestResult = currentWebView.getHitTestResult();
2294
2295         // Create the URL strings.
2296         final String imageUrl;
2297         final String linkUrl;
2298
2299         // Get handles for the system managers.
2300         final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2301         FragmentManager fragmentManager = getSupportFragmentManager();
2302         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2303
2304         // Remove the lint errors below that the clipboard manager might be null.
2305         assert clipboardManager != null;
2306
2307         // Process the link according to the type.
2308         switch (hitTestResult.getType()) {
2309             // `SRC_ANCHOR_TYPE` is a link.
2310             case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2311                 // Get the target URL.
2312                 linkUrl = hitTestResult.getExtra();
2313
2314                 // Set the target URL as the title of the `ContextMenu`.
2315                 menu.setHeaderTitle(linkUrl);
2316
2317                 // Add an Open in New Tab entry.
2318                 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2319                     // Load the link URL in a new tab.
2320                     addNewTab(linkUrl);
2321                     return false;
2322                 });
2323
2324                 // Add an Open with App entry.
2325                 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2326                     openWithApp(linkUrl);
2327                     return false;
2328                 });
2329
2330                 // Add an Open with Browser entry.
2331                 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2332                     openWithBrowser(linkUrl);
2333                     return false;
2334                 });
2335
2336                 // Add a Copy URL entry.
2337                 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2338                     // Save the link URL in a `ClipData`.
2339                     ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2340
2341                     // Set the `ClipData` as the clipboard's primary clip.
2342                     clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2343                     return false;
2344                 });
2345
2346                 // Add a Download URL entry.
2347                 menu.add(R.string.download_url).setOnMenuItemClickListener((MenuItem item) -> {
2348                     // Check if the download should be processed by an external app.
2349                     if (sharedPreferences.getBoolean("download_with_external_app", false)) {  // Download with an external app.
2350                         openUrlWithExternalApp(linkUrl);
2351                     } else {  // Download with Android's download manager.
2352                         // Check to see if the storage permission has already been granted.
2353                         if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {  // The storage permission needs to be requested.
2354                             // Store the variables for future use by `onRequestPermissionsResult()`.
2355                             downloadUrl = linkUrl;
2356                             downloadContentDisposition = "none";
2357                             downloadContentLength = -1;
2358
2359                             // Show a dialog if the user has previously denied the permission.
2360                             if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {  // Show a dialog explaining the request first.
2361                                 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
2362                                 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
2363
2364                                 // Show the download location permission alert dialog.  The permission will be requested when the the dialog is closed.
2365                                 downloadLocationPermissionDialogFragment.show(fragmentManager, getString(R.string.download_location));
2366                             } else {  // Show the permission request directly.
2367                                 // Request the permission.  The download dialog will be launched by `onRequestPermissionResult()`.
2368                                 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2369                             }
2370                         } else {  // The storage permission has already been granted.
2371                             // Get a handle for the download file alert dialog.
2372                             DialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(linkUrl, "none", -1);
2373
2374                             // Show the download file alert dialog.
2375                             downloadFileDialogFragment.show(fragmentManager, getString(R.string.download));
2376                         }
2377                     }
2378                     return false;
2379                 });
2380
2381                 // Add a Cancel entry, which by default closes the context menu.
2382                 menu.add(R.string.cancel);
2383                 break;
2384
2385             case WebView.HitTestResult.EMAIL_TYPE:
2386                 // Get the target URL.
2387                 linkUrl = hitTestResult.getExtra();
2388
2389                 // Set the target URL as the title of the `ContextMenu`.
2390                 menu.setHeaderTitle(linkUrl);
2391
2392                 // Add a Write Email entry.
2393                 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2394                     // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2395                     Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2396
2397                     // Parse the url and set it as the data for the `Intent`.
2398                     emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2399
2400                     // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2401                     emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2402
2403                     // Make it so.
2404                     startActivity(emailIntent);
2405                     return false;
2406                 });
2407
2408                 // Add a Copy Email Address entry.
2409                 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2410                     // Save the email address in a `ClipData`.
2411                     ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2412
2413                     // Set the `ClipData` as the clipboard's primary clip.
2414                     clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2415                     return false;
2416                 });
2417
2418                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2419                 menu.add(R.string.cancel);
2420                 break;
2421
2422             // `IMAGE_TYPE` is an image. `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.  Privacy Browser processes them the same.
2423             case WebView.HitTestResult.IMAGE_TYPE:
2424             case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2425                 // Get the image URL.
2426                 imageUrl = hitTestResult.getExtra();
2427
2428                 // Set the image URL as the title of the context menu.
2429                 menu.setHeaderTitle(imageUrl);
2430
2431                 // Add an Open in New Tab entry.
2432                 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2433                     // Load the image URL in a new tab.
2434                     addNewTab(imageUrl);
2435                     return false;
2436                 });
2437
2438                 // Add a View Image entry.
2439                 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2440                     loadUrl(imageUrl);
2441                     return false;
2442                 });
2443
2444                 // Add a `Download Image` entry.
2445                 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2446                     // Check if the download should be processed by an external app.
2447                     if (sharedPreferences.getBoolean("download_with_external_app", false)) {  // Download with an external app.
2448                         openUrlWithExternalApp(imageUrl);
2449                     } else {  // Download with Android's download manager.
2450                         // Check to see if the storage permission has already been granted.
2451                         if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {  // The storage permission needs to be requested.
2452                             // Store the image URL for use by `onRequestPermissionResult()`.
2453                             downloadImageUrl = imageUrl;
2454
2455                             // Show a dialog if the user has previously denied the permission.
2456                             if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {  // Show a dialog explaining the request first.
2457                                 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2458                                 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2459
2460                                 // Show the download location permission alert dialog.  The permission will be requested when the dialog is closed.
2461                                 downloadLocationPermissionDialogFragment.show(fragmentManager, getString(R.string.download_location));
2462                             } else {  // Show the permission request directly.
2463                                 // Request the permission.  The download dialog will be launched by `onRequestPermissionResult().
2464                                 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2465                             }
2466                         } else {  // The storage permission has already been granted.
2467                             // Get a handle for the download image alert dialog.
2468                             DialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2469
2470                             // Show the download image alert dialog.
2471                             downloadImageDialogFragment.show(fragmentManager, getString(R.string.download));
2472                         }
2473                     }
2474                     return false;
2475                 });
2476
2477                 // Add a `Copy URL` entry.
2478                 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2479                     // Save the image URL in a `ClipData`.
2480                     ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2481
2482                     // Set the `ClipData` as the clipboard's primary clip.
2483                     clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2484                     return false;
2485                 });
2486
2487                 // Add an Open with App entry.
2488                 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2489                     openWithApp(imageUrl);
2490                     return false;
2491                 });
2492
2493                 // Add an Open with Browser entry.
2494                 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2495                     openWithBrowser(imageUrl);
2496                     return false;
2497                 });
2498
2499                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2500                 menu.add(R.string.cancel);
2501                 break;
2502         }
2503     }
2504
2505     @Override
2506     public void onCreateBookmark(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2507         // Get a handle for the bookmarks list view.
2508         ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2509
2510         // Get the views from the dialog fragment.
2511         EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
2512         EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
2513
2514         // Extract the strings from the edit texts.
2515         String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2516         String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2517
2518         // Create a favorite icon byte array output stream.
2519         ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2520
2521         // Convert the favorite icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
2522         favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2523
2524         // Convert the favorite icon byte array stream to a byte array.
2525         byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2526
2527         // Display the new bookmark below the current items in the (0 indexed) list.
2528         int newBookmarkDisplayOrder = bookmarksListView.getCount();
2529
2530         // Create the bookmark.
2531         bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2532
2533         // Update the bookmarks cursor with the current contents of this folder.
2534         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2535
2536         // Update the list view.
2537         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2538
2539         // Scroll to the new bookmark.
2540         bookmarksListView.setSelection(newBookmarkDisplayOrder);
2541     }
2542
2543     @Override
2544     public void onCreateBookmarkFolder(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2545         // Get a handle for the bookmarks list view.
2546         ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2547
2548         // Get handles for the views in the dialog fragment.
2549         EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
2550         RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
2551         ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
2552
2553         // Get new folder name string.
2554         String folderNameString = createFolderNameEditText.getText().toString();
2555
2556         // Create a folder icon bitmap.
2557         Bitmap folderIconBitmap;
2558
2559         // Set the folder icon bitmap according to the dialog.
2560         if (defaultFolderIconRadioButton.isChecked()) {  // Use the default folder icon.
2561             // Get the default folder icon drawable.
2562             Drawable folderIconDrawable = folderIconImageView.getDrawable();
2563
2564             // Convert the folder icon drawable to a bitmap drawable.
2565             BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2566
2567             // Convert the folder icon bitmap drawable to a bitmap.
2568             folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2569         } else {  // Use the WebView favorite icon.
2570             // Copy the favorite icon bitmap to the folder icon bitmap.
2571             folderIconBitmap = favoriteIconBitmap;
2572         }
2573
2574         // Create a folder icon byte array output stream.
2575         ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2576
2577         // Convert the folder icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
2578         folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2579
2580         // Convert the folder icon byte array stream to a byte array.
2581         byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2582
2583         // Move all the bookmarks down one in the display order.
2584         for (int i = 0; i < bookmarksListView.getCount(); i++) {
2585             int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2586             bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2587         }
2588
2589         // Create the folder, which will be placed at the top of the `ListView`.
2590         bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2591
2592         // Update the bookmarks cursor with the current contents of this folder.
2593         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2594
2595         // Update the `ListView`.
2596         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2597
2598         // Scroll to the new folder.
2599         bookmarksListView.setSelection(0);
2600     }
2601
2602     @Override
2603     public void onSaveBookmark(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, Bitmap favoriteIconBitmap) {
2604         // Get handles for the views from `dialogFragment`.
2605         EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
2606         EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
2607         RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
2608
2609         // Store the bookmark strings.
2610         String bookmarkNameString = editBookmarkNameEditText.getText().toString();
2611         String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
2612
2613         // Update the bookmark.
2614         if (currentBookmarkIconRadioButton.isChecked()) {  // Update the bookmark without changing the favorite icon.
2615             bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
2616         } else {  // Update the bookmark using the `WebView` favorite icon.
2617             // Create a favorite icon byte array output stream.
2618             ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2619
2620             // Convert the favorite icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
2621             favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
2622
2623             // Convert the favorite icon byte array stream to a byte array.
2624             byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
2625
2626             //  Update the bookmark and the favorite icon.
2627             bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
2628         }
2629
2630         // Update the bookmarks cursor with the current contents of this folder.
2631         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2632
2633         // Update the list view.
2634         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2635     }
2636
2637     @Override
2638     public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId, Bitmap favoriteIconBitmap) {
2639         // Get handles for the views from `dialogFragment`.
2640         EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
2641         RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
2642         RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
2643         ImageView defaultFolderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
2644
2645         // Get the new folder name.
2646         String newFolderNameString = editFolderNameEditText.getText().toString();
2647
2648         // Check if the favorite icon has changed.
2649         if (currentFolderIconRadioButton.isChecked()) {  // Only the name has changed.
2650             // Update the name in the database.
2651             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2652         } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) {  // Only the icon has changed.
2653             // Create the new folder icon Bitmap.
2654             Bitmap folderIconBitmap;
2655
2656             // Populate the new folder icon bitmap.
2657             if (defaultFolderIconRadioButton.isChecked()) {
2658                 // Get the default folder icon drawable.
2659                 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2660
2661                 // Convert the folder icon drawable to a bitmap drawable.
2662                 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2663
2664                 // Convert the folder icon bitmap drawable to a bitmap.
2665                 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2666             } else {  // Use the `WebView` favorite icon.
2667                 // Copy the favorite icon bitmap to the folder icon bitmap.
2668                 folderIconBitmap = favoriteIconBitmap;
2669             }
2670
2671             // Create a folder icon byte array output stream.
2672             ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2673
2674             // Convert the folder icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
2675             folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2676
2677             // Convert the folder icon byte array stream to a byte array.
2678             byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2679
2680             // Update the folder icon in the database.
2681             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, newFolderIconByteArray);
2682         } else {  // The folder icon and the name have changed.
2683             // Get the new folder icon `Bitmap`.
2684             Bitmap folderIconBitmap;
2685             if (defaultFolderIconRadioButton.isChecked()) {
2686                 // Get the default folder icon drawable.
2687                 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2688
2689                 // Convert the folder icon drawable to a bitmap drawable.
2690                 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2691
2692                 // Convert the folder icon bitmap drawable to a bitmap.
2693                 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2694             } else {  // Use the `WebView` favorite icon.
2695                 // Copy the favorite icon bitmap to the folder icon bitmap.
2696                 folderIconBitmap = favoriteIconBitmap;
2697             }
2698
2699             // Create a folder icon byte array output stream.
2700             ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2701
2702             // Convert the folder icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
2703             folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2704
2705             // Convert the folder icon byte array stream to a byte array.
2706             byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2707
2708             // Update the folder name and icon in the database.
2709             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, newFolderIconByteArray);
2710         }
2711
2712         // Update the bookmarks cursor with the current contents of this folder.
2713         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2714
2715         // Update the `ListView`.
2716         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2717     }
2718
2719     @Override
2720     public void onCloseDownloadLocationPermissionDialog(int downloadType) {
2721         switch (downloadType) {
2722             case DownloadLocationPermissionDialog.DOWNLOAD_FILE:
2723                 // Request the WRITE_EXTERNAL_STORAGE permission with a file request code.
2724                 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2725                 break;
2726
2727             case DownloadLocationPermissionDialog.DOWNLOAD_IMAGE:
2728                 // Request the WRITE_EXTERNAL_STORAGE permission with an image request code.
2729                 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2730                 break;
2731         }
2732     }
2733
2734     @Override
2735     public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
2736         // Get a handle for the fragment manager.
2737         FragmentManager fragmentManager = getSupportFragmentManager();
2738
2739         switch (requestCode) {
2740             case DOWNLOAD_FILE_REQUEST_CODE:
2741                 // Show the download file alert dialog.  When the dialog closes, the correct command will be used based on the permission status.
2742                 DialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(downloadUrl, downloadContentDisposition, downloadContentLength);
2743
2744                 // On API 23, displaying the fragment must be delayed or the app will crash.
2745                 if (Build.VERSION.SDK_INT == 23) {
2746                     new Handler().postDelayed(() -> downloadFileDialogFragment.show(fragmentManager, getString(R.string.download)), 500);
2747                 } else {
2748                     downloadFileDialogFragment.show(fragmentManager, getString(R.string.download));
2749                 }
2750
2751                 // Reset the download variables.
2752                 downloadUrl = "";
2753                 downloadContentDisposition = "";
2754                 downloadContentLength = 0;
2755                 break;
2756
2757             case DOWNLOAD_IMAGE_REQUEST_CODE:
2758                 // Show the download image alert dialog.  When the dialog closes, the correct command will be used based on the permission status.
2759                 DialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(downloadImageUrl);
2760
2761                 // On API 23, displaying the fragment must be delayed or the app will crash.
2762                 if (Build.VERSION.SDK_INT == 23) {
2763                     new Handler().postDelayed(() -> downloadImageDialogFragment.show(fragmentManager, getString(R.string.download)), 500);
2764                 } else {
2765                     downloadImageDialogFragment.show(fragmentManager, getString(R.string.download));
2766                 }
2767
2768                 // Reset the image URL variable.
2769                 downloadImageUrl = "";
2770                 break;
2771         }
2772     }
2773
2774     @Override
2775     public void onDownloadImage(DialogFragment dialogFragment, String imageUrl) {
2776         // Download the image if it has an HTTP or HTTPS URI.
2777         if (imageUrl.startsWith("http")) {
2778             // Get a handle for the system `DOWNLOAD_SERVICE`.
2779             DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2780
2781             // Parse `imageUrl`.
2782             DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
2783
2784             // Get a handle for the cookie manager.
2785             CookieManager cookieManager = CookieManager.getInstance();
2786
2787             // Pass cookies to download manager if cookies are enabled.  This is required to download images from websites that require a login.
2788             // Code contributed 2017 Hendrik Knackstedt.  Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2789             if (cookieManager.acceptCookie()) {
2790                 // Get the cookies for `imageUrl`.
2791                 String cookies = cookieManager.getCookie(imageUrl);
2792
2793                 // Add the cookies to `downloadRequest`.  In the HTTP request header, cookies are named `Cookie`.
2794                 downloadRequest.addRequestHeader("Cookie", cookies);
2795             }
2796
2797             // Get the file name from the dialog fragment.
2798             EditText downloadImageNameEditText = dialogFragment.getDialog().findViewById(R.id.download_image_name);
2799             String imageName = downloadImageNameEditText.getText().toString();
2800
2801             // Specify the download location.
2802             if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {  // External write permission granted.
2803                 // Download to the public download directory.
2804                 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, imageName);
2805             } else {  // External write permission denied.
2806                 // Download to the app's external download directory.
2807                 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, imageName);
2808             }
2809
2810             // Allow `MediaScanner` to index the download if it is a media file.
2811             downloadRequest.allowScanningByMediaScanner();
2812
2813             // Add the URL as the description for the download.
2814             downloadRequest.setDescription(imageUrl);
2815
2816             // Show the download notification after the download is completed.
2817             downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2818
2819             // Remove the lint warning below that `downloadManager` might be `null`.
2820             assert downloadManager != null;
2821
2822             // Initiate the download.
2823             downloadManager.enqueue(downloadRequest);
2824         } else {  // The image is not an HTTP or HTTPS URI.
2825             Snackbar.make(currentWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
2826         }
2827     }
2828
2829     @Override
2830     public void onDownloadFile(DialogFragment dialogFragment, String downloadUrl) {
2831         // Download the file if it has an HTTP or HTTPS URI.
2832         if (downloadUrl.startsWith("http")) {
2833             // Get a handle for the system `DOWNLOAD_SERVICE`.
2834             DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2835
2836             // Parse `downloadUrl`.
2837             DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
2838
2839             // Get a handle for the cookie manager.
2840             CookieManager cookieManager = CookieManager.getInstance();
2841
2842             // Pass cookies to download manager if cookies are enabled.  This is required to download files from websites that require a login.
2843             // Code contributed 2017 Hendrik Knackstedt.  Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2844             if (cookieManager.acceptCookie()) {
2845                 // Get the cookies for `downloadUrl`.
2846                 String cookies = cookieManager.getCookie(downloadUrl);
2847
2848                 // Add the cookies to `downloadRequest`.  In the HTTP request header, cookies are named `Cookie`.
2849                 downloadRequest.addRequestHeader("Cookie", cookies);
2850             }
2851
2852             // Get the file name from the dialog fragment.
2853             EditText downloadFileNameEditText = dialogFragment.getDialog().findViewById(R.id.download_file_name);
2854             String fileName = downloadFileNameEditText.getText().toString();
2855
2856             // Specify the download location.
2857             if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {  // External write permission granted.
2858                 // Download to the public download directory.
2859                 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
2860             } else {  // External write permission denied.
2861                 // Download to the app's external download directory.
2862                 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, fileName);
2863             }
2864
2865             // Allow `MediaScanner` to index the download if it is a media file.
2866             downloadRequest.allowScanningByMediaScanner();
2867
2868             // Add the URL as the description for the download.
2869             downloadRequest.setDescription(downloadUrl);
2870
2871             // Show the download notification after the download is completed.
2872             downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2873
2874             // Remove the lint warning below that `downloadManager` might be `null`.
2875             assert downloadManager != null;
2876
2877             // Initiate the download.
2878             downloadManager.enqueue(downloadRequest);
2879         } else {  // The download is not an HTTP or HTTPS URI.
2880             Snackbar.make(currentWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
2881         }
2882     }
2883
2884     // Override `onBackPressed` to handle the navigation drawer and and the WebView.
2885     @Override
2886     public void onBackPressed() {
2887         // Get a handle for the drawer layout and the tab layout.
2888         DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
2889         TabLayout tabLayout = findViewById(R.id.tablayout);
2890
2891         if (drawerLayout.isDrawerVisible(GravityCompat.START)) {  // The navigation drawer is open.
2892             // Close the navigation drawer.
2893             drawerLayout.closeDrawer(GravityCompat.START);
2894         } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){  // The bookmarks drawer is open.
2895             if (currentBookmarksFolder.isEmpty()) {  // The home folder is displayed.
2896                 // close the bookmarks drawer.
2897                 drawerLayout.closeDrawer(GravityCompat.END);
2898             } else {  // A subfolder is displayed.
2899                 // Place the former parent folder in `currentFolder`.
2900                 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolderName(currentBookmarksFolder);
2901
2902                 // Load the new folder.
2903                 loadBookmarksFolder();
2904             }
2905         } else if (currentWebView.canGoBack()) {  // There is at least one item in the current WebView history.
2906             // Reset the current domain name so that navigation works if third-party requests are blocked.
2907             currentWebView.resetCurrentDomainName();
2908
2909             // Set navigating history so that the domain settings are applied when the new URL is loaded.
2910             currentWebView.setNavigatingHistory(true);
2911
2912             // Go back.
2913             currentWebView.goBack();
2914         } else if (tabLayout.getTabCount() > 1) {  // There are at least two tabs.
2915             // Close the current tab.
2916             closeCurrentTab();
2917         } else {  // There isn't anything to do in Privacy Browser.
2918             // Run the default commands.
2919             super.onBackPressed();
2920
2921             // Manually kill Privacy Browser.  Otherwise, it is glitchy when restarted.
2922             System.exit(0);
2923         }
2924     }
2925
2926     // Process the results of an upload file chooser.  Currently there is only one `startActivityForResult` in this activity, so the request code, used to differentiate them, is ignored.
2927     @Override
2928     public void onActivityResult(int requestCode, int resultCode, Intent data) {
2929         // File uploads only work on API >= 21.
2930         if (Build.VERSION.SDK_INT >= 21) {
2931             // Pass the file to the WebView.
2932             fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
2933         }
2934     }
2935
2936     private void loadUrlFromTextBox() {
2937         // Get a handle for the URL edit text.
2938         EditText urlEditText = findViewById(R.id.url_edittext);
2939
2940         // Get the text from urlTextBox and convert it to a string.  trim() removes white spaces from the beginning and end of the string.
2941         String unformattedUrlString = urlEditText.getText().toString().trim();
2942
2943         // Initialize the formatted URL string.
2944         String url = "";
2945
2946         // Check to see if `unformattedUrlString` is a valid URL.  Otherwise, convert it into a search.
2947         if (unformattedUrlString.startsWith("content://")) {  // This is a Content URL.
2948             // Load the entire content URL.
2949             url = unformattedUrlString;
2950         } else if (Patterns.WEB_URL.matcher(unformattedUrlString).matches() || unformattedUrlString.startsWith("http://") || unformattedUrlString.startsWith("https://") ||
2951                 unformattedUrlString.startsWith("file://")) {  // This is a standard URL.
2952             // Add `https://` at the beginning if there is no protocol.  Otherwise the app will segfault.
2953             if (!unformattedUrlString.startsWith("http") && !unformattedUrlString.startsWith("file://") && !unformattedUrlString.startsWith("content://")) {
2954                 unformattedUrlString = "https://" + unformattedUrlString;
2955             }
2956
2957             // Initialize `unformattedUrl`.
2958             URL unformattedUrl = null;
2959
2960             // 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.
2961             try {
2962                 unformattedUrl = new URL(unformattedUrlString);
2963             } catch (MalformedURLException e) {
2964                 e.printStackTrace();
2965             }
2966
2967             // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2968             String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2969             String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2970             String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2971             String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2972             String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2973
2974             // Build the URI.
2975             Uri.Builder uri = new Uri.Builder();
2976             uri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2977
2978             // Decode the URI as a UTF-8 string in.
2979             try {
2980                 url = URLDecoder.decode(uri.build().toString(), "UTF-8");
2981             } catch (UnsupportedEncodingException exception) {
2982                 // Do nothing.  The formatted URL string will remain blank.
2983             }
2984         } else if (!unformattedUrlString.isEmpty()){  // This is not a URL, but rather a search string.
2985             // Create an encoded URL String.
2986             String encodedUrlString;
2987
2988             // Sanitize the search input.
2989             try {
2990                 encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2991             } catch (UnsupportedEncodingException exception) {
2992                 encodedUrlString = "";
2993             }
2994
2995             // Add the base search URL.
2996             url = searchURL + encodedUrlString;
2997         }
2998
2999         // Clear the focus from the URL edit text.  Otherwise, proximate typing in the box will retain the colorized formatting instead of being reset during refocus.
3000         urlEditText.clearFocus();
3001
3002         // Make it so.
3003         loadUrl(url);
3004     }
3005
3006     private void loadUrl(String url) {
3007         // Sanitize the URL.
3008         url = sanitizeUrl(url);
3009
3010         // Apply the domain settings.
3011         applyDomainSettings(currentWebView, url, true, false);
3012
3013         // Load the URL.
3014         currentWebView.loadUrl(url, customHeaders);
3015     }
3016
3017     public void findPreviousOnPage(View view) {
3018         // Go to the previous highlighted phrase on the page.  `false` goes backwards instead of forwards.
3019         currentWebView.findNext(false);
3020     }
3021
3022     public void findNextOnPage(View view) {
3023         // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
3024         currentWebView.findNext(true);
3025     }
3026
3027     public void closeFindOnPage(View view) {
3028         // Get a handle for the views.
3029         Toolbar toolbar = findViewById(R.id.toolbar);
3030         LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
3031         EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
3032
3033         // Delete the contents of `find_on_page_edittext`.
3034         findOnPageEditText.setText(null);
3035
3036         // Clear the highlighted phrases if the WebView is not null.
3037         if (currentWebView != null) {
3038             currentWebView.clearMatches();
3039         }
3040
3041         // Hide the find on page linear layout.
3042         findOnPageLinearLayout.setVisibility(View.GONE);
3043
3044         // Show the toolbar.
3045         toolbar.setVisibility(View.VISIBLE);
3046
3047         // Get a handle for the input method manager.
3048         InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
3049
3050         // Remove the lint warning below that the input method manager might be null.
3051         assert inputMethodManager != null;
3052
3053         // Hide the keyboard.
3054         inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
3055     }
3056
3057     private void applyAppSettings() {
3058         // Get a handle for the shared preferences.
3059         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3060
3061         // Store the values from the shared preferences in variables.
3062         incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3063         boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
3064         sanitizeGoogleAnalytics = sharedPreferences.getBoolean("google_analytics", true);
3065         sanitizeFacebookClickIds = sharedPreferences.getBoolean("facebook_click_ids", true);
3066         sanitizeTwitterAmpRedirects = sharedPreferences.getBoolean("twitter_amp_redirects", true);
3067         proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
3068         fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3069         hideAppBar = sharedPreferences.getBoolean("hide_app_bar", true);
3070         scrollAppBar = sharedPreferences.getBoolean("scroll_app_bar", true);
3071
3072         // Get handles for the views that need to be modified.
3073         FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
3074         AppBarLayout appBarLayout = findViewById(R.id.appbar_layout);
3075         ActionBar actionBar = getSupportActionBar();
3076         Toolbar toolbar = findViewById(R.id.toolbar);
3077         LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
3078         LinearLayout tabsLinearLayout = findViewById(R.id.tabs_linearlayout);
3079         SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
3080
3081         // Remove the incorrect lint warning below that the action bar might be null.
3082         assert actionBar != null;
3083
3084         // Apply the proxy through Orbot settings.
3085         applyProxyThroughOrbot(false);
3086
3087         // Set Do Not Track status.
3088         if (doNotTrackEnabled) {
3089             customHeaders.put("DNT", "1");
3090         } else {
3091             customHeaders.remove("DNT");
3092         }
3093
3094         // Get the current layout parameters.  Using coordinator layout parameters allows the `setBehavior()` command and using app bar layout parameters allows the `setScrollFlags()` command.
3095         CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
3096         AppBarLayout.LayoutParams toolbarLayoutParams = (AppBarLayout.LayoutParams) toolbar.getLayoutParams();
3097         AppBarLayout.LayoutParams findOnPageLayoutParams = (AppBarLayout.LayoutParams) findOnPageLinearLayout.getLayoutParams();
3098         AppBarLayout.LayoutParams tabsLayoutParams = (AppBarLayout.LayoutParams) tabsLinearLayout.getLayoutParams();
3099
3100         // Add the scrolling behavior to the layout parameters.
3101         if (scrollAppBar) {
3102             // Enable scrolling of the app bar.
3103             swipeRefreshLayoutParams.setBehavior(new AppBarLayout.ScrollingViewBehavior());
3104             toolbarLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3105             findOnPageLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3106             tabsLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3107         } else {
3108             // Disable scrolling of the app bar.
3109             swipeRefreshLayoutParams.setBehavior(null);
3110             toolbarLayoutParams.setScrollFlags(0);
3111             findOnPageLayoutParams.setScrollFlags(0);
3112             tabsLayoutParams.setScrollFlags(0);
3113
3114             // Expand the app bar if it is currently collapsed.
3115             appBarLayout.setExpanded(true);
3116         }
3117
3118         // Apply the modified layout parameters.
3119         swipeRefreshLayout.setLayoutParams(swipeRefreshLayoutParams);
3120         toolbar.setLayoutParams(toolbarLayoutParams);
3121         findOnPageLinearLayout.setLayoutParams(findOnPageLayoutParams);
3122         tabsLinearLayout.setLayoutParams(tabsLayoutParams);
3123
3124         // Set the app bar scrolling for each WebView.
3125         for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3126             // Get the WebView tab fragment.
3127             WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3128
3129             // Get the fragment view.
3130             View fragmentView = webViewTabFragment.getView();
3131
3132             // Only modify the WebViews if they exist.
3133             if (fragmentView != null) {
3134                 // Get the nested scroll WebView from the tab fragment.
3135                 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3136
3137                 // Set the app bar scrolling.
3138                 nestedScrollWebView.setNestedScrollingEnabled(scrollAppBar);
3139             }
3140         }
3141
3142         // Update the full screen browsing mode settings.
3143         if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {  // Privacy Browser is currently in full screen browsing mode.
3144             // Update the visibility of the app bar, which might have changed in the settings.
3145             if (hideAppBar) {
3146                 // Hide the tab linear layout.
3147                 tabsLinearLayout.setVisibility(View.GONE);
3148
3149                 // Hide the action bar.
3150                 actionBar.hide();
3151             } else {
3152                 // Show the tab linear layout.
3153                 tabsLinearLayout.setVisibility(View.VISIBLE);
3154
3155                 // Show the action bar.
3156                 actionBar.show();
3157             }
3158
3159             // Hide the banner ad in the free flavor.
3160             if (BuildConfig.FLAVOR.contentEquals("free")) {
3161                 AdHelper.hideAd(findViewById(R.id.adview));
3162             }
3163
3164             // Remove the translucent status flag.  This is necessary so the root frame layout can fill the entire screen.
3165             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3166
3167             /* Hide the system bars.
3168              * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3169              * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
3170              * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3171              * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3172              */
3173             rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
3174                     View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3175         } else {  // Privacy Browser is not in full screen browsing mode.
3176             // Reset the full screen tracker, which could be true if Privacy Browser was in full screen mode before entering settings and full screen browsing was disabled.
3177             inFullScreenBrowsingMode = false;
3178
3179             // Show the tab linear layout.
3180             tabsLinearLayout.setVisibility(View.VISIBLE);
3181
3182             // Show the action bar.
3183             actionBar.show();
3184
3185             // Show the banner ad in the free flavor.
3186             if (BuildConfig.FLAVOR.contentEquals("free")) {
3187                 // Initialize the ads.  If this isn't the first run, `loadAd()` will be automatically called instead.
3188                 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getSupportFragmentManager(), getString(R.string.google_app_id), getString(R.string.ad_unit_id));
3189             }
3190
3191             // Remove the `SYSTEM_UI` flags from the root frame layout.
3192             rootFrameLayout.setSystemUiVisibility(0);
3193
3194             // Add the translucent status flag.
3195             getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3196         }
3197     }
3198
3199
3200     // `reloadWebsite` is used if returning from the Domains activity.  Otherwise JavaScript might not function correctly if it is newly enabled.
3201     @SuppressLint("SetJavaScriptEnabled")
3202     private boolean applyDomainSettings(NestedScrollWebView nestedScrollWebView, String url, boolean resetTab, boolean reloadWebsite) {
3203         // Store a copy of the current user agent to track changes for the return boolean.
3204         String initialUserAgent = nestedScrollWebView.getSettings().getUserAgentString();
3205
3206         // Parse the URL into a URI.
3207         Uri uri = Uri.parse(url);
3208
3209         // Extract the domain from `uri`.
3210         String newHostName = uri.getHost();
3211
3212         // Strings don't like to be null.
3213         if (newHostName == null) {
3214             newHostName = "";
3215         }
3216
3217         // Only apply the domain settings if a new domain is being loaded.  This allows the user to set temporary settings for JavaScript, cookies, DOM storage, etc.
3218         if (!nestedScrollWebView.getCurrentDomainName().equals(newHostName)) {
3219             // Set the new host name as the current domain name.
3220             nestedScrollWebView.setCurrentDomainName(newHostName);
3221
3222             // Reset the ignoring of pinned domain information.
3223             nestedScrollWebView.setIgnorePinnedDomainInformation(false);
3224
3225             // Clear any pinned SSL certificate or IP addresses.
3226             nestedScrollWebView.clearPinnedSslCertificate();
3227             nestedScrollWebView.clearPinnedIpAddresses();
3228
3229             // Reset the favorite icon if specified.
3230             if (resetTab) {
3231                 // Initialize the favorite icon.
3232                 nestedScrollWebView.initializeFavoriteIcon();
3233
3234                 // Get the current page position.
3235                 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
3236
3237                 // Get a handle for the tab layout.
3238                 TabLayout tabLayout = findViewById(R.id.tablayout);
3239
3240                 // Get the corresponding tab.
3241                 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
3242
3243                 // Update the tab if it isn't null, which sometimes happens when restarting from the background.
3244                 if (tab != null) {
3245                     // Get the tab custom view.
3246                     View tabCustomView = tab.getCustomView();
3247
3248                     // Remove the warning below that the tab custom view might be null.
3249                     assert tabCustomView != null;
3250
3251                     // Get the tab views.
3252                     ImageView tabFavoriteIconImageView = tabCustomView.findViewById(R.id.favorite_icon_imageview);
3253                     TextView tabTitleTextView = tabCustomView.findViewById(R.id.title_textview);
3254
3255                     // Set the default favorite icon as the favorite icon for this tab.
3256                     tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(nestedScrollWebView.getFavoriteOrDefaultIcon(), 64, 64, true));
3257
3258                     // Set the loading title text.
3259                     tabTitleTextView.setText(R.string.loading);
3260                 }
3261             }
3262
3263             // Initialize the database handler.  The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3264             DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3265
3266             // Get a full cursor from `domainsDatabaseHelper`.
3267             Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3268
3269             // Initialize `domainSettingsSet`.
3270             Set<String> domainSettingsSet = new HashSet<>();
3271
3272             // Get the domain name column index.
3273             int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3274
3275             // Populate `domainSettingsSet`.
3276             for (int i = 0; i < domainNameCursor.getCount(); i++) {
3277                 // Move `domainsCursor` to the current row.
3278                 domainNameCursor.moveToPosition(i);
3279
3280                 // Store the domain name in `domainSettingsSet`.
3281                 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3282             }
3283
3284             // Close `domainNameCursor.
3285             domainNameCursor.close();
3286
3287             // Initialize the domain name in database variable.
3288             String domainNameInDatabase = null;
3289
3290             // Check the hostname against the domain settings set.
3291             if (domainSettingsSet.contains(newHostName)) {  // The hostname is contained in the domain settings set.
3292                 // Record the domain name in the database.
3293                 domainNameInDatabase = newHostName;
3294
3295                 // Set the domain settings applied tracker to true.
3296                 nestedScrollWebView.setDomainSettingsApplied(true);
3297             } else {  // The hostname is not contained in the domain settings set.
3298                 // Set the domain settings applied tracker to false.
3299                 nestedScrollWebView.setDomainSettingsApplied(false);
3300             }
3301
3302             // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3303             while (!nestedScrollWebView.getDomainSettingsApplied() && newHostName.contains(".")) {  // Stop checking if domain settings are already applied or there are no more `.` in the host name.
3304                 if (domainSettingsSet.contains("*." + newHostName)) {  // Check the host name prepended by `*.`.
3305                     // Set the domain settings applied tracker to true.
3306                     nestedScrollWebView.setDomainSettingsApplied(true);
3307
3308                     // Store the applied domain names as it appears in the database.
3309                     domainNameInDatabase = "*." + newHostName;
3310                 }
3311
3312                 // Strip out the lowest subdomain of of the host name.
3313                 newHostName = newHostName.substring(newHostName.indexOf(".") + 1);
3314             }
3315
3316
3317             // Get a handle for the shared preferences.
3318             SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3319
3320             // Store the general preference information.
3321             String defaultFontSizeString = sharedPreferences.getString("font_size", getString(R.string.font_size_default_value));
3322             String defaultUserAgentName = sharedPreferences.getString("user_agent", getString(R.string.user_agent_default_value));
3323             boolean defaultSwipeToRefresh = sharedPreferences.getBoolean("swipe_to_refresh", true);
3324             boolean displayWebpageImages = sharedPreferences.getBoolean("display_webpage_images", true);
3325             boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
3326
3327             // Get a handle for the cookie manager.
3328             CookieManager cookieManager = CookieManager.getInstance();
3329
3330             // Get handles for the views.
3331             RelativeLayout urlRelativeLayout = findViewById(R.id.url_relativelayout);
3332             SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
3333
3334             // Initialize the user agent array adapter and string array.
3335             ArrayAdapter<CharSequence> userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item);
3336             String[] userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
3337
3338             if (nestedScrollWebView.getDomainSettingsApplied()) {  // The url has custom domain settings.
3339                 // Get a cursor for the current host and move it to the first position.
3340                 Cursor currentDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3341                 currentDomainSettingsCursor.moveToFirst();
3342
3343                 // Get the settings from the cursor.
3344                 nestedScrollWebView.setDomainSettingsDatabaseId(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3345                 nestedScrollWebView.setDomainSettingsJavaScriptEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3346                 nestedScrollWebView.setAcceptFirstPartyCookies(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3347                 boolean domainThirdPartyCookiesEnabled = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3348                 nestedScrollWebView.getSettings().setDomStorageEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3349                 // Form data can be removed once the minimum API >= 26.
3350                 boolean saveFormData = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3351                 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASY_LIST,
3352                         currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3353                 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASY_PRIVACY,
3354                         currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3355                 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST,
3356                         currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3357                 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST,
3358                         currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3359                 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRA_PRIVACY,
3360                         currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_ULTRAPRIVACY)) == 1);
3361                 nestedScrollWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS,
3362                         currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
3363                 String userAgentName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3364                 int fontSize = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3365                 int swipeToRefreshInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
3366                 int nightModeInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
3367                 int displayWebpageImagesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3368                 boolean pinnedSslCertificate = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3369                 String pinnedSslIssuedToCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3370                 String pinnedSslIssuedToOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3371                 String pinnedSslIssuedToUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3372                 String pinnedSslIssuedByCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3373                 String pinnedSslIssuedByOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3374                 String pinnedSslIssuedByUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3375                 boolean pinnedIpAddresses = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_IP_ADDRESSES)) == 1);
3376                 String pinnedHostIpAddresses = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.IP_ADDRESSES));
3377
3378                 // Create the pinned SSL date variables.
3379                 Date pinnedSslStartDate;
3380                 Date pinnedSslEndDate;
3381
3382                 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0 because creating a new Date results in an error if the input is 0.
3383                 if (currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
3384                     pinnedSslStartDate = null;
3385                 } else {
3386                     pinnedSslStartDate = new Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
3387                 }
3388
3389                 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0 because creating a new Date results in an error if the input is 0.
3390                 if (currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
3391                     pinnedSslEndDate = null;
3392                 } else {
3393                     pinnedSslEndDate = new Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
3394                 }
3395
3396                 // If there is a pinned SSL certificate, store it in the WebView.
3397                 if (pinnedSslCertificate) {
3398                     nestedScrollWebView.setPinnedSslCertificate(pinnedSslIssuedToCName, pinnedSslIssuedToOName, pinnedSslIssuedToUName, pinnedSslIssuedByCName, pinnedSslIssuedByOName, pinnedSslIssuedByUName,
3399                             pinnedSslStartDate, pinnedSslEndDate);
3400                 }
3401
3402                 // If there is a pinned IP address, store it in the WebView.
3403                 if (pinnedIpAddresses) {
3404                     nestedScrollWebView.setPinnedIpAddresses(pinnedHostIpAddresses);
3405                 }
3406
3407                 // Set night mode according to the night mode int.
3408                 switch (nightModeInt) {
3409                     case DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT:
3410                         // Set night mode according to the current default.
3411                         nestedScrollWebView.setNightMode(sharedPreferences.getBoolean("night_mode", false));
3412                         break;
3413
3414                     case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
3415                         // Enable night mode.
3416                         nestedScrollWebView.setNightMode(true);
3417                         break;
3418
3419                     case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
3420                         // Disable night mode.
3421                         nestedScrollWebView.setNightMode(false);
3422                         break;
3423                 }
3424
3425                 // Enable JavaScript if night mode is enabled.
3426                 if (nestedScrollWebView.getNightMode()) {
3427                     // Enable JavaScript.
3428                     nestedScrollWebView.getSettings().setJavaScriptEnabled(true);
3429                 } else {
3430                     // Set JavaScript according to the domain settings.
3431                     nestedScrollWebView.getSettings().setJavaScriptEnabled(nestedScrollWebView.getDomainSettingsJavaScriptEnabled());
3432                 }
3433
3434                 // Close the current host domain settings cursor.
3435                 currentDomainSettingsCursor.close();
3436
3437                 // Apply the domain settings.
3438                 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptFirstPartyCookies());
3439
3440                 // Set third-party cookies status if API >= 21.
3441                 if (Build.VERSION.SDK_INT >= 21) {
3442                     cookieManager.setAcceptThirdPartyCookies(nestedScrollWebView, domainThirdPartyCookiesEnabled);
3443                 }
3444
3445                 // Apply the form data setting if the API < 26.
3446                 if (Build.VERSION.SDK_INT < 26) {
3447                     nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
3448                 }
3449
3450                 // Apply the font size.
3451                 if (fontSize == 0) {  // Apply the default font size.
3452                     nestedScrollWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3453                 } else {  // Apply the specified font size.
3454                     nestedScrollWebView.getSettings().setTextZoom(fontSize);
3455                 }
3456
3457                 // Set the user agent.
3458                 if (userAgentName.equals(getString(R.string.system_default_user_agent))) {  // Use the system default user agent.
3459                     // Get the array position of the default user agent name.
3460                     int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3461
3462                     // Set the user agent according to the system default.
3463                     switch (defaultUserAgentArrayPosition) {
3464                         case UNRECOGNIZED_USER_AGENT:  // The default user agent name is not on the canonical list.
3465                             // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3466                             nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
3467                             break;
3468
3469                         case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3470                             // Set the user agent to `""`, which uses the default value.
3471                             nestedScrollWebView.getSettings().setUserAgentString("");
3472                             break;
3473
3474                         case SETTINGS_CUSTOM_USER_AGENT:
3475                             // Set the default custom user agent.
3476                             nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
3477                             break;
3478
3479                         default:
3480                             // Get the user agent string from the user agent data array
3481                             nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
3482                     }
3483                 } else {  // Set the user agent according to the stored name.
3484                     // Get the array position of the user agent name.
3485                     int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
3486
3487                     switch (userAgentArrayPosition) {
3488                         case UNRECOGNIZED_USER_AGENT:  // The user agent name contains a custom user agent.
3489                             nestedScrollWebView.getSettings().setUserAgentString(userAgentName);
3490                             break;
3491
3492                         case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3493                             // Set the user agent to `""`, which uses the default value.
3494                             nestedScrollWebView.getSettings().setUserAgentString("");
3495                             break;
3496
3497                         default:
3498                             // Get the user agent string from the user agent data array.
3499                             nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3500                     }
3501                 }
3502
3503                 // Set swipe to refresh.
3504                 switch (swipeToRefreshInt) {
3505                     case DomainsDatabaseHelper.SWIPE_TO_REFRESH_SYSTEM_DEFAULT:
3506                         // Store the swipe to refresh status in the nested scroll WebView.
3507                         nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
3508
3509                         // Apply swipe to refresh according to the default.  This can be removed once the minimum API >= 23 because it is continuously set by an on scroll change listener.
3510                         swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
3511                         break;
3512
3513                     case DomainsDatabaseHelper.SWIPE_TO_REFRESH_ENABLED:
3514                         // Store the swipe to refresh status in the nested scroll WebView.
3515                         nestedScrollWebView.setSwipeToRefresh(true);
3516
3517                         // Enable swipe to refresh.  This can be removed once the minimum API >= 23 because it is continuously set by an on scroll change listener.
3518                         swipeRefreshLayout.setEnabled(true);
3519                         break;
3520
3521                     case DomainsDatabaseHelper.SWIPE_TO_REFRESH_DISABLED:
3522                         // Store the swipe to refresh status in the nested scroll WebView.
3523                         nestedScrollWebView.setSwipeToRefresh(false);
3524
3525                         // Disable swipe to refresh.  This can be removed once the minimum API >= 23 because it is continuously set by an on scroll change listener.
3526                         swipeRefreshLayout.setEnabled(false);
3527                 }
3528
3529                 // Set the loading of webpage images.
3530                 switch (displayWebpageImagesInt) {
3531                     case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
3532                         nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
3533                         break;
3534
3535                     case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
3536                         nestedScrollWebView.getSettings().setLoadsImagesAutomatically(true);
3537                         break;
3538
3539                     case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
3540                         nestedScrollWebView.getSettings().setLoadsImagesAutomatically(false);
3541                         break;
3542                 }
3543
3544                 // Set a green background on the URL relative layout to indicate that custom domain settings are being used. The deprecated `.getDrawable()` must be used until the minimum API >= 21.
3545                 if (darkTheme) {
3546                     urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
3547                 } else {
3548                     urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
3549                 }
3550             } else {  // The new URL does not have custom domain settings.  Load the defaults.
3551                 // Store the values from the shared preferences.
3552                 boolean defaultJavaScriptEnabled = sharedPreferences.getBoolean("javascript", false);
3553                 nestedScrollWebView.setAcceptFirstPartyCookies(sharedPreferences.getBoolean("first_party_cookies", false));
3554                 boolean defaultThirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies", false);
3555                 nestedScrollWebView.getSettings().setDomStorageEnabled(sharedPreferences.getBoolean("dom_storage", false));
3556                 boolean saveFormData = sharedPreferences.getBoolean("save_form_data", false);  // Form data can be removed once the minimum API >= 26.
3557                 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASY_LIST, sharedPreferences.getBoolean("easylist", true));
3558                 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASY_PRIVACY, sharedPreferences.getBoolean("easyprivacy", true));
3559                 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, sharedPreferences.getBoolean("fanboys_annoyance_list", true));
3560                 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, sharedPreferences.getBoolean("fanboys_social_blocking_list", true));
3561                 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRA_PRIVACY, sharedPreferences.getBoolean("ultraprivacy", true));
3562                 nestedScrollWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, sharedPreferences.getBoolean("block_all_third_party_requests", false));
3563                 nestedScrollWebView.setNightMode(sharedPreferences.getBoolean("night_mode", false));
3564
3565                 // Enable JavaScript if night mode is enabled.
3566                 if (nestedScrollWebView.getNightMode()) {
3567                     // Enable JavaScript.
3568                     nestedScrollWebView.getSettings().setJavaScriptEnabled(true);
3569                 } else {
3570                     // Set JavaScript according to the domain settings.
3571                     nestedScrollWebView.getSettings().setJavaScriptEnabled(defaultJavaScriptEnabled);
3572                 }
3573
3574                 // Apply the default settings.
3575                 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptFirstPartyCookies());
3576                 nestedScrollWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3577
3578                 // Apply the form data setting if the API < 26.
3579                 if (Build.VERSION.SDK_INT < 26) {
3580                     nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
3581                 }
3582
3583                 // Store the swipe to refresh status in the nested scroll WebView.
3584                 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
3585
3586                 // Apply swipe to refresh according to the default.
3587                 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
3588
3589                 // Reset the pinned variables.
3590                 nestedScrollWebView.setDomainSettingsDatabaseId(-1);
3591
3592                 // Set third-party cookies status if API >= 21.
3593                 if (Build.VERSION.SDK_INT >= 21) {
3594                     cookieManager.setAcceptThirdPartyCookies(nestedScrollWebView, defaultThirdPartyCookiesEnabled);
3595                 }
3596
3597                 // Get the array position of the user agent name.
3598                 int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3599
3600                 // Set the user agent.
3601                 switch (userAgentArrayPosition) {
3602                     case UNRECOGNIZED_USER_AGENT:  // The default user agent name is not on the canonical list.
3603                         // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3604                         nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
3605                         break;
3606
3607                     case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3608                         // Set the user agent to `""`, which uses the default value.
3609                         nestedScrollWebView.getSettings().setUserAgentString("");
3610                         break;
3611
3612                     case SETTINGS_CUSTOM_USER_AGENT:
3613                         // Set the default custom user agent.
3614                         nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
3615                         break;
3616
3617                     default:
3618                         // Get the user agent string from the user agent data array
3619                         nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3620                 }
3621
3622                 // Set the loading of webpage images.
3623                 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
3624
3625                 // Set a transparent background on URL edit text.  The deprecated `getResources().getDrawable()` must be used until the minimum API >= 21.
3626                 urlRelativeLayout.setBackground(getResources().getDrawable(R.color.transparent));
3627             }
3628
3629             // Close the domains database helper.
3630             domainsDatabaseHelper.close();
3631
3632             // Update the privacy icons.
3633             updatePrivacyIcons(true);
3634         }
3635
3636         // Reload the website if returning from the Domains activity.
3637         if (reloadWebsite) {
3638             nestedScrollWebView.reload();
3639         }
3640
3641         // Return the user agent changed status.
3642         return !nestedScrollWebView.getSettings().getUserAgentString().equals(initialUserAgent);
3643     }
3644
3645     private void applyProxyThroughOrbot(boolean reloadWebsite) {
3646         // Get a handle for the shared preferences.
3647         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3648
3649         // Get the search and theme preferences.
3650         String torSearchString = sharedPreferences.getString("tor_search", getString(R.string.tor_search_default_value));
3651         String torSearchCustomUrlString = sharedPreferences.getString("tor_search_custom_url", getString(R.string.tor_search_custom_url_default_value));
3652         String searchString = sharedPreferences.getString("search", getString(R.string.search_default_value));
3653         String searchCustomUrlString = sharedPreferences.getString("search_custom_url", getString(R.string.search_custom_url_default_value));
3654         boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
3655
3656         // Get a handle for the app bar layout.
3657         AppBarLayout appBarLayout = findViewById(R.id.appbar_layout);
3658
3659         // Set the homepage, search, and proxy options.
3660         if (proxyThroughOrbot) {  // Set the Tor options.
3661             // Set the search URL.
3662             if (torSearchString.equals("Custom URL")) {  // Get the custom URL string.
3663                 searchURL = torSearchCustomUrlString;
3664             } else {  // Use the string from the pre-built list.
3665                 searchURL = torSearchString;
3666             }
3667
3668             // Set the proxy.  `this` refers to the current activity where an `AlertDialog` might be displayed.
3669             OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
3670
3671             // Set the app bar background to indicate proxying through Orbot is enabled.
3672             if (darkTheme) {
3673                 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
3674             } else {
3675                 appBarLayout.setBackgroundResource(R.color.blue_50);
3676             }
3677
3678             // Check to see if Orbot is ready.
3679             if (!orbotStatus.equals("ON")) {  // Orbot is not ready.
3680                 // Set `waitingForOrbot`.
3681                 waitingForOrbot = true;
3682
3683                 // Disable the wide view port so that the waiting for Orbot text is displayed correctly.
3684                 currentWebView.getSettings().setUseWideViewPort(false);
3685
3686                 // Load a waiting page.  `null` specifies no encoding, which defaults to ASCII.
3687                 currentWebView.loadData("<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>", "text/html", null);
3688             } else if (reloadWebsite) {  // Orbot is ready and the website should be reloaded.
3689                 // Reload the website.
3690                 currentWebView.reload();
3691             }
3692         } else {  // Set the non-Tor options.
3693             // Set the search URL.
3694             if (searchString.equals("Custom URL")) {  // Get the custom URL string.
3695                 searchURL = searchCustomUrlString;
3696             } else {  // Use the string from the pre-built list.
3697                 searchURL = searchString;
3698             }
3699
3700             // Reset the proxy to default.  The host is `""` and the port is `"0"`.
3701             OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
3702
3703             // Set the default app bar layout background.
3704             if (darkTheme) {
3705                 appBarLayout.setBackgroundResource(R.color.gray_900);
3706             } else {
3707                 appBarLayout.setBackgroundResource(R.color.gray_100);
3708             }
3709
3710             // Reset `waitingForOrbot.
3711             waitingForOrbot = false;
3712
3713             // Reload the WebViews if requested.
3714             if (reloadWebsite) {
3715                 // Reload the WebViews.
3716                 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3717                     // Get the WebView tab fragment.
3718                     WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3719
3720                     // Get the fragment view.
3721                     View fragmentView = webViewTabFragment.getView();
3722
3723                     // Only reload the WebViews if they exist.
3724                     if (fragmentView != null) {
3725                         // Get the nested scroll WebView from the tab fragment.
3726                         NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3727
3728                         // Reload the WebView.
3729                         nestedScrollWebView.reload();
3730                     }
3731                 }
3732             }
3733         }
3734     }
3735
3736     private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
3737         // Only update the privacy icons if the options menu and the current WebView have already been populated.
3738         if ((optionsMenu != null) && (currentWebView != null)) {
3739             // Get a handle for the shared preferences.
3740             SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3741
3742             // Get the theme and screenshot preferences.
3743             boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
3744
3745             // Get handles for the menu items.
3746             MenuItem privacyMenuItem = optionsMenu.findItem(R.id.toggle_javascript);
3747             MenuItem firstPartyCookiesMenuItem = optionsMenu.findItem(R.id.toggle_first_party_cookies);
3748             MenuItem domStorageMenuItem = optionsMenu.findItem(R.id.toggle_dom_storage);
3749             MenuItem refreshMenuItem = optionsMenu.findItem(R.id.refresh);
3750
3751             // Update the privacy icon.
3752             if (currentWebView.getSettings().getJavaScriptEnabled()) {  // JavaScript is enabled.
3753                 privacyMenuItem.setIcon(R.drawable.javascript_enabled);
3754             } else if (currentWebView.getAcceptFirstPartyCookies()) {  // JavaScript is disabled but cookies are enabled.
3755                 privacyMenuItem.setIcon(R.drawable.warning);
3756             } else {  // All the dangerous features are disabled.
3757                 privacyMenuItem.setIcon(R.drawable.privacy_mode);
3758             }
3759
3760             // Update the first-party cookies icon.
3761             if (currentWebView.getAcceptFirstPartyCookies()) {  // First-party cookies are enabled.
3762                 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
3763             } else {  // First-party cookies are disabled.
3764                 if (darkTheme) {
3765                     firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_dark);
3766                 } else {
3767                     firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_light);
3768                 }
3769             }
3770
3771             // Update the DOM storage icon.
3772             if (currentWebView.getSettings().getJavaScriptEnabled() && currentWebView.getSettings().getDomStorageEnabled()) {  // Both JavaScript and DOM storage are enabled.
3773                 domStorageMenuItem.setIcon(R.drawable.dom_storage_enabled);
3774             } else if (currentWebView.getSettings().getJavaScriptEnabled()) {  // JavaScript is enabled but DOM storage is disabled.
3775                 if (darkTheme) {
3776                     domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
3777                 } else {
3778                     domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
3779                 }
3780             } else {  // JavaScript is disabled, so DOM storage is ghosted.
3781                 if (darkTheme) {
3782                     domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
3783                 } else {
3784                     domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
3785                 }
3786             }
3787
3788             // Update the refresh icon.
3789             if (darkTheme) {
3790                 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
3791             } else {
3792                 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
3793             }
3794
3795             // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
3796             if (runInvalidateOptionsMenu) {
3797                 invalidateOptionsMenu();
3798             }
3799         }
3800     }
3801
3802     private void openUrlWithExternalApp(String url) {
3803         // Create a download intent.  Not specifying the action type will display the maximum number of options.
3804         Intent downloadIntent = new Intent();
3805
3806         // Set the URI and the MIME type.  Specifying `text/html` displays a good number of options.
3807         downloadIntent.setDataAndType(Uri.parse(url), "text/html");
3808
3809         // Flag the intent to open in a new task.
3810         downloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3811
3812         // Show the chooser.
3813         startActivity(Intent.createChooser(downloadIntent, getString(R.string.open_with)));
3814     }
3815
3816     private void highlightUrlText() {
3817         // Get a handle for the URL edit text.
3818         EditText urlEditText = findViewById(R.id.url_edittext);
3819
3820         // Only highlight the URL text if the box is not currently selected.
3821         if (!urlEditText.hasFocus()) {
3822             // Get the URL string.
3823             String urlString = urlEditText.getText().toString();
3824
3825             // Highlight the URL according to the protocol.
3826             if (urlString.startsWith("file://")) {  // This is a file URL.
3827                 // De-emphasize only the protocol.
3828                 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3829             } else if (urlString.startsWith("content://")) {
3830                 // De-emphasize only the protocol.
3831                 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 10, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3832             } else {  // This is a web URL.
3833                 // Get the index of the `/` immediately after the domain name.
3834                 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
3835
3836                 // Create a base URL string.
3837                 String baseUrl;
3838
3839                 // Get the base URL.
3840                 if (endOfDomainName > 0) {  // There is at least one character after the base URL.
3841                     // Get the base URL.
3842                     baseUrl = urlString.substring(0, endOfDomainName);
3843                 } else {  // There are no characters after the base URL.
3844                     // Set the base URL to be the entire URL string.
3845                     baseUrl = urlString;
3846                 }
3847
3848                 // Get the index of the last `.` in the domain.
3849                 int lastDotIndex = baseUrl.lastIndexOf(".");
3850
3851                 // Get the index of the penultimate `.` in the domain.
3852                 int penultimateDotIndex = baseUrl.lastIndexOf(".", lastDotIndex - 1);
3853
3854                 // Markup the beginning of the URL.
3855                 if (urlString.startsWith("http://")) {  // Highlight the protocol of connections that are not encrypted.
3856                     urlEditText.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3857
3858                     // De-emphasize subdomains.
3859                     if (penultimateDotIndex > 0) {  // There is more than one subdomain in the domain name.
3860                         urlEditText.getText().setSpan(initialGrayColorSpan, 7, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3861                     }
3862                 } else if (urlString.startsWith("https://")) {  // De-emphasize the protocol of connections that are encrypted.
3863                     if (penultimateDotIndex > 0) {  // There is more than one subdomain in the domain name.
3864                         // De-emphasize the protocol and the additional subdomains.
3865                         urlEditText.getText().setSpan(initialGrayColorSpan, 0, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3866                     } else {  // There is only one subdomain in the domain name.
3867                         // De-emphasize only the protocol.
3868                         urlEditText.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3869                     }
3870                 }
3871
3872                 // De-emphasize the text after the domain name.
3873                 if (endOfDomainName > 0) {
3874                     urlEditText.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3875                 }
3876             }
3877         }
3878     }
3879
3880     private void loadBookmarksFolder() {
3881         // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
3882         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
3883
3884         // Populate the bookmarks cursor adapter.  `this` specifies the `Context`.  `false` disables `autoRequery`.
3885         bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
3886             @Override
3887             public View newView(Context context, Cursor cursor, ViewGroup parent) {
3888                 // Inflate the individual item layout.  `false` does not attach it to the root.
3889                 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
3890             }
3891
3892             @Override
3893             public void bindView(View view, Context context, Cursor cursor) {
3894                 // Get handles for the views.
3895                 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
3896                 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
3897
3898                 // Get the favorite icon byte array from the cursor.
3899                 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
3900
3901                 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
3902                 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
3903
3904                 // Display the bitmap in `bookmarkFavoriteIcon`.
3905                 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
3906
3907                 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
3908                 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
3909                 bookmarkNameTextView.setText(bookmarkNameString);
3910
3911                 // Make the font bold for folders.
3912                 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
3913                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
3914                 } else {  // Reset the font to default for normal bookmarks.
3915                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
3916                 }
3917             }
3918         };
3919
3920         // Get a handle for the bookmarks list view.
3921         ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
3922
3923         // Populate the list view with the adapter.
3924         bookmarksListView.setAdapter(bookmarksCursorAdapter);
3925
3926         // Get a handle for the bookmarks title text view.
3927         TextView bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
3928
3929         // Set the bookmarks drawer title.
3930         if (currentBookmarksFolder.isEmpty()) {
3931             bookmarksTitleTextView.setText(R.string.bookmarks);
3932         } else {
3933             bookmarksTitleTextView.setText(currentBookmarksFolder);
3934         }
3935     }
3936
3937     private void openWithApp(String url) {
3938         // Create the open with intent with `ACTION_VIEW`.
3939         Intent openWithAppIntent = new Intent(Intent.ACTION_VIEW);
3940
3941         // Set the URI but not the MIME type.  This should open all available apps.
3942         openWithAppIntent.setData(Uri.parse(url));
3943
3944         // Flag the intent to open in a new task.
3945         openWithAppIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3946
3947         // Show the chooser.
3948         startActivity(openWithAppIntent);
3949     }
3950
3951     private void openWithBrowser(String url) {
3952         // Create the open with intent with `ACTION_VIEW`.
3953         Intent openWithBrowserIntent = new Intent(Intent.ACTION_VIEW);
3954
3955         // Set the URI and the MIME type.  `"text/html"` should load browser options.
3956         openWithBrowserIntent.setDataAndType(Uri.parse(url), "text/html");
3957
3958         // Flag the intent to open in a new task.
3959         openWithBrowserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3960
3961         // Show the chooser.
3962         startActivity(openWithBrowserIntent);
3963     }
3964
3965     private String sanitizeUrl(String url) {
3966         // Sanitize Google Analytics.
3967         if (sanitizeGoogleAnalytics) {
3968             // Remove `?utm_`.
3969             if (url.contains("?utm_")) {
3970                 url = url.substring(0, url.indexOf("?utm_"));
3971             }
3972
3973             // Remove `&utm_`.
3974             if (url.contains("&utm_")) {
3975                 url = url.substring(0, url.indexOf("&utm_"));
3976             }
3977         }
3978
3979         // Sanitize Facebook Click IDs.
3980         if (sanitizeFacebookClickIds) {
3981             // Remove `?fbclid=`.
3982             if (url.contains("?fbclid=")) {
3983                 url = url.substring(0, url.indexOf("?fbclid="));
3984             }
3985
3986             // Remove `&fbclid=`.
3987             if (url.contains("&fbclid=")) {
3988                 url = url.substring(0, url.indexOf("&fbclid="));
3989             }
3990         }
3991
3992         // Sanitize Twitter AMP redirects.
3993         if (sanitizeTwitterAmpRedirects) {
3994             // Remove `?amp=1`.
3995             if (url.contains("?amp=1")) {
3996                 url = url.substring(0, url.indexOf("?amp=1"));
3997             }
3998         }
3999
4000         // Return the sanitized URL.
4001         return url;
4002     }
4003
4004     public void addTab(View view) {
4005         // Add a new tab with a blank URL.
4006         addNewTab("");
4007     }
4008
4009     private void addNewTab(String url) {
4010         // Sanitize the URL.
4011         url = sanitizeUrl(url);
4012
4013         // Get a handle for the tab layout and the view pager.
4014         TabLayout tabLayout = findViewById(R.id.tablayout);
4015         ViewPager webViewPager = findViewById(R.id.webviewpager);
4016
4017         // Get the new page number.  The page numbers are 0 indexed, so the new page number will match the current count.
4018         int newTabNumber = tabLayout.getTabCount();
4019
4020         // Add a new tab.
4021         tabLayout.addTab(tabLayout.newTab());
4022
4023         // Get the new tab.
4024         TabLayout.Tab newTab = tabLayout.getTabAt(newTabNumber);
4025
4026         // Remove the lint warning below that the current tab might be null.
4027         assert newTab != null;
4028
4029         // Set a custom view on the new tab.
4030         newTab.setCustomView(R.layout.tab_custom_view);
4031
4032         // Add the new WebView page.
4033         webViewPagerAdapter.addPage(newTabNumber, webViewPager, url);
4034     }
4035
4036     public void closeTab(View view) {
4037         // Get a handle for the tab layout.
4038         TabLayout tabLayout = findViewById(R.id.tablayout);
4039
4040         // Run the command according to the number of tabs.
4041         if (tabLayout.getTabCount() > 1) {  // There is more than one tab open.
4042             // Close the current tab.
4043             closeCurrentTab();
4044         } else {  // There is only one tab open.
4045             clearAndExit();
4046         }
4047     }
4048
4049     private void closeCurrentTab() {
4050         // Get handles for the views.
4051         AppBarLayout appBarLayout = findViewById(R.id.appbar_layout);
4052         TabLayout tabLayout = findViewById(R.id.tablayout);
4053         ViewPager webViewPager = findViewById(R.id.webviewpager);
4054
4055         // Get the current tab number.
4056         int currentTabNumber = tabLayout.getSelectedTabPosition();
4057
4058         // Delete the current tab.
4059         tabLayout.removeTabAt(currentTabNumber);
4060
4061         // Delete the current page.  If the selected page number did not change during the delete, it will return true, meaning that the current WebView must be reset.
4062         if (webViewPagerAdapter.deletePage(currentTabNumber, webViewPager)) {
4063             setCurrentWebView(currentTabNumber);
4064         }
4065
4066         // Expand the app bar if it is currently collapsed.
4067         appBarLayout.setExpanded(true);
4068     }
4069
4070     private void clearAndExit() {
4071         // Get a handle for the shared preferences.
4072         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4073
4074         // Close the bookmarks cursor and database.
4075         bookmarksCursor.close();
4076         bookmarksDatabaseHelper.close();
4077
4078         // Get the status of the clear everything preference.
4079         boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
4080
4081         // Get a handle for the runtime.
4082         Runtime runtime = Runtime.getRuntime();
4083
4084         // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
4085         // which links to `/data/data/com.stoutner.privacybrowser.standard`.
4086         String privateDataDirectoryString = getApplicationInfo().dataDir;
4087
4088         // Clear cookies.
4089         if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
4090             // The command to remove cookies changed slightly in API 21.
4091             if (Build.VERSION.SDK_INT >= 21) {
4092                 CookieManager.getInstance().removeAllCookies(null);
4093             } else {
4094                 CookieManager.getInstance().removeAllCookie();
4095             }
4096
4097             // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4098             try {
4099                 // Two commands must be used because `Runtime.exec()` does not like `*`.
4100                 Process deleteCookiesProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
4101                 Process deleteCookiesJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
4102
4103                 // Wait until the processes have finished.
4104                 deleteCookiesProcess.waitFor();
4105                 deleteCookiesJournalProcess.waitFor();
4106             } catch (Exception exception) {
4107                 // Do nothing if an error is thrown.
4108             }
4109         }
4110
4111         // Clear DOM storage.
4112         if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
4113             // Ask `WebStorage` to clear the DOM storage.
4114             WebStorage webStorage = WebStorage.getInstance();
4115             webStorage.deleteAllData();
4116
4117             // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4118             try {
4119                 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4120                 Process deleteLocalStorageProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
4121
4122                 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
4123                 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
4124                 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
4125                 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
4126                 Process deleteDatabaseProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
4127
4128                 // Wait until the processes have finished.
4129                 deleteLocalStorageProcess.waitFor();
4130                 deleteIndexProcess.waitFor();
4131                 deleteQuotaManagerProcess.waitFor();
4132                 deleteQuotaManagerJournalProcess.waitFor();
4133                 deleteDatabaseProcess.waitFor();
4134             } catch (Exception exception) {
4135                 // Do nothing if an error is thrown.
4136             }
4137         }
4138
4139         // Clear form data if the API < 26.
4140         if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
4141             WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
4142             webViewDatabase.clearFormData();
4143
4144             // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4145             try {
4146                 // A string array must be used because the database contains a space and `Runtime.exec` will not otherwise escape the string correctly.
4147                 Process deleteWebDataProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
4148                 Process deleteWebDataJournalProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
4149
4150                 // Wait until the processes have finished.
4151                 deleteWebDataProcess.waitFor();
4152                 deleteWebDataJournalProcess.waitFor();
4153             } catch (Exception exception) {
4154                 // Do nothing if an error is thrown.
4155             }
4156         }
4157
4158         // Clear the cache.
4159         if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
4160             // Clear the cache from each WebView.
4161             for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4162                 // Get the WebView tab fragment.
4163                 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4164
4165                 // Get the fragment view.
4166                 View fragmentView = webViewTabFragment.getView();
4167
4168                 // Only clear the cache if the WebView exists.
4169                 if (fragmentView != null) {
4170                     // Get the nested scroll WebView from the tab fragment.
4171                     NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4172
4173                     // Clear the cache for this WebView.
4174                     nestedScrollWebView.clearCache(true);
4175                 }
4176             }
4177
4178             // Manually delete the cache directories.
4179             try {
4180                 // Delete the main cache directory.
4181                 Process deleteCacheProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/cache");
4182
4183                 // Delete the secondary `Service Worker` cache directory.
4184                 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4185                 Process deleteServiceWorkerProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
4186
4187                 // Wait until the processes have finished.
4188                 deleteCacheProcess.waitFor();
4189                 deleteServiceWorkerProcess.waitFor();
4190             } catch (Exception exception) {
4191                 // Do nothing if an error is thrown.
4192             }
4193         }
4194
4195         // Wipe out each WebView.
4196         for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4197             // Get the WebView tab fragment.
4198             WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4199
4200             // Get the fragment view.
4201             View fragmentView = webViewTabFragment.getView();
4202
4203             // Only wipe out the WebView if it exists.
4204             if (fragmentView != null) {
4205                 // Get the nested scroll WebView from the tab fragment.
4206                 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4207
4208                 // Clear SSL certificate preferences for this WebView.
4209                 nestedScrollWebView.clearSslPreferences();
4210
4211                 // Clear the back/forward history for this WebView.
4212                 nestedScrollWebView.clearHistory();
4213
4214                 // Destroy the internal state of `mainWebView`.
4215                 nestedScrollWebView.destroy();
4216             }
4217         }
4218
4219         // Clear the custom headers.
4220         customHeaders.clear();
4221
4222         // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
4223         // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
4224         if (clearEverything) {
4225             try {
4226                 // Delete the folder.
4227                 Process deleteAppWebviewProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
4228
4229                 // Wait until the process has finished.
4230                 deleteAppWebviewProcess.waitFor();
4231             } catch (Exception exception) {
4232                 // Do nothing if an error is thrown.
4233             }
4234         }
4235
4236         // Close Privacy Browser.  `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
4237         if (Build.VERSION.SDK_INT >= 21) {
4238             finishAndRemoveTask();
4239         } else {
4240             finish();
4241         }
4242
4243         // Remove the terminated program from RAM.  The status code is `0`.
4244         System.exit(0);
4245     }
4246
4247     private void setCurrentWebView(int pageNumber) {
4248         // Get a handle for the shared preferences.
4249         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4250
4251         // Get the theme preference.
4252         boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
4253
4254         // Get handles for the URL views.
4255         RelativeLayout urlRelativeLayout = findViewById(R.id.url_relativelayout);
4256         EditText urlEditText = findViewById(R.id.url_edittext);
4257         SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
4258
4259         //Stop the swipe to refresh indicator if it is running
4260         swipeRefreshLayout.setRefreshing(false);
4261
4262         // Get the WebView tab fragment.
4263         WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(pageNumber);
4264
4265         // Get the fragment view.
4266         View fragmentView = webViewTabFragment.getView();
4267
4268         // Set the current WebView if the fragment view is not null.
4269         if (fragmentView != null) {
4270             // Store the current WebView.
4271             currentWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4272
4273             // Update the status of swipe to refresh.
4274             if (currentWebView.getSwipeToRefresh()) {  // Swipe to refresh is enabled.
4275                 if (Build.VERSION.SDK_INT >= 23) {  // For API >= 23, swipe refresh layout is continuously updated with an on scroll change listener and only enabled if the WebView is scrolled to the top.
4276                     // Enable the swipe refresh layout if the WebView is scrolled all the way to the top.
4277                     swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
4278                 } else {
4279                     // Enable the swipe refresh layout.
4280                     swipeRefreshLayout.setEnabled(true);
4281                 }
4282             } else {  // Swipe to refresh is disabled.
4283                 // Disable the swipe refresh layout.
4284                 swipeRefreshLayout.setEnabled(false);
4285             }
4286
4287             // Get a handle for the cookie manager.
4288             CookieManager cookieManager = CookieManager.getInstance();
4289
4290             // Set the first-party cookie status.
4291             cookieManager.setAcceptCookie(currentWebView.getAcceptFirstPartyCookies());
4292
4293             // Update the privacy icons.  `true` redraws the icons in the app bar.
4294             updatePrivacyIcons(true);
4295
4296             // Get a handle for the input method manager.
4297             InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
4298
4299             // Remove the lint warning below that the input method manager might be null.
4300             assert inputMethodManager != null;
4301
4302             // Get the current URL.
4303             String url = currentWebView.getUrl();
4304
4305             // Update the URL edit text if not loading a new intent.  Otherwise, this will be handled by `onPageStarted()` (if called) and `onPageFinished()`.
4306             if (!loadingNewIntent) {  // A new intent is not being loaded.
4307                 if ((url == null) || url.equals("about:blank")) {  // The WebView is blank.
4308                     // Display the hint in the URL edit text.
4309                     urlEditText.setText("");
4310
4311                     // Request focus for the URL text box.
4312                     urlEditText.requestFocus();
4313
4314                     // Display the keyboard.
4315                     inputMethodManager.showSoftInput(urlEditText, 0);
4316                 } else {  // The WebView has a loaded URL.
4317                     // Clear the focus from the URL text box.
4318                     urlEditText.clearFocus();
4319
4320                     // Hide the soft keyboard.
4321                     inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
4322
4323                     // Display the current URL in the URL text box.
4324                     urlEditText.setText(url);
4325
4326                     // Highlight the URL text.
4327                     highlightUrlText();
4328                 }
4329             } else {  // A new intent is being loaded.
4330                 // Reset the loading new intent tracker.
4331                 loadingNewIntent = false;
4332             }
4333
4334             // Set the background to indicate the domain settings status.
4335             if (currentWebView.getDomainSettingsApplied()) {
4336                 // Set a green background on the URL relative layout to indicate that custom domain settings are being used. The deprecated `.getDrawable()` must be used until the minimum API >= 21.
4337                 if (darkTheme) {
4338                     urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
4339                 } else {
4340                     urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
4341                 }
4342             } else {
4343                 urlRelativeLayout.setBackground(getResources().getDrawable(R.color.transparent));
4344             }
4345         }
4346     }
4347
4348     @Override
4349     public void initializeWebView(NestedScrollWebView nestedScrollWebView, int pageNumber, ProgressBar progressBar, String url) {
4350         // Get handles for the activity views.
4351         FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
4352         DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
4353         RelativeLayout mainContentRelativeLayout = findViewById(R.id.main_content_relativelayout);
4354         ActionBar actionBar = getSupportActionBar();
4355         LinearLayout tabsLinearLayout = findViewById(R.id.tabs_linearlayout);
4356         EditText urlEditText = findViewById(R.id.url_edittext);
4357         TabLayout tabLayout = findViewById(R.id.tablayout);
4358         SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
4359
4360         // Remove the incorrect lint warning below that the action bar might be null.
4361         assert actionBar != null;
4362
4363         // Get a handle for the activity
4364         Activity activity = this;
4365
4366         // Get a handle for the input method manager.
4367         InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
4368
4369         // Instantiate the blocklist helper.
4370         BlockListHelper blockListHelper = new BlockListHelper();
4371
4372         // Remove the lint warning below that the input method manager might be null.
4373         assert inputMethodManager != null;
4374
4375         // Get a handle for the shared preferences.
4376         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4377
4378         // Get the relevant preferences.
4379         boolean downloadWithExternalApp = sharedPreferences.getBoolean("download_with_external_app", false);
4380
4381         // Initialize the favorite icon.
4382         nestedScrollWebView.initializeFavoriteIcon();
4383
4384         // Set the app bar scrolling.
4385         nestedScrollWebView.setNestedScrollingEnabled(sharedPreferences.getBoolean("scroll_app_bar", true));
4386
4387         // Allow pinch to zoom.
4388         nestedScrollWebView.getSettings().setBuiltInZoomControls(true);
4389
4390         // Hide zoom controls.
4391         nestedScrollWebView.getSettings().setDisplayZoomControls(false);
4392
4393         // Don't allow mixed content (HTTP and HTTPS) on the same website.
4394         if (Build.VERSION.SDK_INT >= 21) {
4395             nestedScrollWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW);
4396         }
4397
4398         // Set the WebView to use a wide viewport.  Otherwise, some web pages will be scrunched and some content will render outside the screen.
4399         nestedScrollWebView.getSettings().setUseWideViewPort(true);
4400
4401         // Set the WebView to load in overview mode (zoomed out to the maximum width).
4402         nestedScrollWebView.getSettings().setLoadWithOverviewMode(true);
4403
4404         // Explicitly disable geolocation.
4405         nestedScrollWebView.getSettings().setGeolocationEnabled(false);
4406
4407         // Create a double-tap gesture detector to toggle full-screen mode.
4408         GestureDetector doubleTapGestureDetector = new GestureDetector(getApplicationContext(), new GestureDetector.SimpleOnGestureListener() {
4409             // Override `onDoubleTap()`.  All other events are handled using the default settings.
4410             @Override
4411             public boolean onDoubleTap(MotionEvent event) {
4412                 if (fullScreenBrowsingModeEnabled) {  // Only process the double-tap if full screen browsing mode is enabled.
4413                     // Toggle the full screen browsing mode tracker.
4414                     inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
4415
4416                     // Toggle the full screen browsing mode.
4417                     if (inFullScreenBrowsingMode) {  // Switch to full screen mode.
4418                         // Store the swipe refresh layout top padding.
4419                         swipeRefreshLayoutPaddingTop = swipeRefreshLayout.getPaddingTop();
4420
4421                         // Hide the app bar if specified.
4422                         if (hideAppBar) {
4423                             // Close the find on page bar if it is visible.
4424                             closeFindOnPage(null);
4425
4426                             // Hide the tab linear layout.
4427                             tabsLinearLayout.setVisibility(View.GONE);
4428
4429                             // Hide the action bar.
4430                             actionBar.hide();
4431
4432                             // Check to see if app bar scrolling is disabled.
4433                             if (!scrollAppBar) {
4434                                 // Remove the padding from the top of the swipe refresh layout.
4435                                 swipeRefreshLayout.setPadding(0, 0, 0, 0);
4436                             }
4437                         }
4438
4439                         // Hide the banner ad in the free flavor.
4440                         if (BuildConfig.FLAVOR.contentEquals("free")) {
4441                             AdHelper.hideAd(findViewById(R.id.adview));
4442                         }
4443
4444                         // Remove the translucent status flag.  This is necessary so the root frame layout can fill the entire screen.
4445                         getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4446
4447                         /* Hide the system bars.
4448                          * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4449                          * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4450                          * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4451                          * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4452                          */
4453                         rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
4454                                 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
4455                     } else {  // Switch to normal viewing mode.
4456                         // Show the tab linear layout.
4457                         tabsLinearLayout.setVisibility(View.VISIBLE);
4458
4459                         // Show the action bar.
4460                         actionBar.show();
4461
4462                         // Check to see if app bar scrolling is disabled.
4463                         if (!scrollAppBar) {
4464                             // Add the padding from the top of the swipe refresh layout.
4465                             swipeRefreshLayout.setPadding(0, swipeRefreshLayoutPaddingTop, 0, 0);
4466                         }
4467
4468                         // Show the banner ad in the free flavor.
4469                         if (BuildConfig.FLAVOR.contentEquals("free")) {
4470                             // Reload the ad.
4471                             AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
4472                         }
4473
4474                         // Remove the `SYSTEM_UI` flags from the root frame layout.
4475                         rootFrameLayout.setSystemUiVisibility(0);
4476
4477                         // Add the translucent status flag.
4478                         getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4479                     }
4480
4481                     // Consume the double-tap.
4482                     return true;
4483                 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
4484                     return false;
4485                 }
4486             }
4487         });
4488
4489         // Pass all touch events on the WebView through the double-tap gesture detector.
4490         nestedScrollWebView.setOnTouchListener((View view, MotionEvent event) -> {
4491             // Call `performClick()` on the view, which is required for accessibility.
4492             view.performClick();
4493
4494             // Send the event to the gesture detector.
4495             return doubleTapGestureDetector.onTouchEvent(event);
4496         });
4497
4498         // Register the WebView for a context menu.  This is used to see link targets and download images.
4499         registerForContextMenu(nestedScrollWebView);
4500
4501         // Allow the downloading of files.
4502         nestedScrollWebView.setDownloadListener((String downloadUrl, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
4503             // Check if the download should be processed by an external app.
4504             if (downloadWithExternalApp) {  // Download with an external app.
4505                 // Create a download intent.  Not specifying the action type will display the maximum number of options.
4506                 Intent downloadIntent = new Intent();
4507
4508                 // Set the URI and the MIME type.  Specifying `text/html` displays a good number of options.
4509                 downloadIntent.setDataAndType(Uri.parse(downloadUrl), "text/html");
4510
4511                 // Flag the intent to open in a new task.
4512                 downloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4513
4514                 // Show the chooser.
4515                 startActivity(Intent.createChooser(downloadIntent, getString(R.string.open_with)));
4516             } else {  // Download with Android's download manager.
4517                 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
4518                 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {  // The storage permission has not been granted.
4519                     // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
4520
4521                     // Store the variables for future use by `onRequestPermissionsResult()`.
4522                     this.downloadUrl = downloadUrl;
4523                     downloadContentDisposition = contentDisposition;
4524                     downloadContentLength = contentLength;
4525
4526                     // Show a dialog if the user has previously denied the permission.
4527                     if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {  // Show a dialog explaining the request first.
4528                         // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
4529                         DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
4530
4531                         // Show the download location permission alert dialog.  The permission will be requested when the the dialog is closed.
4532                         downloadLocationPermissionDialogFragment.show(getSupportFragmentManager(), getString(R.string.download_location));
4533                     } else {  // Show the permission request directly.
4534                         // Request the permission.  The download dialog will be launched by `onRequestPermissionResult()`.
4535                         ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
4536                     }
4537                 } else {  // The storage permission has already been granted.
4538                     // Get a handle for the download file alert dialog.
4539                     DialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(downloadUrl, contentDisposition, contentLength);
4540
4541                     // Show the download file alert dialog.
4542                     downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
4543                 }
4544             }
4545         });
4546
4547         // Update the find on page count.
4548         nestedScrollWebView.setFindListener(new WebView.FindListener() {
4549             // Get a handle for `findOnPageCountTextView`.
4550             final TextView findOnPageCountTextView = findViewById(R.id.find_on_page_count_textview);
4551
4552             @Override
4553             public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
4554                 if ((isDoneCounting) && (numberOfMatches == 0)) {  // There are no matches.
4555                     // Set `findOnPageCountTextView` to `0/0`.
4556                     findOnPageCountTextView.setText(R.string.zero_of_zero);
4557                 } else if (isDoneCounting) {  // There are matches.
4558                     // `activeMatchOrdinal` is zero-based.
4559                     int activeMatch = activeMatchOrdinal + 1;
4560
4561                     // Build the match string.
4562                     String matchString = activeMatch + "/" + numberOfMatches;
4563
4564                     // Set `findOnPageCountTextView`.
4565                     findOnPageCountTextView.setText(matchString);
4566                 }
4567             }
4568         });
4569
4570         // Update the status of swipe to refresh based on the scroll position of the nested scroll WebView.
4571         // Once the minimum API >= 23 this can be replaced with `nestedScrollWebView.setOnScrollChangeListener()`.
4572         nestedScrollWebView.getViewTreeObserver().addOnScrollChangedListener(() -> {
4573             if (nestedScrollWebView.getSwipeToRefresh()) {
4574                 // Only enable swipe to refresh if the WebView is scrolled to the top.
4575                 swipeRefreshLayout.setEnabled(nestedScrollWebView.getScrollY() == 0);
4576             }
4577         });
4578
4579         // Set the web chrome client.
4580         nestedScrollWebView.setWebChromeClient(new WebChromeClient() {
4581             // Update the progress bar when a page is loading.
4582             @Override
4583             public void onProgressChanged(WebView view, int progress) {
4584                 // Inject the night mode CSS if night mode is enabled.
4585                 if (nestedScrollWebView.getNightMode()) {  // Night mode is enabled.
4586                     // `background-color: #212121` sets the background to be dark gray.  `color: #BDBDBD` sets the text color to be light gray.  `box-shadow: none` removes a lower underline on links
4587                     // used by WordPress.  `text-decoration: none` removes all text underlines.  `text-shadow: none` removes text shadows, which usually have a hard coded color.
4588                     // `border: none` removes all borders, which can also be used to underline text.  `a {color: #1565C0}` sets links to be a dark blue.
4589                     // `::selection {background: #0D47A1}' sets the text selection highlight color to be a dark blue. `!important` takes precedent over any existing sub-settings.
4590                     nestedScrollWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; " +
4591                             "style.innerHTML = '* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important;" +
4592                             "text-shadow: none !important; border: none !important;} a {color: #1565C0 !important;} ::selection {background: #0D47A1 !important;}'; parent.appendChild(style)})()", value -> {
4593                         // Initialize a handler to display `mainWebView`.
4594                         Handler displayWebViewHandler = new Handler();
4595
4596                         // Setup a runnable to display `mainWebView` after a delay to allow the CSS to be applied.
4597                         Runnable displayWebViewRunnable = () -> {
4598                             // Only display `mainWebView` if the progress bar is gone.  This prevents the display of the `WebView` while it is still loading.
4599                             if (progressBar.getVisibility() == View.GONE) {
4600                                 nestedScrollWebView.setVisibility(View.VISIBLE);
4601                             }
4602                         };
4603
4604                         // Display the WebView after 500 milliseconds.
4605                         displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
4606                     });
4607                 } else {  // Night mode is disabled.
4608                     // Display the nested scroll WebView if night mode is disabled.
4609                     // Because of a race condition between `applyDomainSettings` and `onPageStarted`,
4610                     // when night mode is set by domain settings the WebView may be hidden even if night mode is not currently enabled.
4611                     nestedScrollWebView.setVisibility(View.VISIBLE);
4612                 }
4613
4614                 // Update the progress bar.
4615                 progressBar.setProgress(progress);
4616
4617                 // Set the visibility of the progress bar.
4618                 if (progress < 100) {
4619                     // Show the progress bar.
4620                     progressBar.setVisibility(View.VISIBLE);
4621                 } else {
4622                     // Hide the progress bar.
4623                     progressBar.setVisibility(View.GONE);
4624
4625                     //Stop the swipe to refresh indicator if it is running
4626                     swipeRefreshLayout.setRefreshing(false);
4627                 }
4628             }
4629
4630             // Set the favorite icon when it changes.
4631             @Override
4632             public void onReceivedIcon(WebView view, Bitmap icon) {
4633                 // Only update the favorite icon if the website has finished loading.
4634                 if (progressBar.getVisibility() == View.GONE) {
4635                     // Store the new favorite icon.
4636                     nestedScrollWebView.setFavoriteOrDefaultIcon(icon);
4637
4638                     // Get the current page position.
4639                     int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
4640
4641                     // Get the current tab.
4642                     TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
4643
4644                     // Check to see if the tab has been populated.
4645                     if (tab != null) {
4646                         // Get the custom view from the tab.
4647                         View tabView = tab.getCustomView();
4648
4649                         // Check to see if the custom tab view has been populated.
4650                         if (tabView != null) {
4651                             // Get the favorite icon image view from the tab.
4652                             ImageView tabFavoriteIconImageView = tabView.findViewById(R.id.favorite_icon_imageview);
4653
4654                             // Display the favorite icon in the tab.
4655                             tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
4656                         }
4657                     }
4658                 }
4659             }
4660
4661             // Save a copy of the title when it changes.
4662             @Override
4663             public void onReceivedTitle(WebView view, String title) {
4664                 // Get the current page position.
4665                 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
4666
4667                 // Get the current tab.
4668                 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
4669
4670                 // Only populate the title text view if the tab has been fully created.
4671                 if (tab != null) {
4672                     // Get the custom view from the tab.
4673                     View tabView = tab.getCustomView();
4674
4675                     // Remove the incorrect warning below that the current tab view might be null.
4676                     assert tabView != null;
4677
4678                     // Get the title text view from the tab.
4679                     TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
4680
4681                     // Set the title as the tab text.
4682                     tabTitleTextView.setText(title);
4683                 }
4684             }
4685
4686             // Enter full screen video.
4687             @Override
4688             public void onShowCustomView(View video, CustomViewCallback callback) {
4689                 // Get a handle for the full screen video frame layout.
4690                 FrameLayout fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
4691
4692                 // Set the full screen video flag.
4693                 displayingFullScreenVideo = true;
4694
4695                 // Pause the ad if this is the free flavor.
4696                 if (BuildConfig.FLAVOR.contentEquals("free")) {
4697                     // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
4698                     AdHelper.pauseAd(findViewById(R.id.adview));
4699                 }
4700
4701                 // Hide the keyboard.
4702                 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
4703
4704                 // Hide the main content relative layout.
4705                 mainContentRelativeLayout.setVisibility(View.GONE);
4706
4707                 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
4708                 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
4709
4710                 // Remove the translucent status flag.  This is necessary so the root frame layout can fill the entire screen.
4711                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4712
4713                 /* Hide the system bars.
4714                  * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4715                  * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4716                  * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4717                  * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4718                  */
4719                 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
4720                         View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
4721
4722                 // Disable the sliding drawers.
4723                 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
4724
4725                 // Add the video view to the full screen video frame layout.
4726                 fullScreenVideoFrameLayout.addView(video);
4727
4728                 // Show the full screen video frame layout.
4729                 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
4730             }
4731
4732             // Exit full screen video.
4733             @Override
4734             public void onHideCustomView() {
4735                 // Get a handle for the full screen video frame layout.
4736                 FrameLayout fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
4737
4738                 // Unset the full screen video flag.
4739                 displayingFullScreenVideo = false;
4740
4741                 // Remove all the views from the full screen video frame layout.
4742                 fullScreenVideoFrameLayout.removeAllViews();
4743
4744                 // Hide the full screen video frame layout.
4745                 fullScreenVideoFrameLayout.setVisibility(View.GONE);
4746
4747                 // Enable the sliding drawers.
4748                 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
4749
4750                 // Show the main content relative layout.
4751                 mainContentRelativeLayout.setVisibility(View.VISIBLE);
4752
4753                 // Apply the appropriate full screen mode flags.
4754                 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {  // Privacy Browser is currently in full screen browsing mode.
4755                     // Hide the app bar if specified.
4756                     if (hideAppBar) {
4757                         // Hide the tab linear layout.
4758                         tabsLinearLayout.setVisibility(View.GONE);
4759
4760                         // Hide the action bar.
4761                         actionBar.hide();
4762                     }
4763
4764                     // Hide the banner ad in the free flavor.
4765                     if (BuildConfig.FLAVOR.contentEquals("free")) {
4766                         AdHelper.hideAd(findViewById(R.id.adview));
4767                     }
4768
4769                     // Remove the translucent status flag.  This is necessary so the root frame layout can fill the entire screen.
4770                     getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4771
4772                     /* Hide the system bars.
4773                      * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4774                      * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4775                      * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4776                      * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4777                      */
4778                     rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
4779                             View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
4780                 } else {  // Switch to normal viewing mode.
4781                     // Remove the `SYSTEM_UI` flags from the root frame layout.
4782                     rootFrameLayout.setSystemUiVisibility(0);
4783
4784                     // Add the translucent status flag.
4785                     getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4786                 }
4787
4788                 // Reload the ad for the free flavor if not in full screen mode.
4789                 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
4790                     // Reload the ad.
4791                     AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
4792                 }
4793             }
4794
4795             // Upload files.
4796             @Override
4797             public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
4798                 // Show the file chooser if the device is running API >= 21.
4799                 if (Build.VERSION.SDK_INT >= 21) {
4800                     // Store the file path callback.
4801                     fileChooserCallback = filePathCallback;
4802
4803                     // Create an intent to open a chooser based ont the file chooser parameters.
4804                     Intent fileChooserIntent = fileChooserParams.createIntent();
4805
4806                     // Open the file chooser.  Currently only one `startActivityForResult` exists in this activity, so the request code, used to differentiate them, is simply `0`.
4807                     startActivityForResult(fileChooserIntent, 0);
4808                 }
4809                 return true;
4810             }
4811         });
4812
4813         nestedScrollWebView.setWebViewClient(new WebViewClient() {
4814             // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
4815             // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
4816             @Override
4817             public boolean shouldOverrideUrlLoading(WebView view, String url) {
4818                 // Sanitize the url.
4819                 url = sanitizeUrl(url);
4820
4821                 if (url.startsWith("http")) {  // Load the URL in Privacy Browser.
4822                     // Apply the domain settings for the new URL.  This doesn't do anything if the domain has not changed.
4823                     boolean userAgentChanged = applyDomainSettings(nestedScrollWebView, url, true, false);
4824
4825                     // Check if the user agent has changed.
4826                     if (userAgentChanged) {
4827                         // Manually load the URL.  The changing of the user agent will cause WebView to reload the previous URL.
4828                         nestedScrollWebView.loadUrl(url, customHeaders);
4829
4830                         // Returning true indicates that Privacy Browser is manually handling the loading of the URL.
4831                         return true;
4832                     } else {
4833                         // Returning false causes the current WebView to handle the URL and prevents it from adding redirects to the history list.
4834                         return false;
4835                     }
4836                 } else if (url.startsWith("mailto:")) {  // Load the email address in an external email program.
4837                     // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
4838                     Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
4839
4840                     // Parse the url and set it as the data for the intent.
4841                     emailIntent.setData(Uri.parse(url));
4842
4843                     // Open the email program in a new task instead of as part of Privacy Browser.
4844                     emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4845
4846                     // Make it so.
4847                     startActivity(emailIntent);
4848
4849                     // Returning true indicates Privacy Browser is handling the URL by creating an intent.
4850                     return true;
4851                 } else if (url.startsWith("tel:")) {  // Load the phone number in the dialer.
4852                     // Open the dialer and load the phone number, but wait for the user to place the call.
4853                     Intent dialIntent = new Intent(Intent.ACTION_DIAL);
4854
4855                     // Add the phone number to the intent.
4856                     dialIntent.setData(Uri.parse(url));
4857
4858                     // Open the dialer in a new task instead of as part of Privacy Browser.
4859                     dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4860
4861                     // Make it so.
4862                     startActivity(dialIntent);
4863
4864                     // Returning true indicates Privacy Browser is handling the URL by creating an intent.
4865                     return true;
4866                 } else {  // Load a system chooser to select an app that can handle the URL.
4867                     // Open an app that can handle the URL.
4868                     Intent genericIntent = new Intent(Intent.ACTION_VIEW);
4869
4870                     // Add the URL to the intent.
4871                     genericIntent.setData(Uri.parse(url));
4872
4873                     // List all apps that can handle the URL instead of just opening the first one.
4874                     genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
4875
4876                     // Open the app in a new task instead of as part of Privacy Browser.
4877                     genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4878
4879                     // Start the app or display a snackbar if no app is available to handle the URL.
4880                     try {
4881                         startActivity(genericIntent);
4882                     } catch (ActivityNotFoundException exception) {
4883                         Snackbar.make(nestedScrollWebView, getString(R.string.unrecognized_url) + "  " + url, Snackbar.LENGTH_SHORT).show();
4884                     }
4885
4886                     // Returning true indicates Privacy Browser is handling the URL by creating an intent.
4887                     return true;
4888                 }
4889             }
4890
4891             // Check requests against the block lists.  The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
4892             @Override
4893             public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
4894                 // Sanitize the URL.
4895                 url = sanitizeUrl(url);
4896
4897                 // Get a handle for the navigation view.
4898                 NavigationView navigationView = findViewById(R.id.navigationview);
4899
4900                 // Get a handle for the navigation menu.
4901                 Menu navigationMenu = navigationView.getMenu();
4902
4903                 // Get a handle for the navigation requests menu item.  The menu is 0 based.
4904                 MenuItem navigationRequestsMenuItem = navigationMenu.getItem(5);
4905
4906                 // Create an empty web resource response to be used if the resource request is blocked.
4907                 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
4908
4909                 // Reset the whitelist results tracker.
4910                 String[] whitelistResultStringArray = null;
4911
4912                 // Initialize the third party request tracker.
4913                 boolean isThirdPartyRequest = false;
4914
4915                 // Get the current URL.  `.getUrl()` throws an error because operations on the WebView cannot be made from this thread.
4916                 String currentBaseDomain = nestedScrollWebView.getCurrentDomainName();
4917
4918                 // Store a copy of the current domain for use in later requests.
4919                 String currentDomain = currentBaseDomain;
4920
4921                 // Nobody is happy when comparing null strings.
4922                 if ((currentBaseDomain != null) && (url != null)) {
4923                     // Convert the request URL to a URI.
4924                     Uri requestUri = Uri.parse(url);
4925
4926                     // Get the request host name.
4927                     String requestBaseDomain = requestUri.getHost();
4928
4929                     // Only check for third-party requests if the current base domain is not empty and the request domain is not null.
4930                     if (!currentBaseDomain.isEmpty() && (requestBaseDomain != null)) {
4931                         // Determine the current base domain.
4932                         while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) {  // There is at least one subdomain.
4933                             // Remove the first subdomain.
4934                             currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
4935                         }
4936
4937                         // Determine the request base domain.
4938                         while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) {  // There is at least one subdomain.
4939                             // Remove the first subdomain.
4940                             requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
4941                         }
4942
4943                         // Update the third party request tracker.
4944                         isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
4945                     }
4946                 }
4947
4948                 // Get the current WebView page position.
4949                 int webViewPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
4950
4951                 // Determine if the WebView is currently displayed.
4952                 boolean webViewDisplayed = (webViewPagePosition == tabLayout.getSelectedTabPosition());
4953
4954                 // Block third-party requests if enabled.
4955                 if (isThirdPartyRequest && nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS)) {
4956                     // Add the result to the resource requests.
4957                     nestedScrollWebView.addResourceRequest(new String[]{BlockListHelper.REQUEST_THIRD_PARTY, url});
4958
4959                     // Increment the blocked requests counters.
4960                     nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
4961                     nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS);
4962
4963                     // Update the titles of the blocklist menu items if the WebView is currently displayed.
4964                     if (webViewDisplayed) {
4965                         // Updating the UI must be run from the UI thread.
4966                         activity.runOnUiThread(() -> {
4967                             // Update the menu item titles.
4968                             navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
4969
4970                             // Update the options menu if it has been populated.
4971                             if (optionsMenu != null) {
4972                                 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
4973                                 optionsMenu.findItem(R.id.block_all_third_party_requests).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " +
4974                                         getString(R.string.block_all_third_party_requests));
4975                             }
4976                         });
4977                     }
4978
4979                     // Return an empty web resource response.
4980                     return emptyWebResourceResponse;
4981                 }
4982
4983                 // Check UltraPrivacy if it is enabled.
4984                 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY)) {
4985                     // Check the URL against UltraPrivacy.
4986                     String[] ultraPrivacyResults = blockListHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraPrivacy);
4987
4988                     // Process the UltraPrivacy results.
4989                     if (ultraPrivacyResults[0].equals(BlockListHelper.REQUEST_BLOCKED)) {  // The resource request matched UltraPrivacy's blacklist.
4990                         // Add the result to the resource requests.
4991                         nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
4992                                 ultraPrivacyResults[5]});
4993
4994                         // Increment the blocked requests counters.
4995                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
4996                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRA_PRIVACY);
4997
4998                         // Update the titles of the blocklist menu items if the WebView is currently displayed.
4999                         if (webViewDisplayed) {
5000                             // Updating the UI must be run from the UI thread.
5001                             activity.runOnUiThread(() -> {
5002                                 // Update the menu item titles.
5003                                 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5004
5005                                 // Update the options menu if it has been populated.
5006                                 if (optionsMenu != null) {
5007                                     optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5008                                     optionsMenu.findItem(R.id.ultraprivacy).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRA_PRIVACY) + " - " + getString(R.string.ultraprivacy));
5009                                 }
5010                             });
5011                         }
5012
5013                         // The resource request was blocked.  Return an empty web resource response.
5014                         return emptyWebResourceResponse;
5015                     } else if (ultraPrivacyResults[0].equals(BlockListHelper.REQUEST_ALLOWED)) {  // The resource request matched UltraPrivacy's whitelist.
5016                         // Add a whitelist entry to the resource requests array.
5017                         nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5018                                 ultraPrivacyResults[5]});
5019
5020                         // The resource request has been allowed by UltraPrivacy.  `return null` loads the requested resource.
5021                         return null;
5022                     }
5023                 }
5024
5025                 // Check EasyList if it is enabled.
5026                 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST)) {
5027                     // Check the URL against EasyList.
5028                     String[] easyListResults = blockListHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyList);
5029
5030                     // Process the EasyList results.
5031                     if (easyListResults[0].equals(BlockListHelper.REQUEST_BLOCKED)) {  // The resource request matched EasyList's blacklist.
5032                         // Add the result to the resource requests.
5033                         nestedScrollWebView.addResourceRequest(new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]});
5034
5035                         // Increment the blocked requests counters.
5036                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5037                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASY_LIST);
5038
5039                         // Update the titles of the blocklist menu items if the WebView is currently displayed.
5040                         if (webViewDisplayed) {
5041                             // Updating the UI must be run from the UI thread.
5042                             activity.runOnUiThread(() -> {
5043                                 // Update the menu item titles.
5044                                 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5045
5046                                 // Update the options menu if it has been populated.
5047                                 if (optionsMenu != null) {
5048                                     optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5049                                     optionsMenu.findItem(R.id.easylist).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASY_LIST) + " - " + getString(R.string.easylist));
5050                                 }
5051                             });
5052                         }
5053
5054                         // The resource request was blocked.  Return an empty web resource response.
5055                         return emptyWebResourceResponse;
5056                     } else if (easyListResults[0].equals(BlockListHelper.REQUEST_ALLOWED)) {  // The resource request matched EasyList's whitelist.
5057                         // Update the whitelist result string array tracker.
5058                         whitelistResultStringArray = new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]};
5059                     }
5060                 }
5061
5062                 // Check EasyPrivacy if it is enabled.
5063                 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY)) {
5064                     // Check the URL against EasyPrivacy.
5065                     String[] easyPrivacyResults = blockListHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyPrivacy);
5066
5067                     // Process the EasyPrivacy results.
5068                     if (easyPrivacyResults[0].equals(BlockListHelper.REQUEST_BLOCKED)) {  // The resource request matched EasyPrivacy's blacklist.
5069                         // Add the result to the resource requests.
5070                         nestedScrollWebView.addResourceRequest(new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4],
5071                                 easyPrivacyResults[5]});
5072
5073                         // Increment the blocked requests counters.
5074                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5075                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASY_PRIVACY);
5076
5077                         // Update the titles of the blocklist menu items if the WebView is currently displayed.
5078                         if (webViewDisplayed) {
5079                             // Updating the UI must be run from the UI thread.
5080                             activity.runOnUiThread(() -> {
5081                                 // Update the menu item titles.
5082                                 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5083
5084                                 // Update the options menu if it has been populated.
5085                                 if (optionsMenu != null) {
5086                                     optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5087                                     optionsMenu.findItem(R.id.easyprivacy).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASY_PRIVACY) + " - " + getString(R.string.easyprivacy));
5088                                 }
5089                             });
5090                         }
5091
5092                         // The resource request was blocked.  Return an empty web resource response.
5093                         return emptyWebResourceResponse;
5094                     } else if (easyPrivacyResults[0].equals(BlockListHelper.REQUEST_ALLOWED)) {  // The resource request matched EasyPrivacy's whitelist.
5095                         // Update the whitelist result string array tracker.
5096                         whitelistResultStringArray = new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5]};
5097                     }
5098                 }
5099
5100                 // Check Fanboy’s Annoyance List if it is enabled.
5101                 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST)) {
5102                     // Check the URL against Fanboy's Annoyance List.
5103                     String[] fanboysAnnoyanceListResults = blockListHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList);
5104
5105                     // Process the Fanboy's Annoyance List results.
5106                     if (fanboysAnnoyanceListResults[0].equals(BlockListHelper.REQUEST_BLOCKED)) {  // The resource request matched Fanboy's Annoyance List's blacklist.
5107                         // Add the result to the resource requests.
5108                         nestedScrollWebView.addResourceRequest(new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5109                                 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]});
5110
5111                         // Increment the blocked requests counters.
5112                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5113                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST);
5114
5115                         // Update the titles of the blocklist menu items if the WebView is currently displayed.
5116                         if (webViewDisplayed) {
5117                             // Updating the UI must be run from the UI thread.
5118                             activity.runOnUiThread(() -> {
5119                                 // Update the menu item titles.
5120                                 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5121
5122                                 // Update the options menu if it has been populated.
5123                                 if (optionsMenu != null) {
5124                                     optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5125                                     optionsMenu.findItem(R.id.fanboys_annoyance_list).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " +
5126                                             getString(R.string.fanboys_annoyance_list));
5127                                 }
5128                             });
5129                         }
5130
5131                         // The resource request was blocked.  Return an empty web resource response.
5132                         return emptyWebResourceResponse;
5133                     } else if (fanboysAnnoyanceListResults[0].equals(BlockListHelper.REQUEST_ALLOWED)){  // The resource request matched Fanboy's Annoyance List's whitelist.
5134                         // Update the whitelist result string array tracker.
5135                         whitelistResultStringArray = new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5136                                 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]};
5137                     }
5138                 } else if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST)) {  // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
5139                     // Check the URL against Fanboy's Annoyance List.
5140                     String[] fanboysSocialListResults = blockListHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysSocialList);
5141
5142                     // Process the Fanboy's Social Blocking List results.
5143                     if (fanboysSocialListResults[0].equals(BlockListHelper.REQUEST_BLOCKED)) {  // The resource request matched Fanboy's Social Blocking List's blacklist.
5144                         // Add the result to the resource requests.
5145                         nestedScrollWebView.addResourceRequest(new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5146                                 fanboysSocialListResults[4], fanboysSocialListResults[5]});
5147
5148                         // Increment the blocked requests counters.
5149                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5150                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST);
5151
5152                         // Update the titles of the blocklist menu items if the WebView is currently displayed.
5153                         if (webViewDisplayed) {
5154                             // Updating the UI must be run from the UI thread.
5155                             activity.runOnUiThread(() -> {
5156                                 // Update the menu item titles.
5157                                 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5158
5159                                 // Update the options menu if it has been populated.
5160                                 if (optionsMenu != null) {
5161                                     optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5162                                     optionsMenu.findItem(R.id.fanboys_social_blocking_list).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " +
5163                                             getString(R.string.fanboys_social_blocking_list));
5164                                 }
5165                             });
5166                         }
5167
5168                         // The resource request was blocked.  Return an empty web resource response.
5169                         return emptyWebResourceResponse;
5170                     } else if (fanboysSocialListResults[0].equals(BlockListHelper.REQUEST_ALLOWED)) {  // The resource request matched Fanboy's Social Blocking List's whitelist.
5171                         // Update the whitelist result string array tracker.
5172                         whitelistResultStringArray = new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5173                                 fanboysSocialListResults[4], fanboysSocialListResults[5]};
5174                     }
5175                 }
5176
5177                 // Add the request to the log because it hasn't been processed by any of the previous checks.
5178                 if (whitelistResultStringArray != null) {  // The request was processed by a whitelist.
5179                     nestedScrollWebView.addResourceRequest(whitelistResultStringArray);
5180                 } else {  // The request didn't match any blocklist entry.  Log it as a default request.
5181                     nestedScrollWebView.addResourceRequest(new String[]{BlockListHelper.REQUEST_DEFAULT, url});
5182                 }
5183
5184                 // The resource request has not been blocked.  `return null` loads the requested resource.
5185                 return null;
5186             }
5187
5188             // Handle HTTP authentication requests.
5189             @Override
5190             public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
5191                 // Store the handler.
5192                 nestedScrollWebView.setHttpAuthHandler(handler);
5193
5194                 // Instantiate an HTTP authentication dialog.
5195                 DialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm, nestedScrollWebView.getWebViewFragmentId());
5196
5197                 // Show the HTTP authentication dialog.
5198                 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
5199             }
5200
5201             @Override
5202             public void onPageStarted(WebView view, String url, Bitmap favicon) {
5203                 // Get the preferences.
5204                 boolean scrollAppBar = sharedPreferences.getBoolean("scroll_app_bar", true);
5205                 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
5206
5207                 // Get a handler for the app bar layout.
5208                 AppBarLayout appBarLayout = findViewById(R.id.appbar_layout);
5209
5210                 // Set the top padding of the swipe refresh layout according to the app bar scrolling preference.
5211                 if (scrollAppBar) {
5212                     // No padding is needed because it will automatically be placed below the app bar layout due to the scrolling layout behavior.
5213                     swipeRefreshLayout.setPadding(0, 0, 0, 0);
5214
5215                     // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5216                     swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10, defaultProgressViewEndOffset);
5217                 } else {
5218                     // Get the app bar layout height.  This can't be done in `applyAppSettings()` because the app bar is not yet populated.
5219                     int appBarHeight = appBarLayout.getHeight();
5220
5221                     // The swipe refresh layout must be manually moved below the app bar layout.
5222                     swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0);
5223
5224                     // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5225                     swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight);
5226                 }
5227
5228                 // Reset the list of resource requests.
5229                 nestedScrollWebView.clearResourceRequests();
5230
5231                 // Reset the requests counters.
5232                 nestedScrollWebView.resetRequestsCounters();
5233
5234                 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
5235                 if (nestedScrollWebView.getNightMode()) {
5236                     nestedScrollWebView.setVisibility(View.INVISIBLE);
5237                 } else {
5238                     nestedScrollWebView.setVisibility(View.VISIBLE);
5239                 }
5240
5241                 // Hide the keyboard.
5242                 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
5243
5244                 // Check to see if Privacy Browser is waiting on Orbot.
5245                 if (!waitingForOrbot) {  // Process the URL.
5246                     // Get the current page position.
5247                     int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5248
5249                     // Update the URL text bar if the page is currently selected.
5250                     if (tabLayout.getSelectedTabPosition() == currentPagePosition) {
5251                         // Clear the focus from the URL edit text.
5252                         urlEditText.clearFocus();
5253
5254                         // Display the formatted URL text.
5255                         urlEditText.setText(url);
5256
5257                         // Apply text highlighting to `urlTextBox`.
5258                         highlightUrlText();
5259                     }
5260
5261                     // Reset the list of host IP addresses.
5262                     nestedScrollWebView.clearCurrentIpAddresses();
5263
5264                     // Get a URI for the current URL.
5265                     Uri currentUri = Uri.parse(url);
5266
5267                     // Get the IP addresses for the host.
5268                     new GetHostIpAddresses(activity, getSupportFragmentManager(), nestedScrollWebView).execute(currentUri.getHost());
5269
5270                     // Apply any custom domain settings if the URL was loaded by navigating history.
5271                     if (nestedScrollWebView.getNavigatingHistory()) {
5272                         // Reset navigating history.
5273                         nestedScrollWebView.setNavigatingHistory(false);
5274
5275                         // Apply the domain settings.
5276                         boolean userAgentChanged = applyDomainSettings(nestedScrollWebView, url, true, false);
5277
5278                         // Manually load the URL if the user agent has changed, which will have caused the previous URL to be reloaded.
5279                         if (userAgentChanged) {
5280                             loadUrl(url);
5281                         }
5282                     }
5283
5284                     // Replace Refresh with Stop if the options menu has been created.  (The WebView typically begins loading before the menu items are instantiated.)
5285                     if (optionsMenu != null) {
5286                         // Get a handle for the refresh menu item.
5287                         MenuItem refreshMenuItem = optionsMenu.findItem(R.id.refresh);
5288
5289                         // Set the title.
5290                         refreshMenuItem.setTitle(R.string.stop);
5291
5292                         // Get the app bar and theme preferences.
5293                         boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
5294
5295                         // If the icon is displayed in the AppBar, set it according to the theme.
5296                         if (displayAdditionalAppBarIcons) {
5297                             if (darkTheme) {
5298                                 refreshMenuItem.setIcon(R.drawable.close_dark);
5299                             } else {
5300                                 refreshMenuItem.setIcon(R.drawable.close_light);
5301                             }
5302                         }
5303                     }
5304                 }
5305             }
5306
5307             @Override
5308             public void onPageFinished(WebView view, String url) {
5309                 // Reset the wide view port if it has been turned off by the waiting for Orbot message.
5310                 if (!waitingForOrbot) {
5311                     // Only use a wide view port if the URL starts with `http`, not for `file://` and `content://`.
5312                     nestedScrollWebView.getSettings().setUseWideViewPort(url.startsWith("http"));
5313                 }
5314
5315                 // Flush any cookies to persistent storage.  The cookie manager has become very lazy about flushing cookies in recent versions.
5316                 if (nestedScrollWebView.getAcceptFirstPartyCookies() && Build.VERSION.SDK_INT >= 21) {
5317                     CookieManager.getInstance().flush();
5318                 }
5319
5320                 // Update the Refresh menu item if the options menu has been created.
5321                 if (optionsMenu != null) {
5322                     // Get a handle for the refresh menu item.
5323                     MenuItem refreshMenuItem = optionsMenu.findItem(R.id.refresh);
5324
5325                     // Reset the Refresh title.
5326                     refreshMenuItem.setTitle(R.string.refresh);
5327
5328                     // Get the app bar and theme preferences.
5329                     boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
5330                     boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
5331
5332                     // If the icon is displayed in the AppBar, reset it according to the theme.
5333                     if (displayAdditionalAppBarIcons) {
5334                         if (darkTheme) {
5335                             refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
5336                         } else {
5337                             refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
5338                         }
5339                     }
5340                 }
5341
5342                 // Clear the cache and history if Incognito Mode is enabled.
5343                 if (incognitoModeEnabled) {
5344                     // Clear the cache.  `true` includes disk files.
5345                     nestedScrollWebView.clearCache(true);
5346
5347                     // Clear the back/forward history.
5348                     nestedScrollWebView.clearHistory();
5349
5350                     // Manually delete cache folders.
5351                     try {
5352                         // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
5353                         // which links to `/data/data/com.stoutner.privacybrowser.standard`.
5354                         String privateDataDirectoryString = getApplicationInfo().dataDir;
5355
5356                         // Delete the main cache directory.
5357                         Runtime.getRuntime().exec("rm -rf " + privateDataDirectoryString + "/cache");
5358
5359                         // Delete the secondary `Service Worker` cache directory.
5360                         // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
5361                         Runtime.getRuntime().exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
5362                     } catch (IOException e) {
5363                         // Do nothing if an error is thrown.
5364                     }
5365                 }
5366
5367                 // Update the URL text box and apply domain settings if not waiting on Orbot.
5368                 if (!waitingForOrbot) {
5369                     // Get the current page position.
5370                     int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5371
5372                     // Check the current website information against any pinned domain information if the current IP addresses have been loaded.
5373                     if ((nestedScrollWebView.hasPinnedSslCertificate() || nestedScrollWebView.hasPinnedIpAddresses()) && nestedScrollWebView.hasCurrentIpAddresses() &&
5374                             !nestedScrollWebView.ignorePinnedDomainInformation()) {
5375                         CheckPinnedMismatchHelper.checkPinnedMismatch(getSupportFragmentManager(), nestedScrollWebView);
5376                     }
5377
5378                     // Get the current URL from the nested scroll WebView.  This is more accurate than using the URL passed into the method, which is sometimes not the final one.
5379                     String currentUrl = nestedScrollWebView.getUrl();
5380
5381                     // Update the URL text bar if the page is currently selected and the user is not currently typing in the URL edit text.
5382                     // Crash records show that, in some crazy way, it is possible for the current URL to be blank at this point.
5383                     // Probably some sort of race condition when Privacy Browser is being resumed.
5384                     if ((tabLayout.getSelectedTabPosition() == currentPagePosition) && !urlEditText.hasFocus() && (currentUrl != null)) {
5385                         // Check to see if the URL is `about:blank`.
5386                         if (currentUrl.equals("about:blank")) {  // The WebView is blank.
5387                             // Display the hint in the URL edit text.
5388                             urlEditText.setText("");
5389
5390                             // Request focus for the URL text box.
5391                             urlEditText.requestFocus();
5392
5393                             // Display the keyboard.
5394                             inputMethodManager.showSoftInput(urlEditText, 0);
5395
5396                             // Hide the WebView, which causes the default background color to be displayed according to the theme.
5397                             nestedScrollWebView.setVisibility(View.INVISIBLE);
5398
5399                             // Apply the domain settings.  This clears any settings from the previous domain.
5400                             applyDomainSettings(nestedScrollWebView, "", true, false);
5401                         } else {  // The WebView has loaded a webpage.
5402                             // Display the final URL.  Getting the URL from the WebView instead of using the one provided by `onPageFinished()` makes websites like YouTube function correctly.
5403                             urlEditText.setText(currentUrl);
5404
5405                             // Apply text highlighting to the URL.
5406                             highlightUrlText();
5407                         }
5408                     }
5409
5410                     // Get the current tab.
5411                     TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
5412
5413                     // Only populate the title text view if the tab has been fully created.
5414                     if (tab != null) {
5415                         // Get the custom view from the tab.
5416                         View tabView = tab.getCustomView();
5417
5418                         // Remove the incorrect warning below that the current tab view might be null.
5419                         assert tabView != null;
5420
5421                         // Get the title text view from the tab.
5422                         TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
5423
5424                         // Set the title as the tab text.  Sometimes `onReceivedTitle()` is not called, especially when navigating history.
5425                         tabTitleTextView.setText(nestedScrollWebView.getTitle());
5426                     }
5427                 }
5428             }
5429
5430             // Handle SSL Certificate errors.
5431             @Override
5432             public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
5433                 // Get the current website SSL certificate.
5434                 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
5435
5436                 // Extract the individual pieces of information from the current website SSL certificate.
5437                 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
5438                 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
5439                 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
5440                 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
5441                 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
5442                 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
5443                 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
5444                 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
5445
5446                 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
5447                 if (nestedScrollWebView.hasPinnedSslCertificate()) {
5448                     // Get the pinned SSL certificate.
5449                     ArrayList<Object> pinnedSslCertificateArrayList = nestedScrollWebView.getPinnedSslCertificate();
5450
5451                     // Extract the arrays from the array list.
5452                     String[] pinnedSslCertificateStringArray = (String[]) pinnedSslCertificateArrayList.get(0);
5453                     Date[] pinnedSslCertificateDateArray = (Date[]) pinnedSslCertificateArrayList.get(1);
5454
5455                     // Check if the current SSL certificate matches the pinned certificate.
5456                     if (currentWebsiteIssuedToCName.equals(pinnedSslCertificateStringArray[0]) && currentWebsiteIssuedToOName.equals(pinnedSslCertificateStringArray[1]) &&
5457                         currentWebsiteIssuedToUName.equals(pinnedSslCertificateStringArray[2]) && currentWebsiteIssuedByCName.equals(pinnedSslCertificateStringArray[3]) &&
5458                         currentWebsiteIssuedByOName.equals(pinnedSslCertificateStringArray[4]) && currentWebsiteIssuedByUName.equals(pinnedSslCertificateStringArray[5]) &&
5459                         currentWebsiteSslStartDate.equals(pinnedSslCertificateDateArray[0]) && currentWebsiteSslEndDate.equals(pinnedSslCertificateDateArray[1])) {
5460
5461                         // An SSL certificate is pinned and matches the current domain certificate.  Proceed to the website without displaying an error.
5462                         handler.proceed();
5463                     }
5464                 } else {  // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
5465                     // Store the SSL error handler.
5466                     nestedScrollWebView.setSslErrorHandler(handler);
5467
5468                     // Instantiate an SSL certificate error alert dialog.
5469                     DialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error, nestedScrollWebView.getWebViewFragmentId());
5470
5471                     // Show the SSL certificate error dialog.
5472                     sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
5473                 }
5474             }
5475         });
5476
5477         // Check to see if this is the first page.
5478         if (pageNumber == 0) {
5479             // Set this nested scroll WebView as the current WebView.
5480             currentWebView = nestedScrollWebView;
5481
5482             // Apply the app settings from the shared preferences.
5483             applyAppSettings();
5484
5485             // Load the website if not waiting for Orbot to connect.
5486             if (!waitingForOrbot) {
5487                 // Get the intent that started the app.
5488                 Intent launchingIntent = getIntent();
5489
5490                 // Get the information from the intent.
5491                 String launchingIntentAction = launchingIntent.getAction();
5492                 Uri launchingIntentUriData = launchingIntent.getData();
5493
5494                 // If the intent action is a web search, perform the search.
5495                 if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) {
5496                     // Create an encoded URL string.
5497                     String encodedUrlString;
5498
5499                     // Sanitize the search input and convert it to a search.
5500                     try {
5501                         encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
5502                     } catch (UnsupportedEncodingException exception) {
5503                         encodedUrlString = "";
5504                     }
5505
5506                     // Load the completed search URL.
5507                     loadUrl(searchURL + encodedUrlString);
5508                 } else if (launchingIntentUriData != null){  // Check to see if the intent contains a new URL.
5509                     // Load the URL from the intent.
5510                     loadUrl(launchingIntentUriData.toString());
5511                 } else {  // The is no URL in the intent.
5512                     // Select the homepage based on the proxy through Orbot status.
5513                     if (proxyThroughOrbot) {
5514                         // Load the Tor homepage.
5515                         loadUrl(sharedPreferences.getString("tor_homepage", getString(R.string.tor_homepage_default_value)));
5516                     } else {
5517                         // Load the normal homepage.
5518                         loadUrl(sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
5519                     }
5520                 }
5521             }
5522         } else {  // This is not the first tab.
5523             // Apply the domain settings.
5524             applyDomainSettings(nestedScrollWebView, url, false, false);
5525
5526             // Load the URL.
5527             nestedScrollWebView.loadUrl(url, customHeaders);
5528
5529             // Display the keyboard if the URL is blank.
5530             if (url.equals("")) {
5531                 inputMethodManager.showSoftInput(urlEditText, 0);
5532             }
5533         }
5534     }
5535 }