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