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