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