2 * Copyright 2015-2022 Soren Stoutner <soren@stoutner.com>.
4 * Download cookie code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
6 * This file is part of Privacy Browser Android <https://www.stoutner.com/privacy-browser-android>.
8 * Privacy Browser Android 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.
13 * Privacy Browser Android 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.
18 * You should have received a copy of the GNU General Public License
19 * along with Privacy Browser Android. If not, see <http://www.gnu.org/licenses/>.
22 package com.stoutner.privacybrowser.activities;
24 import android.animation.ObjectAnimator;
25 import android.annotation.SuppressLint;
26 import android.app.Activity;
27 import android.app.Dialog;
28 import android.app.DownloadManager;
29 import android.app.SearchManager;
30 import android.content.ActivityNotFoundException;
31 import android.content.BroadcastReceiver;
32 import android.content.ClipData;
33 import android.content.ClipboardManager;
34 import android.content.Context;
35 import android.content.Intent;
36 import android.content.IntentFilter;
37 import android.content.SharedPreferences;
38 import android.content.pm.PackageManager;
39 import android.content.res.Configuration;
40 import android.database.Cursor;
41 import android.graphics.Bitmap;
42 import android.graphics.BitmapFactory;
43 import android.graphics.Typeface;
44 import android.graphics.drawable.BitmapDrawable;
45 import android.graphics.drawable.Drawable;
46 import android.net.Uri;
47 import android.net.http.SslCertificate;
48 import android.net.http.SslError;
49 import android.os.AsyncTask;
50 import android.os.Build;
51 import android.os.Bundle;
52 import android.os.Environment;
53 import android.os.Handler;
54 import android.os.Message;
55 import android.preference.PreferenceManager;
56 import android.print.PrintDocumentAdapter;
57 import android.print.PrintManager;
58 import android.provider.DocumentsContract;
59 import android.provider.OpenableColumns;
60 import android.text.Editable;
61 import android.text.Spanned;
62 import android.text.TextWatcher;
63 import android.text.style.ForegroundColorSpan;
64 import android.util.Patterns;
65 import android.util.TypedValue;
66 import android.view.ContextMenu;
67 import android.view.GestureDetector;
68 import android.view.KeyEvent;
69 import android.view.Menu;
70 import android.view.MenuItem;
71 import android.view.MotionEvent;
72 import android.view.View;
73 import android.view.ViewGroup;
74 import android.view.WindowManager;
75 import android.view.inputmethod.InputMethodManager;
76 import android.webkit.CookieManager;
77 import android.webkit.HttpAuthHandler;
78 import android.webkit.SslErrorHandler;
79 import android.webkit.ValueCallback;
80 import android.webkit.WebBackForwardList;
81 import android.webkit.WebChromeClient;
82 import android.webkit.WebResourceRequest;
83 import android.webkit.WebResourceResponse;
84 import android.webkit.WebSettings;
85 import android.webkit.WebStorage;
86 import android.webkit.WebView;
87 import android.webkit.WebViewClient;
88 import android.webkit.WebViewDatabase;
89 import android.widget.ArrayAdapter;
90 import android.widget.CheckBox;
91 import android.widget.CursorAdapter;
92 import android.widget.EditText;
93 import android.widget.FrameLayout;
94 import android.widget.ImageView;
95 import android.widget.LinearLayout;
96 import android.widget.ListView;
97 import android.widget.ProgressBar;
98 import android.widget.RadioButton;
99 import android.widget.RelativeLayout;
100 import android.widget.TextView;
102 import androidx.activity.OnBackPressedCallback;
103 import androidx.activity.result.ActivityResultCallback;
104 import androidx.activity.result.ActivityResultLauncher;
105 import androidx.activity.result.contract.ActivityResultContracts;
106 import androidx.annotation.NonNull;
107 import androidx.appcompat.app.ActionBar;
108 import androidx.appcompat.app.ActionBarDrawerToggle;
109 import androidx.appcompat.app.AppCompatActivity;
110 import androidx.appcompat.app.AppCompatDelegate;
111 import androidx.appcompat.widget.Toolbar;
112 import androidx.coordinatorlayout.widget.CoordinatorLayout;
113 import androidx.core.content.res.ResourcesCompat;
114 import androidx.core.view.GravityCompat;
115 import androidx.drawerlayout.widget.DrawerLayout;
116 import androidx.fragment.app.DialogFragment;
117 import androidx.fragment.app.Fragment;
118 import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
119 import androidx.viewpager.widget.ViewPager;
120 import androidx.webkit.WebSettingsCompat;
121 import androidx.webkit.WebViewFeature;
123 import com.google.android.material.appbar.AppBarLayout;
124 import com.google.android.material.floatingactionbutton.FloatingActionButton;
125 import com.google.android.material.navigation.NavigationView;
126 import com.google.android.material.snackbar.Snackbar;
127 import com.google.android.material.tabs.TabLayout;
129 import com.stoutner.privacybrowser.R;
130 import com.stoutner.privacybrowser.adapters.WebViewPagerAdapter;
131 import com.stoutner.privacybrowser.asynctasks.GetHostIpAddresses;
132 import com.stoutner.privacybrowser.asynctasks.PopulateBlocklists;
133 import com.stoutner.privacybrowser.asynctasks.PrepareSaveDialog;
134 import com.stoutner.privacybrowser.asynctasks.SaveUrl;
135 import com.stoutner.privacybrowser.asynctasks.SaveWebpageImage;
136 import com.stoutner.privacybrowser.dataclasses.PendingDialog;
137 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
138 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
139 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
140 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
141 import com.stoutner.privacybrowser.dialogs.FontSizeDialog;
142 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
143 import com.stoutner.privacybrowser.dialogs.OpenDialog;
144 import com.stoutner.privacybrowser.dialogs.ProxyNotInstalledDialog;
145 import com.stoutner.privacybrowser.dialogs.PinnedMismatchDialog;
146 import com.stoutner.privacybrowser.dialogs.SaveDialog;
147 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
148 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
149 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
150 import com.stoutner.privacybrowser.dialogs.WaitingForProxyDialog;
151 import com.stoutner.privacybrowser.fragments.WebViewTabFragment;
152 import com.stoutner.privacybrowser.helpers.BlocklistHelper;
153 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
154 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
155 import com.stoutner.privacybrowser.helpers.ProxyHelper;
156 import com.stoutner.privacybrowser.helpers.SanitizeUrlHelper;
157 import com.stoutner.privacybrowser.views.NestedScrollWebView;
159 import java.io.ByteArrayInputStream;
160 import java.io.ByteArrayOutputStream;
162 import java.io.FileInputStream;
163 import java.io.FileOutputStream;
164 import java.io.IOException;
165 import java.io.InputStream;
166 import java.io.OutputStream;
167 import java.io.UnsupportedEncodingException;
169 import java.net.MalformedURLException;
171 import java.net.URLDecoder;
172 import java.net.URLEncoder;
174 import java.text.NumberFormat;
176 import java.util.ArrayList;
177 import java.util.Date;
178 import java.util.HashSet;
179 import java.util.List;
180 import java.util.Objects;
181 import java.util.Set;
182 import java.util.concurrent.ExecutorService;
183 import java.util.concurrent.Executors;
187 public class MainWebViewActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener,
188 EditBookmarkFolderDialog.EditBookmarkFolderListener, FontSizeDialog.UpdateFontSizeListener, NavigationView.OnNavigationItemSelectedListener, OpenDialog.OpenListener,
189 PinnedMismatchDialog.PinnedMismatchListener, PopulateBlocklists.PopulateBlocklistsListener, SaveDialog.SaveListener, UrlHistoryDialog.NavigateHistoryListener,
190 WebViewTabFragment.NewTabListener {
192 // Define the public static variables.
193 public static ExecutorService executorService = Executors.newFixedThreadPool(4);
194 public static String orbotStatus = "unknown";
195 public static ArrayList<PendingDialog> pendingDialogsArrayList = new ArrayList<>();
196 public static String proxyMode = ProxyHelper.NONE;
198 // Declare the public static variables.
199 public static String currentBookmarksFolder = "";
200 public static boolean restartFromBookmarksActivity;
201 public static WebViewPagerAdapter webViewPagerAdapter;
203 // Declare the public static views.
204 public static AppBarLayout appBarLayout;
206 // The user agent constants are public static so they can be accessed from `SettingsFragment`, `DomainsActivity`, and `DomainSettingsFragment`.
207 public final static int UNRECOGNIZED_USER_AGENT = -1;
208 public final static int SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1;
209 public final static int SETTINGS_CUSTOM_USER_AGENT = 11;
210 public final static int DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0;
211 public final static int DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2;
212 public final static int DOMAINS_CUSTOM_USER_AGENT = 12;
214 // Define the start activity for result request codes. The public static entry is accessed from `OpenDialog()`.
215 private final int BROWSE_FILE_UPLOAD_REQUEST_CODE = 0;
216 public final static int BROWSE_OPEN_REQUEST_CODE = 1;
218 // Define the saved instance state constants.
219 private final String SAVED_STATE_ARRAY_LIST = "saved_state_array_list";
220 private final String SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST = "saved_nested_scroll_webview_state_array_list";
221 private final String SAVED_TAB_POSITION = "saved_tab_position";
222 private final String PROXY_MODE = "proxy_mode";
224 // Define the saved instance state variables.
225 private ArrayList<Bundle> savedStateArrayList;
226 private ArrayList<Bundle> savedNestedScrollWebViewStateArrayList;
227 private int savedTabPosition;
228 private String savedProxyMode;
230 // Define the class variables.
231 @SuppressWarnings("rawtypes")
232 AsyncTask populateBlocklists;
234 // The current WebView is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
235 // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, `applyProxy()`, and `applyDomainSettings()`.
236 private NestedScrollWebView currentWebView;
238 // The search URL is set in `applyAppSettings()` and used in `onNewIntent()`, `loadUrlFromTextBox()`, `initializeApp()`, and `initializeWebView()`.
239 private String searchURL;
241 // The blocklists are populated in `finishedPopulatingBlocklists()` and accessed from `initializeWebView()`.
242 private ArrayList<List<String[]>> easyList;
243 private ArrayList<List<String[]>> easyPrivacy;
244 private ArrayList<List<String[]>> fanboysAnnoyanceList;
245 private ArrayList<List<String[]>> fanboysSocialList;
246 private ArrayList<List<String[]>> ultraList;
247 private ArrayList<List<String[]>> ultraPrivacy;
249 // The action bar drawer toggle is initialized in `onCreate()` and used in `onResume()`.
250 private ActionBarDrawerToggle actionBarDrawerToggle;
252 // The color spans are used in `onCreate()` and `highlightUrlText()`.
253 private ForegroundColorSpan redColorSpan;
254 private ForegroundColorSpan initialGrayColorSpan;
255 private ForegroundColorSpan finalGrayColorSpan;
257 // `bookmarksCursor` is used in `onDestroy()`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
258 private Cursor bookmarksCursor;
260 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
261 private CursorAdapter bookmarksCursorAdapter;
263 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
264 private String oldFolderNameString;
266 // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
267 private ValueCallback<Uri[]> fileChooserCallback;
269 // The default progress view offsets are set in `onCreate()` and used in `initializeWebView()`.
270 private int appBarHeight;
271 private int defaultProgressViewStartOffset;
272 private int defaultProgressViewEndOffset;
274 // Declare the helpers.
275 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
276 private DomainsDatabaseHelper domainsDatabaseHelper;
277 private ProxyHelper proxyHelper;
278 private SanitizeUrlHelper sanitizeUrlHelper;
280 // Declare the class variables
281 private boolean bottomAppBar;
282 private boolean displayAdditionalAppBarIcons;
283 private boolean displayingFullScreenVideo;
284 private boolean downloadWithExternalApp;
285 private boolean fullScreenBrowsingModeEnabled;
286 private boolean hideAppBar;
287 private boolean incognitoModeEnabled;
288 private boolean inFullScreenBrowsingMode;
289 private boolean loadingNewIntent;
290 private BroadcastReceiver orbotStatusBroadcastReceiver;
291 private boolean reapplyAppSettingsOnRestart;
292 private boolean reapplyDomainSettingsOnRestart;
293 private boolean sanitizeAmpRedirects;
294 private boolean sanitizeTrackingQueries;
295 private boolean scrollAppBar;
296 private boolean waitingForProxy;
297 private String webViewDefaultUserAgent;
299 // Define the class variables.
300 private ObjectAnimator objectAnimator = new ObjectAnimator();
301 private String saveUrlString = "";
303 // Declare the class views.
304 private FrameLayout rootFrameLayout;
305 private DrawerLayout drawerLayout;
306 private CoordinatorLayout coordinatorLayout;
307 private Toolbar toolbar;
308 private RelativeLayout urlRelativeLayout;
309 private EditText urlEditText;
310 private ActionBar actionBar;
311 private LinearLayout findOnPageLinearLayout;
312 private LinearLayout tabsLinearLayout;
313 private TabLayout tabLayout;
314 private SwipeRefreshLayout swipeRefreshLayout;
315 private ViewPager webViewPager;
316 private FrameLayout fullScreenVideoFrameLayout;
318 // Declare the class menus.
319 private Menu optionsMenu;
321 // Declare the class menu items.
322 private MenuItem navigationBackMenuItem;
323 private MenuItem navigationForwardMenuItem;
324 private MenuItem navigationHistoryMenuItem;
325 private MenuItem navigationRequestsMenuItem;
326 private MenuItem optionsPrivacyMenuItem;
327 private MenuItem optionsRefreshMenuItem;
328 private MenuItem optionsCookiesMenuItem;
329 private MenuItem optionsDomStorageMenuItem;
330 private MenuItem optionsSaveFormDataMenuItem;
331 private MenuItem optionsClearDataMenuItem;
332 private MenuItem optionsClearCookiesMenuItem;
333 private MenuItem optionsClearDomStorageMenuItem;
334 private MenuItem optionsClearFormDataMenuItem;
335 private MenuItem optionsBlocklistsMenuItem;
336 private MenuItem optionsEasyListMenuItem;
337 private MenuItem optionsEasyPrivacyMenuItem;
338 private MenuItem optionsFanboysAnnoyanceListMenuItem;
339 private MenuItem optionsFanboysSocialBlockingListMenuItem;
340 private MenuItem optionsUltraListMenuItem;
341 private MenuItem optionsUltraPrivacyMenuItem;
342 private MenuItem optionsBlockAllThirdPartyRequestsMenuItem;
343 private MenuItem optionsProxyMenuItem;
344 private MenuItem optionsProxyNoneMenuItem;
345 private MenuItem optionsProxyTorMenuItem;
346 private MenuItem optionsProxyI2pMenuItem;
347 private MenuItem optionsProxyCustomMenuItem;
348 private MenuItem optionsUserAgentMenuItem;
349 private MenuItem optionsUserAgentPrivacyBrowserMenuItem;
350 private MenuItem optionsUserAgentWebViewDefaultMenuItem;
351 private MenuItem optionsUserAgentFirefoxOnAndroidMenuItem;
352 private MenuItem optionsUserAgentChromeOnAndroidMenuItem;
353 private MenuItem optionsUserAgentSafariOnIosMenuItem;
354 private MenuItem optionsUserAgentFirefoxOnLinuxMenuItem;
355 private MenuItem optionsUserAgentChromiumOnLinuxMenuItem;
356 private MenuItem optionsUserAgentFirefoxOnWindowsMenuItem;
357 private MenuItem optionsUserAgentChromeOnWindowsMenuItem;
358 private MenuItem optionsUserAgentEdgeOnWindowsMenuItem;
359 private MenuItem optionsUserAgentInternetExplorerOnWindowsMenuItem;
360 private MenuItem optionsUserAgentSafariOnMacosMenuItem;
361 private MenuItem optionsUserAgentCustomMenuItem;
362 private MenuItem optionsSwipeToRefreshMenuItem;
363 private MenuItem optionsWideViewportMenuItem;
364 private MenuItem optionsDisplayImagesMenuItem;
365 private MenuItem optionsDarkWebViewMenuItem;
366 private MenuItem optionsFontSizeMenuItem;
367 private MenuItem optionsAddOrEditDomainMenuItem;
369 // This variable won't be needed once the class is migrated to Kotlin, as can be seen in LogcatActivity or AboutVersionFragment.
370 private Activity resultLauncherActivityHandle;
372 // Define the save URL activity result launcher. It must be defined before `onCreate()` is run or the app will crash.
373 private final ActivityResultLauncher<String> saveUrlActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.CreateDocument("*/*"),
374 new ActivityResultCallback<Uri>() {
376 public void onActivityResult(Uri fileUri) {
377 // Only save the URL if the file URI is not null, which happens if the user exited the file picker by pressing back.
378 if (fileUri != null) {
379 new SaveUrl(getApplicationContext(), resultLauncherActivityHandle, fileUri, currentWebView.getSettings().getUserAgentString(), currentWebView.getAcceptCookies()).execute(saveUrlString);
382 // Reset the save URL string.
387 // Define the save webpage archive activity result launcher. It must be defined before `onCreate()` is run or the app will crash.
388 private final ActivityResultLauncher<String> saveWebpageArchiveActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.CreateDocument("multipart/related"),
389 new ActivityResultCallback<Uri>() {
391 public void onActivityResult(Uri fileUri) {
392 // Only save the webpage archive if the file URI is not null, which happens if the user exited the file picker by pressing back.
393 if (fileUri != null) {
395 // Create a temporary MHT file.
396 File temporaryMhtFile = File.createTempFile("temporary_mht_file", ".mht", getCacheDir());
398 // Save the temporary MHT file.
399 currentWebView.saveWebArchive(temporaryMhtFile.toString(), false, callbackValue -> {
400 if (callbackValue != null) { // The temporary MHT file was saved successfully.
402 // Create a temporary MHT file input stream.
403 FileInputStream temporaryMhtFileInputStream = new FileInputStream(temporaryMhtFile);
405 // Get an output stream for the save webpage file path.
406 OutputStream mhtOutputStream = getContentResolver().openOutputStream(fileUri);
408 // Create a transfer byte array.
409 byte[] transferByteArray = new byte[1024];
411 // Create an integer to track the number of bytes read.
414 // Copy the temporary MHT file input stream to the MHT output stream.
415 while ((bytesRead = temporaryMhtFileInputStream.read(transferByteArray)) > 0) {
416 mhtOutputStream.write(transferByteArray, 0, bytesRead);
419 // Close the streams.
420 mhtOutputStream.close();
421 temporaryMhtFileInputStream.close();
423 // Initialize the file name string from the file URI last path segment.
424 String fileNameString = fileUri.getLastPathSegment();
426 // Query the exact file name if the API >= 26.
427 if (Build.VERSION.SDK_INT >= 26) {
428 // Get a cursor from the content resolver.
429 Cursor contentResolverCursor = resultLauncherActivityHandle.getContentResolver().query(fileUri, null, null, null);
431 // Move to the fist row.
432 contentResolverCursor.moveToFirst();
434 // Get the file name from the cursor.
435 fileNameString = contentResolverCursor.getString(contentResolverCursor.getColumnIndexOrThrow(OpenableColumns.DISPLAY_NAME));
438 contentResolverCursor.close();
441 // Display a snackbar.
442 Snackbar.make(currentWebView, getString(R.string.file_saved) + " " + fileNameString, Snackbar.LENGTH_SHORT).show();
443 } catch (Exception exception) {
444 // Display a snackbar with the exception.
445 Snackbar.make(currentWebView, getString(R.string.error_saving_file) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
447 // Delete the temporary MHT file.
448 //noinspection ResultOfMethodCallIgnored
449 temporaryMhtFile.delete();
451 } else { // There was an unspecified error while saving the temporary MHT file.
452 // Display an error snackbar.
453 Snackbar.make(currentWebView, getString(R.string.error_saving_file), Snackbar.LENGTH_INDEFINITE).show();
456 } catch (IOException ioException) {
457 // Display a snackbar with the IO exception.
458 Snackbar.make(currentWebView, getString(R.string.error_saving_file) + " " + ioException, Snackbar.LENGTH_INDEFINITE).show();
464 // Define the save webpage image activity result launcher. It must be defined before `onCreate()` is run or the app will crash.
465 private final ActivityResultLauncher<String> saveWebpageImageActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.CreateDocument("image/png"),
466 new ActivityResultCallback<Uri>() {
468 public void onActivityResult(Uri fileUri) {
469 // Only save the webpage image if the file URI is not null, which happens if the user exited the file picker by pressing back.
470 if (fileUri != null) {
471 // Save the webpage image.
472 new SaveWebpageImage(resultLauncherActivityHandle, fileUri, currentWebView).execute();
477 // Remove the warning about needing to override `performClick()` when using an `OnTouchListener` with WebView.
478 @SuppressLint("ClickableViewAccessibility")
480 protected void onCreate(Bundle savedInstanceState) {
481 // Run the default commands.
482 super.onCreate(savedInstanceState);
484 // Populate the result launcher activity. This will no longer be needed once the activity has transitioned to Kotlin.
485 resultLauncherActivityHandle = this;
487 // Check to see if the activity has been restarted.
488 if (savedInstanceState != null) {
489 // Store the saved instance state variables.
490 savedStateArrayList = savedInstanceState.getParcelableArrayList(SAVED_STATE_ARRAY_LIST);
491 savedNestedScrollWebViewStateArrayList = savedInstanceState.getParcelableArrayList(SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST);
492 savedTabPosition = savedInstanceState.getInt(SAVED_TAB_POSITION);
493 savedProxyMode = savedInstanceState.getString(PROXY_MODE);
496 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
497 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
499 // Get a handle for the shared preferences.
500 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
502 // Get the preferences.
503 String appTheme = sharedPreferences.getString(getString(R.string.app_theme_key), getString(R.string.app_theme_default_value));
504 boolean allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false);
505 bottomAppBar = sharedPreferences.getBoolean(getString(R.string.bottom_app_bar_key), false);
506 displayAdditionalAppBarIcons = sharedPreferences.getBoolean(getString(R.string.display_additional_app_bar_icons_key), false);
508 // Get the theme entry values string array.
509 String[] appThemeEntryValuesStringArray = getResources().getStringArray(R.array.app_theme_entry_values);
511 // Set the app theme according to the preference. A switch statement cannot be used because the theme entry values string array is not a compile time constant.
512 if (appTheme.equals(appThemeEntryValuesStringArray[1])) { // The light theme is selected.
513 // Apply the light theme.
514 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
515 } else if (appTheme.equals(appThemeEntryValuesStringArray[2])) { // The dark theme is selected.
516 // Apply the dark theme.
517 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
518 } else { // The system default theme is selected.
519 if (Build.VERSION.SDK_INT >= 28) { // The system default theme is supported.
520 // Follow the system default theme.
521 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
522 } else { // The system default theme is not supported.
523 // Follow the battery saver mode.
524 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY);
528 // Disable screenshots if not allowed.
529 if (!allowScreenshots) {
530 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
533 // Enable the drawing of the entire webpage. This makes it possible to save a website image. This must be done before anything else happens with the WebView.
534 WebView.enableSlowWholeDocumentDraw();
536 // Set the content view according to the position of the app bar.
537 if (bottomAppBar) setContentView(R.layout.main_framelayout_bottom_appbar);
538 else setContentView(R.layout.main_framelayout_top_appbar);
540 // Get handles for the views.
541 rootFrameLayout = findViewById(R.id.root_framelayout);
542 drawerLayout = findViewById(R.id.drawerlayout);
543 coordinatorLayout = findViewById(R.id.coordinatorlayout);
544 appBarLayout = findViewById(R.id.appbar_layout);
545 toolbar = findViewById(R.id.toolbar);
546 findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
547 tabsLinearLayout = findViewById(R.id.tabs_linearlayout);
548 tabLayout = findViewById(R.id.tablayout);
549 swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
550 webViewPager = findViewById(R.id.webviewpager);
551 NavigationView navigationView = findViewById(R.id.navigationview);
552 fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
554 // Get a handle for the navigation menu.
555 Menu navigationMenu = navigationView.getMenu();
557 // Get handles for the navigation menu items.
558 navigationBackMenuItem = navigationMenu.findItem(R.id.back);
559 navigationForwardMenuItem = navigationMenu.findItem(R.id.forward);
560 navigationHistoryMenuItem = navigationMenu.findItem(R.id.history);
561 navigationRequestsMenuItem = navigationMenu.findItem(R.id.requests);
563 // Listen for touches on the navigation menu.
564 navigationView.setNavigationItemSelectedListener(this);
566 // Get a handle for the app compat delegate.
567 AppCompatDelegate appCompatDelegate = getDelegate();
569 // Set the support action bar.
570 appCompatDelegate.setSupportActionBar(toolbar);
572 // Get a handle for the action bar.
573 actionBar = appCompatDelegate.getSupportActionBar();
575 // Remove the incorrect lint warning below that the action bar might be null.
576 assert actionBar != null;
578 // Add the custom layout, which shows the URL text bar.
579 actionBar.setCustomView(R.layout.url_app_bar);
580 actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
582 // Get handles for the views in the URL app bar.
583 urlRelativeLayout = findViewById(R.id.url_relativelayout);
584 urlEditText = findViewById(R.id.url_edittext);
586 // Create the hamburger icon at the start of the AppBar.
587 actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
589 // Initially disable the sliding drawers. They will be enabled once the blocklists are loaded.
590 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
592 // Initialize the web view pager adapter.
593 webViewPagerAdapter = new WebViewPagerAdapter(getSupportFragmentManager());
595 // Set the pager adapter on the web view pager.
596 webViewPager.setAdapter(webViewPagerAdapter);
598 // Store up to 100 tabs in memory.
599 webViewPager.setOffscreenPageLimit(100);
601 // Instantiate the helpers.
602 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this);
603 domainsDatabaseHelper = new DomainsDatabaseHelper(this);
604 proxyHelper = new ProxyHelper();
605 sanitizeUrlHelper = new SanitizeUrlHelper();
607 // Initialize the app.
610 // Apply the app settings from the shared preferences.
613 // Control what the system back command does.
614 OnBackPressedCallback onBackPressedCallback = new OnBackPressedCallback(true) {
616 public void handleOnBackPressed() {
617 // Process the different back options.
618 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
619 // Close the navigation drawer.
620 drawerLayout.closeDrawer(GravityCompat.START);
621 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
622 // close the bookmarks drawer.
623 drawerLayout.closeDrawer(GravityCompat.END);
624 } else if (displayingFullScreenVideo) { // A full screen video is shown.
625 // Exit the full screen video.
626 exitFullScreenVideo();
627 } else if (currentWebView.canGoBack()) { // There is at least one item in the current WebView history.
628 // Get the current web back forward list.
629 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
631 // Get the previous entry URL.
632 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
634 // Apply the domain settings.
635 applyDomainSettings(currentWebView, previousUrl, false, false, false);
638 currentWebView.goBack();
639 } else if (tabLayout.getTabCount() > 1) { // There are at least two tabs.
640 // Close the current tab.
642 } else { // There isn't anything to do in Privacy Browser.
643 // Close Privacy Browser. `finishAndRemoveTask()` also removes Privacy Browser from the recent app list.
644 finishAndRemoveTask();
646 // Manually kill Privacy Browser. Otherwise, it is glitchy when restarted.
652 // Register the on back pressed callback.
653 getOnBackPressedDispatcher().addCallback(this, onBackPressedCallback);
655 // Populate the blocklists.
656 populateBlocklists = new PopulateBlocklists(this, this).execute();
660 protected void onNewIntent(Intent intent) {
661 // Run the default commands.
662 super.onNewIntent(intent);
664 // Check to see if the app is being restarted from a saved state.
665 if (savedStateArrayList == null || savedStateArrayList.size() == 0) { // The activity is not being restarted from a saved state.
666 // Get the information from the intent.
667 String intentAction = intent.getAction();
668 Uri intentUriData = intent.getData();
669 String intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT);
671 // Determine if this is a web search.
672 boolean isWebSearch = ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH));
674 // 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.
675 if (intentUriData != null || intentStringExtra != null || isWebSearch) {
676 // Exit the full screen video if it is displayed.
677 if (displayingFullScreenVideo) {
678 // Exit full screen video mode.
679 exitFullScreenVideo();
681 // Reload the current WebView. Otherwise, it can display entirely black.
682 currentWebView.reload();
685 // Get the shared preferences.
686 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
688 // Create a URL string.
691 // If the intent action is a web search, perform the search.
692 if (isWebSearch) { // The intent is a web search.
693 // Create an encoded URL string.
694 String encodedUrlString;
696 // Sanitize the search input and convert it to a search.
698 encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
699 } catch (UnsupportedEncodingException exception) {
700 encodedUrlString = "";
703 // Add the base search URL.
704 url = searchURL + encodedUrlString;
705 } else if (intentUriData != null) { // The intent contains a URL formatted as a URI.
706 // Set the intent data as the URL.
707 url = intentUriData.toString();
708 } else { // The intent contains a string, which might be a URL.
709 // Set the intent string as the URL.
710 url = intentStringExtra;
713 // Add a new tab if specified in the preferences.
714 if (sharedPreferences.getBoolean(getString(R.string.open_intents_in_new_tab_key), true)) { // Load the URL in a new tab.
715 // Set the loading new intent flag.
716 loadingNewIntent = true;
719 addNewTab(url, true);
720 } else { // Load the URL in the current tab.
722 loadUrl(currentWebView, url);
725 // Close the navigation drawer if it is open.
726 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
727 drawerLayout.closeDrawer(GravityCompat.START);
730 // Close the bookmarks drawer if it is open.
731 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
732 drawerLayout.closeDrawer(GravityCompat.END);
735 } else { // The app has been restarted.
736 // Replace the intent that started the app with this one. This will load the tab after the others have been restored.
742 public void onRestart() {
743 // Run the default commands.
746 // Apply the app settings if returning from the Settings activity.
747 if (reapplyAppSettingsOnRestart) {
748 // Reset the reapply app settings on restart tracker.
749 reapplyAppSettingsOnRestart = false;
751 // Apply the app settings.
755 // Apply the domain settings if returning from the settings or domains activity.
756 if (reapplyDomainSettingsOnRestart) {
757 // Reset the reapply domain settings on restart tracker.
758 reapplyDomainSettingsOnRestart = false;
760 // Reapply the domain settings for each tab.
761 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
762 // Get the WebView tab fragment.
763 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
765 // Get the fragment view.
766 View fragmentView = webViewTabFragment.getView();
768 // Only reload the WebViews if they exist.
769 if (fragmentView != null) {
770 // Get the nested scroll WebView from the tab fragment.
771 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
773 // Reset the current domain name so the domain settings will be reapplied.
774 nestedScrollWebView.setCurrentDomainName("");
776 // Reapply the domain settings if the URL is not null, which can happen if an empty tab is active when returning from settings.
777 if (nestedScrollWebView.getUrl() != null) {
778 applyDomainSettings(nestedScrollWebView, nestedScrollWebView.getUrl(), false, true, false);
784 // Update the bookmarks drawer if returning from the Bookmarks activity.
785 if (restartFromBookmarksActivity) {
786 // Close the bookmarks drawer.
787 drawerLayout.closeDrawer(GravityCompat.END);
789 // Reload the bookmarks drawer.
790 loadBookmarksFolder();
792 // Reset `restartFromBookmarksActivity`.
793 restartFromBookmarksActivity = false;
796 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
797 updatePrivacyIcons(true);
800 // `onStart()` runs after `onCreate()` or `onRestart()`. This is used instead of `onResume()` so the commands aren't called every time the screen is partially hidden.
802 public void onStart() {
803 // Run the default commands.
806 // Resume any WebViews.
807 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
808 // Get the WebView tab fragment.
809 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
811 // Get the fragment view.
812 View fragmentView = webViewTabFragment.getView();
814 // Only resume the WebViews if they exist (they won't when the app is first created).
815 if (fragmentView != null) {
816 // Get the nested scroll WebView from the tab fragment.
817 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
819 // Resume the nested scroll WebView.
820 nestedScrollWebView.onResume();
824 // Resume the nested scroll WebView JavaScript timers. This is a global command that resumes JavaScript timers on all WebViews.
825 if (currentWebView != null) {
826 currentWebView.resumeTimers();
829 // Reapply the proxy settings if the system is using a proxy. This redisplays the appropriate alert dialog.
830 if (!proxyMode.equals(ProxyHelper.NONE)) {
834 // Reapply any system UI flags.
835 if (displayingFullScreenVideo || inFullScreenBrowsingMode) { // The system is displaying a website or a video in full screen mode.
836 /* Hide the system bars.
837 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
838 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
839 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
840 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
842 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
843 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
846 // Show any pending dialogs.
847 for (int i = 0; i < pendingDialogsArrayList.size(); i++) {
848 // Get the pending dialog from the array list.
849 PendingDialog pendingDialog = pendingDialogsArrayList.get(i);
851 // Show the pending dialog.
852 pendingDialog.dialogFragment.show(getSupportFragmentManager(), pendingDialog.tag);
855 // Clear the pending dialogs array list.
856 pendingDialogsArrayList.clear();
859 // `onStop()` runs after `onPause()`. It is used instead of `onPause()` so the commands are not called every time the screen is partially hidden.
861 public void onStop() {
862 // Run the default commands.
865 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
866 // Get the WebView tab fragment.
867 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
869 // Get the fragment view.
870 View fragmentView = webViewTabFragment.getView();
872 // Only pause the WebViews if they exist (they won't when the app is first created).
873 if (fragmentView != null) {
874 // Get the nested scroll WebView from the tab fragment.
875 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
877 // Pause the nested scroll WebView.
878 nestedScrollWebView.onPause();
882 // Pause the WebView JavaScript timers. This is a global command that pauses JavaScript on all WebViews.
883 if (currentWebView != null) {
884 currentWebView.pauseTimers();
889 public void onSaveInstanceState(@NonNull Bundle savedInstanceState) {
890 // Run the default commands.
891 super.onSaveInstanceState(savedInstanceState);
893 // Create the saved state array lists.
894 ArrayList<Bundle> savedStateArrayList = new ArrayList<>();
895 ArrayList<Bundle> savedNestedScrollWebViewStateArrayList = new ArrayList<>();
897 // Get the URLs from each tab.
898 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
899 // Get the WebView tab fragment.
900 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
902 // Get the fragment view.
903 View fragmentView = webViewTabFragment.getView();
905 if (fragmentView != null) {
906 // Get the nested scroll WebView from the tab fragment.
907 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
909 // Create saved state bundle.
910 Bundle savedStateBundle = new Bundle();
912 // Get the current states.
913 nestedScrollWebView.saveState(savedStateBundle);
914 Bundle savedNestedScrollWebViewStateBundle = nestedScrollWebView.saveNestedScrollWebViewState();
916 // Store the saved states in the array lists.
917 savedStateArrayList.add(savedStateBundle);
918 savedNestedScrollWebViewStateArrayList.add(savedNestedScrollWebViewStateBundle);
922 // Get the current tab position.
923 int currentTabPosition = tabLayout.getSelectedTabPosition();
925 // Store the saved states in the bundle.
926 savedInstanceState.putParcelableArrayList(SAVED_STATE_ARRAY_LIST, savedStateArrayList);
927 savedInstanceState.putParcelableArrayList(SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST, savedNestedScrollWebViewStateArrayList);
928 savedInstanceState.putInt(SAVED_TAB_POSITION, currentTabPosition);
929 savedInstanceState.putString(PROXY_MODE, proxyMode);
933 public void onDestroy() {
934 // Unregister the orbot status broadcast receiver if it exists.
935 if (orbotStatusBroadcastReceiver != null) {
936 this.unregisterReceiver(orbotStatusBroadcastReceiver);
939 // Close the bookmarks cursor if it exists.
940 if (bookmarksCursor != null) {
941 bookmarksCursor.close();
944 // Close the bookmarks database if it exists.
945 if (bookmarksDatabaseHelper != null) {
946 bookmarksDatabaseHelper.close();
949 // Stop populating the blocklists if the AsyncTask is running in the background.
950 if (populateBlocklists != null) {
951 populateBlocklists.cancel(true);
954 // Run the default commands.
959 public boolean onCreateOptionsMenu(Menu menu) {
960 // Inflate the menu. This adds items to the action bar if it is present.
961 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
963 // Store a handle for the options menu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons()`.
966 // Get handles for the menu items.
967 optionsPrivacyMenuItem = menu.findItem(R.id.javascript);
968 optionsRefreshMenuItem = menu.findItem(R.id.refresh);
969 MenuItem bookmarksMenuItem = menu.findItem(R.id.bookmarks);
970 optionsCookiesMenuItem = menu.findItem(R.id.cookies);
971 optionsDomStorageMenuItem = menu.findItem(R.id.dom_storage);
972 optionsSaveFormDataMenuItem = menu.findItem(R.id.save_form_data); // Form data can be removed once the minimum API >= 26.
973 optionsClearDataMenuItem = menu.findItem(R.id.clear_data);
974 optionsClearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
975 optionsClearDomStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
976 optionsClearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
977 optionsBlocklistsMenuItem = menu.findItem(R.id.blocklists);
978 optionsEasyListMenuItem = menu.findItem(R.id.easylist);
979 optionsEasyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
980 optionsFanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
981 optionsFanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
982 optionsUltraListMenuItem = menu.findItem(R.id.ultralist);
983 optionsUltraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
984 optionsBlockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
985 optionsProxyMenuItem = menu.findItem(R.id.proxy);
986 optionsProxyNoneMenuItem = menu.findItem(R.id.proxy_none);
987 optionsProxyTorMenuItem = menu.findItem(R.id.proxy_tor);
988 optionsProxyI2pMenuItem = menu.findItem(R.id.proxy_i2p);
989 optionsProxyCustomMenuItem = menu.findItem(R.id.proxy_custom);
990 optionsUserAgentMenuItem = menu.findItem(R.id.user_agent);
991 optionsUserAgentPrivacyBrowserMenuItem = menu.findItem(R.id.user_agent_privacy_browser);
992 optionsUserAgentWebViewDefaultMenuItem = menu.findItem(R.id.user_agent_webview_default);
993 optionsUserAgentFirefoxOnAndroidMenuItem = menu.findItem(R.id.user_agent_firefox_on_android);
994 optionsUserAgentChromeOnAndroidMenuItem = menu.findItem(R.id.user_agent_chrome_on_android);
995 optionsUserAgentSafariOnIosMenuItem = menu.findItem(R.id.user_agent_safari_on_ios);
996 optionsUserAgentFirefoxOnLinuxMenuItem = menu.findItem(R.id.user_agent_firefox_on_linux);
997 optionsUserAgentChromiumOnLinuxMenuItem = menu.findItem(R.id.user_agent_chromium_on_linux);
998 optionsUserAgentFirefoxOnWindowsMenuItem = menu.findItem(R.id.user_agent_firefox_on_windows);
999 optionsUserAgentChromeOnWindowsMenuItem = menu.findItem(R.id.user_agent_chrome_on_windows);
1000 optionsUserAgentEdgeOnWindowsMenuItem = menu.findItem(R.id.user_agent_edge_on_windows);
1001 optionsUserAgentInternetExplorerOnWindowsMenuItem = menu.findItem(R.id.user_agent_internet_explorer_on_windows);
1002 optionsUserAgentSafariOnMacosMenuItem = menu.findItem(R.id.user_agent_safari_on_macos);
1003 optionsUserAgentCustomMenuItem = menu.findItem(R.id.user_agent_custom);
1004 optionsSwipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
1005 optionsWideViewportMenuItem = menu.findItem(R.id.wide_viewport);
1006 optionsDisplayImagesMenuItem = menu.findItem(R.id.display_images);
1007 optionsDarkWebViewMenuItem = menu.findItem(R.id.dark_webview);
1008 optionsFontSizeMenuItem = menu.findItem(R.id.font_size);
1009 optionsAddOrEditDomainMenuItem = menu.findItem(R.id.add_or_edit_domain);
1011 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1012 updatePrivacyIcons(false);
1014 // Only display the form data menu items if the API < 26.
1015 optionsSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1016 optionsClearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1018 // Disable the clear form data menu item if the API >= 26 so that the status of the main Clear Data is calculated correctly.
1019 optionsClearFormDataMenuItem.setEnabled(Build.VERSION.SDK_INT < 26);
1021 // 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.
1022 if (displayAdditionalAppBarIcons) {
1023 optionsRefreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
1024 bookmarksMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1025 optionsCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1026 } else { //Do not display the additional icons.
1027 optionsRefreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1028 bookmarksMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1029 optionsCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1032 // Replace Refresh with Stop if a URL is already loading.
1033 if (currentWebView != null && currentWebView.getProgress() != 100) {
1035 optionsRefreshMenuItem.setTitle(R.string.stop);
1037 // Set the icon if it is displayed in the app bar. Once the minimum API is >= 26, the blue and black icons can be combined with a tint list.
1038 if (displayAdditionalAppBarIcons) {
1039 optionsRefreshMenuItem.setIcon(R.drawable.close_blue);
1048 public boolean onPrepareOptionsMenu(Menu menu) {
1049 // Get a handle for the cookie manager.
1050 CookieManager cookieManager = CookieManager.getInstance();
1052 // Initialize the current user agent string and the font size.
1053 String currentUserAgent = getString(R.string.user_agent_privacy_browser);
1056 // 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.
1057 if (currentWebView != null) {
1058 // Set the add or edit domain text.
1059 if (currentWebView.getDomainSettingsApplied()) {
1060 optionsAddOrEditDomainMenuItem.setTitle(R.string.edit_domain_settings);
1062 optionsAddOrEditDomainMenuItem.setTitle(R.string.add_domain_settings);
1065 // Get the current user agent from the WebView.
1066 currentUserAgent = currentWebView.getSettings().getUserAgentString();
1068 // Get the current font size from the
1069 fontSize = currentWebView.getSettings().getTextZoom();
1071 // Set the status of the menu item checkboxes.
1072 optionsDomStorageMenuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1073 optionsSaveFormDataMenuItem.setChecked(currentWebView.getSettings().getSaveFormData()); // Form data can be removed once the minimum API >= 26.
1074 optionsEasyListMenuItem.setChecked(currentWebView.getEasyListEnabled());
1075 optionsEasyPrivacyMenuItem.setChecked(currentWebView.getEasyPrivacyEnabled());
1076 optionsFanboysAnnoyanceListMenuItem.setChecked(currentWebView.getFanboysAnnoyanceListEnabled());
1077 optionsFanboysSocialBlockingListMenuItem.setChecked(currentWebView.getFanboysSocialBlockingListEnabled());
1078 optionsUltraListMenuItem.setChecked(currentWebView.getUltraListEnabled());
1079 optionsUltraPrivacyMenuItem.setChecked(currentWebView.getUltraPrivacyEnabled());
1080 optionsBlockAllThirdPartyRequestsMenuItem.setChecked(currentWebView.getBlockAllThirdPartyRequests());
1081 optionsSwipeToRefreshMenuItem.setChecked(currentWebView.getSwipeToRefresh());
1082 optionsWideViewportMenuItem.setChecked(currentWebView.getSettings().getUseWideViewPort());
1083 optionsDisplayImagesMenuItem.setChecked(currentWebView.getSettings().getLoadsImagesAutomatically());
1085 // Initialize the display names for the blocklists with the number of blocked requests.
1086 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
1087 optionsEasyListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASYLIST) + " - " + getString(R.string.easylist));
1088 optionsEasyPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASYPRIVACY) + " - " + getString(R.string.easyprivacy));
1089 optionsFanboysAnnoyanceListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " + getString(R.string.fanboys_annoyance_list));
1090 optionsFanboysSocialBlockingListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " + getString(R.string.fanboys_social_blocking_list));
1091 optionsUltraListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRALIST) + " - " + getString(R.string.ultralist));
1092 optionsUltraPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRAPRIVACY) + " - " + getString(R.string.ultraprivacy));
1093 optionsBlockAllThirdPartyRequestsMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " + getString(R.string.block_all_third_party_requests));
1095 // Enable DOM Storage if JavaScript is enabled.
1096 optionsDomStorageMenuItem.setEnabled(currentWebView.getSettings().getJavaScriptEnabled());
1098 // Get the current theme status.
1099 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
1101 // Enable dark WebView if the API is < 33 or if night mode is enabled.
1102 optionsDarkWebViewMenuItem.setEnabled((Build.VERSION.SDK_INT < 33) || (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES));
1104 // Set the checkbox status for dark WebView if the WebView supports it.
1105 if ((Build.VERSION.SDK_INT >= 33) && WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) { // The device is running API >= 33 and algorithmic darkening is supported.
1106 optionsDarkWebViewMenuItem.setChecked(WebSettingsCompat.isAlgorithmicDarkeningAllowed(currentWebView.getSettings()));
1107 } else if ((Build.VERSION.SDK_INT < 33) && WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) { // The device is running API < 33 and the WebView supports force dark.
1108 //noinspection deprecation
1109 optionsDarkWebViewMenuItem.setChecked(WebSettingsCompat.getForceDark(currentWebView.getSettings()) == WebSettingsCompat.FORCE_DARK_ON);
1113 // Set the cookies menu item checked status.
1114 optionsCookiesMenuItem.setChecked(cookieManager.acceptCookie());
1116 // Enable Clear Cookies if there are any.
1117 optionsClearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1119 // 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`.
1120 String privateDataDirectoryString = getApplicationInfo().dataDir;
1122 // Get a count of the number of files in the Local Storage directory.
1123 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1124 int localStorageDirectoryNumberOfFiles = 0;
1125 if (localStorageDirectory.exists()) {
1126 // `Objects.requireNonNull` removes a lint warning that `localStorageDirectory.list` might produce a null pointed exception if it is dereferenced.
1127 localStorageDirectoryNumberOfFiles = Objects.requireNonNull(localStorageDirectory.list()).length;
1130 // Get a count of the number of files in the IndexedDB directory.
1131 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1132 int indexedDBDirectoryNumberOfFiles = 0;
1133 if (indexedDBDirectory.exists()) {
1134 // `Objects.requireNonNull` removes a lint warning that `indexedDBDirectory.list` might produce a null pointed exception if it is dereferenced.
1135 indexedDBDirectoryNumberOfFiles = Objects.requireNonNull(indexedDBDirectory.list()).length;
1138 // Enable Clear DOM Storage if there is any.
1139 optionsClearDomStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1141 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
1142 if (Build.VERSION.SDK_INT < 26) {
1143 // Get the WebView database.
1144 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1146 // Enable the clear form data menu item if there is anything to clear.
1147 optionsClearFormDataMenuItem.setEnabled(webViewDatabase.hasFormData());
1150 // Enable Clear Data if any of the submenu items are enabled.
1151 optionsClearDataMenuItem.setEnabled(optionsClearCookiesMenuItem.isEnabled() || optionsClearDomStorageMenuItem.isEnabled() || optionsClearFormDataMenuItem.isEnabled());
1153 // Disable Fanboy's Social Blocking List menu item if Fanboy's Annoyance List is checked.
1154 optionsFanboysSocialBlockingListMenuItem.setEnabled(!optionsFanboysAnnoyanceListMenuItem.isChecked());
1156 // Set the proxy title and check the applied proxy.
1157 switch (proxyMode) {
1158 case ProxyHelper.NONE:
1159 // Set the proxy title.
1160 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_none));
1162 // Check the proxy None radio button.
1163 optionsProxyNoneMenuItem.setChecked(true);
1166 case ProxyHelper.TOR:
1167 // Set the proxy title.
1168 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_tor));
1170 // Check the proxy Tor radio button.
1171 optionsProxyTorMenuItem.setChecked(true);
1174 case ProxyHelper.I2P:
1175 // Set the proxy title.
1176 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_i2p));
1178 // Check the proxy I2P radio button.
1179 optionsProxyI2pMenuItem.setChecked(true);
1182 case ProxyHelper.CUSTOM:
1183 // Set the proxy title.
1184 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_custom));
1186 // Check the proxy Custom radio button.
1187 optionsProxyCustomMenuItem.setChecked(true);
1191 // Select the current user agent menu item. A switch statement cannot be used because the user agents are not compile time constants.
1192 if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) { // Privacy Browser.
1193 // Update the user agent menu item title.
1194 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_privacy_browser));
1196 // Select the Privacy Browser radio box.
1197 optionsUserAgentPrivacyBrowserMenuItem.setChecked(true);
1198 } else if (currentUserAgent.equals(webViewDefaultUserAgent)) { // WebView Default.
1199 // Update the user agent menu item title.
1200 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_webview_default));
1202 // Select the WebView Default radio box.
1203 optionsUserAgentWebViewDefaultMenuItem.setChecked(true);
1204 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) { // Firefox on Android.
1205 // Update the user agent menu item title.
1206 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_android));
1208 // Select the Firefox on Android radio box.
1209 optionsUserAgentFirefoxOnAndroidMenuItem.setChecked(true);
1210 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) { // Chrome on Android.
1211 // Update the user agent menu item title.
1212 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_android));
1214 // Select the Chrome on Android radio box.
1215 optionsUserAgentChromeOnAndroidMenuItem.setChecked(true);
1216 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) { // Safari on iOS.
1217 // Update the user agent menu item title.
1218 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_ios));
1220 // Select the Safari on iOS radio box.
1221 optionsUserAgentSafariOnIosMenuItem.setChecked(true);
1222 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) { // Firefox on Linux.
1223 // Update the user agent menu item title.
1224 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_linux));
1226 // Select the Firefox on Linux radio box.
1227 optionsUserAgentFirefoxOnLinuxMenuItem.setChecked(true);
1228 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) { // Chromium on Linux.
1229 // Update the user agent menu item title.
1230 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chromium_on_linux));
1232 // Select the Chromium on Linux radio box.
1233 optionsUserAgentChromiumOnLinuxMenuItem.setChecked(true);
1234 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) { // Firefox on Windows.
1235 // Update the user agent menu item title.
1236 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_windows));
1238 // Select the Firefox on Windows radio box.
1239 optionsUserAgentFirefoxOnWindowsMenuItem.setChecked(true);
1240 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) { // Chrome on Windows.
1241 // Update the user agent menu item title.
1242 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_windows));
1244 // Select the Chrome on Windows radio box.
1245 optionsUserAgentChromeOnWindowsMenuItem.setChecked(true);
1246 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) { // Edge on Windows.
1247 // Update the user agent menu item title.
1248 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_edge_on_windows));
1250 // Select the Edge on Windows radio box.
1251 optionsUserAgentEdgeOnWindowsMenuItem.setChecked(true);
1252 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) { // Internet Explorer on Windows.
1253 // Update the user agent menu item title.
1254 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_internet_explorer_on_windows));
1256 // Select the Internet on Windows radio box.
1257 optionsUserAgentInternetExplorerOnWindowsMenuItem.setChecked(true);
1258 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) { // Safari on macOS.
1259 // Update the user agent menu item title.
1260 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_macos));
1262 // Select the Safari on macOS radio box.
1263 optionsUserAgentSafariOnMacosMenuItem.setChecked(true);
1264 } else { // Custom user agent.
1265 // Update the user agent menu item title.
1266 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_custom));
1268 // Select the Custom radio box.
1269 optionsUserAgentCustomMenuItem.setChecked(true);
1272 // Set the font size title.
1273 optionsFontSizeMenuItem.setTitle(getString(R.string.font_size) + " - " + fontSize + "%");
1275 // Run all the other default commands.
1276 super.onPrepareOptionsMenu(menu);
1278 // Display the menu.
1283 public boolean onOptionsItemSelected(MenuItem menuItem) {
1284 // Get a handle for the shared preferences.
1285 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1287 // Get a handle for the cookie manager.
1288 CookieManager cookieManager = CookieManager.getInstance();
1290 // Get the selected menu item ID.
1291 int menuItemId = menuItem.getItemId();
1293 // Run the commands that correlate to the selected menu item.
1294 if (menuItemId == R.id.javascript) { // JavaScript.
1295 // Toggle the JavaScript status.
1296 currentWebView.getSettings().setJavaScriptEnabled(!currentWebView.getSettings().getJavaScriptEnabled());
1298 // Update the privacy icon.
1299 updatePrivacyIcons(true);
1301 // Display a `Snackbar`.
1302 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScrip is enabled.
1303 Snackbar.make(webViewPager, R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1304 } else if (cookieManager.acceptCookie()) { // JavaScript is disabled, but first-party cookies are enabled.
1305 Snackbar.make(webViewPager, R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1306 } else { // Privacy mode.
1307 Snackbar.make(webViewPager, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1310 // Reload the current WebView.
1311 currentWebView.reload();
1313 // Consume the event.
1315 } else if (menuItemId == R.id.refresh) { // Refresh.
1316 // Run the command that correlates to the current status of the menu item.
1317 if (menuItem.getTitle().equals(getString(R.string.refresh))) { // The refresh button was pushed.
1318 // Reload the current WebView.
1319 currentWebView.reload();
1320 } else { // The stop button was pushed.
1321 // Stop the loading of the WebView.
1322 currentWebView.stopLoading();
1325 // Consume the event.
1327 } else if (menuItemId == R.id.bookmarks) { // Bookmarks.
1328 // Open the bookmarks drawer.
1329 drawerLayout.openDrawer(GravityCompat.END);
1331 // Consume the event.
1333 } else if (menuItemId == R.id.cookies) { // Cookies.
1334 // Switch the first-party cookie status.
1335 cookieManager.setAcceptCookie(!cookieManager.acceptCookie());
1337 // Store the cookie status.
1338 currentWebView.setAcceptCookies(cookieManager.acceptCookie());
1340 // Update the menu checkbox.
1341 menuItem.setChecked(cookieManager.acceptCookie());
1343 // Update the privacy icon.
1344 updatePrivacyIcons(true);
1346 // Display a snackbar.
1347 if (cookieManager.acceptCookie()) { // Cookies are enabled.
1348 Snackbar.make(webViewPager, R.string.cookies_enabled, Snackbar.LENGTH_SHORT).show();
1349 } else if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is still enabled.
1350 Snackbar.make(webViewPager, R.string.cookies_disabled, Snackbar.LENGTH_SHORT).show();
1351 } else { // Privacy mode.
1352 Snackbar.make(webViewPager, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1355 // Reload the current WebView.
1356 currentWebView.reload();
1358 // Consume the event.
1360 } else if (menuItemId == R.id.dom_storage) { // DOM storage.
1361 // Toggle the status of domStorageEnabled.
1362 currentWebView.getSettings().setDomStorageEnabled(!currentWebView.getSettings().getDomStorageEnabled());
1364 // Update the menu checkbox.
1365 menuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1367 // Update the privacy icon.
1368 updatePrivacyIcons(true);
1370 // Display a snackbar.
1371 if (currentWebView.getSettings().getDomStorageEnabled()) {
1372 Snackbar.make(webViewPager, R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1374 Snackbar.make(webViewPager, R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1377 // Reload the current WebView.
1378 currentWebView.reload();
1380 // Consume the event.
1382 } else if (menuItemId == R.id.save_form_data) { // Form data. This can be removed once the minimum API >= 26.
1383 // Switch the status of saveFormDataEnabled.
1384 currentWebView.getSettings().setSaveFormData(!currentWebView.getSettings().getSaveFormData());
1386 // Update the menu checkbox.
1387 menuItem.setChecked(currentWebView.getSettings().getSaveFormData());
1389 // Display a snackbar.
1390 if (currentWebView.getSettings().getSaveFormData()) {
1391 Snackbar.make(webViewPager, R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1393 Snackbar.make(webViewPager, R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1396 // Update the privacy icon.
1397 updatePrivacyIcons(true);
1399 // Reload the current WebView.
1400 currentWebView.reload();
1402 // Consume the event.
1404 } else if (menuItemId == R.id.clear_cookies) { // Clear cookies.
1405 // Create a snackbar.
1406 Snackbar.make(webViewPager, R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1407 .setAction(R.string.undo, v -> {
1408 // Do nothing because everything will be handled by `onDismissed()` below.
1410 .addCallback(new Snackbar.Callback() {
1412 public void onDismissed(Snackbar snackbar, int event) {
1413 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1414 // Delete the cookies.
1415 cookieManager.removeAllCookies(null);
1421 // Consume the event.
1423 } else if (menuItemId == R.id.clear_dom_storage) { // Clear DOM storage.
1424 // Create a snackbar.
1425 Snackbar.make(webViewPager, R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1426 .setAction(R.string.undo, v -> {
1427 // Do nothing because everything will be handled by `onDismissed()` below.
1429 .addCallback(new Snackbar.Callback() {
1431 public void onDismissed(Snackbar snackbar, int event) {
1432 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1433 // Delete the DOM Storage.
1434 WebStorage webStorage = WebStorage.getInstance();
1435 webStorage.deleteAllData();
1437 // Initialize a handler to manually delete the DOM storage files and directories.
1438 Handler deleteDomStorageHandler = new Handler();
1440 // Setup a runnable to manually delete the DOM storage files and directories.
1441 Runnable deleteDomStorageRunnable = () -> {
1443 // Get a handle for the runtime.
1444 Runtime runtime = Runtime.getRuntime();
1446 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
1447 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
1448 String privateDataDirectoryString = getApplicationInfo().dataDir;
1450 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1451 Process deleteLocalStorageProcess = runtime.exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1453 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1454 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1455 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1456 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1457 Process deleteDatabasesProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1459 // Wait for the processes to finish.
1460 deleteLocalStorageProcess.waitFor();
1461 deleteIndexProcess.waitFor();
1462 deleteQuotaManagerProcess.waitFor();
1463 deleteQuotaManagerJournalProcess.waitFor();
1464 deleteDatabasesProcess.waitFor();
1465 } catch (Exception exception) {
1466 // Do nothing if an error is thrown.
1470 // Manually delete the DOM storage files after 200 milliseconds.
1471 deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200);
1477 // Consume the event.
1479 } else if (menuItemId == R.id.clear_form_data) { // Clear form data. This can be remove once the minimum API >= 26.
1480 // Create a snackbar.
1481 Snackbar.make(webViewPager, R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1482 .setAction(R.string.undo, v -> {
1483 // Do nothing because everything will be handled by `onDismissed()` below.
1485 .addCallback(new Snackbar.Callback() {
1487 public void onDismissed(Snackbar snackbar, int event) {
1488 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1489 // Get a handle for the webView database.
1490 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1492 // Delete the form data.
1493 webViewDatabase.clearFormData();
1499 // Consume the event.
1501 } else if (menuItemId == R.id.easylist) { // EasyList.
1502 // Toggle the EasyList status.
1503 currentWebView.setEasyListEnabled(!currentWebView.getEasyListEnabled());
1505 // Update the menu checkbox.
1506 menuItem.setChecked(currentWebView.getEasyListEnabled());
1508 // Reload the current WebView.
1509 currentWebView.reload();
1511 // Consume the event.
1513 } else if (menuItemId == R.id.easyprivacy) { // EasyPrivacy.
1514 // Toggle the EasyPrivacy status.
1515 currentWebView.setEasyPrivacyEnabled(!currentWebView.getEasyPrivacyEnabled());
1517 // Update the menu checkbox.
1518 menuItem.setChecked(currentWebView.getEasyPrivacyEnabled());
1520 // Reload the current WebView.
1521 currentWebView.reload();
1523 // Consume the event.
1525 } else if (menuItemId == R.id.fanboys_annoyance_list) { // Fanboy's Annoyance List.
1526 // Toggle Fanboy's Annoyance List status.
1527 currentWebView.setFanboysAnnoyanceListEnabled(!currentWebView.getFanboysAnnoyanceListEnabled());
1529 // Update the menu checkbox.
1530 menuItem.setChecked(currentWebView.getFanboysAnnoyanceListEnabled());
1532 // Update the status of Fanboy's Social Blocking List.
1533 optionsFanboysSocialBlockingListMenuItem.setEnabled(!currentWebView.getFanboysAnnoyanceListEnabled());
1535 // Reload the current WebView.
1536 currentWebView.reload();
1538 // Consume the event.
1540 } else if (menuItemId == R.id.fanboys_social_blocking_list) { // Fanboy's Social Blocking List.
1541 // Toggle Fanboy's Social Blocking List status.
1542 currentWebView.setFanboysSocialBlockingListEnabled(!currentWebView.getFanboysSocialBlockingListEnabled());
1544 // Update the menu checkbox.
1545 menuItem.setChecked(currentWebView.getFanboysSocialBlockingListEnabled());
1547 // Reload the current WebView.
1548 currentWebView.reload();
1550 // Consume the event.
1552 } else if (menuItemId == R.id.ultralist) { // UltraList.
1553 // Toggle the UltraList status.
1554 currentWebView.setUltraListEnabled(!currentWebView.getUltraListEnabled());
1556 // Update the menu checkbox.
1557 menuItem.setChecked(currentWebView.getUltraListEnabled());
1559 // Reload the current WebView.
1560 currentWebView.reload();
1562 // Consume the event.
1564 } else if (menuItemId == R.id.ultraprivacy) { // UltraPrivacy.
1565 // Toggle the UltraPrivacy status.
1566 currentWebView.setUltraPrivacyEnabled(!currentWebView.getUltraPrivacyEnabled());
1568 // Update the menu checkbox.
1569 menuItem.setChecked(currentWebView.getUltraPrivacyEnabled());
1571 // Reload the current WebView.
1572 currentWebView.reload();
1574 // Consume the event.
1576 } else if (menuItemId == R.id.block_all_third_party_requests) { // Block all third-party requests.
1577 //Toggle the third-party requests blocker status.
1578 currentWebView.setBlockAllThirdPartyRequests(!currentWebView.getBlockAllThirdPartyRequests());
1580 // Update the menu checkbox.
1581 menuItem.setChecked(currentWebView.getBlockAllThirdPartyRequests());
1583 // Reload the current WebView.
1584 currentWebView.reload();
1586 // Consume the event.
1588 } else if (menuItemId == R.id.proxy_none) { // Proxy - None.
1589 // Update the proxy mode.
1590 proxyMode = ProxyHelper.NONE;
1592 // Apply the proxy mode.
1595 // Consume the event.
1597 } else if (menuItemId == R.id.proxy_tor) { // Proxy - Tor.
1598 // Update the proxy mode.
1599 proxyMode = ProxyHelper.TOR;
1601 // Apply the proxy mode.
1604 // Consume the event.
1606 } else if (menuItemId == R.id.proxy_i2p) { // Proxy - I2P.
1607 // Update the proxy mode.
1608 proxyMode = ProxyHelper.I2P;
1610 // Apply the proxy mode.
1613 // Consume the event.
1615 } else if (menuItemId == R.id.proxy_custom) { // Proxy - Custom.
1616 // Update the proxy mode.
1617 proxyMode = ProxyHelper.CUSTOM;
1619 // Apply the proxy mode.
1622 // Consume the event.
1624 } else if (menuItemId == R.id.user_agent_privacy_browser) { // User Agent - Privacy Browser.
1625 // Update the user agent.
1626 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
1628 // Reload the current WebView.
1629 currentWebView.reload();
1631 // Consume the event.
1633 } else if (menuItemId == R.id.user_agent_webview_default) { // User Agent - WebView Default.
1634 // Update the user agent.
1635 currentWebView.getSettings().setUserAgentString("");
1637 // Reload the current WebView.
1638 currentWebView.reload();
1640 // Consume the event.
1642 } else if (menuItemId == R.id.user_agent_firefox_on_android) { // User Agent - Firefox on Android.
1643 // Update the user agent.
1644 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
1646 // Reload the current WebView.
1647 currentWebView.reload();
1649 // Consume the event.
1651 } else if (menuItemId == R.id.user_agent_chrome_on_android) { // User Agent - Chrome on Android.
1652 // Update the user agent.
1653 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
1655 // Reload the current WebView.
1656 currentWebView.reload();
1658 // Consume the event.
1660 } else if (menuItemId == R.id.user_agent_safari_on_ios) { // User Agent - Safari on iOS.
1661 // Update the user agent.
1662 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
1664 // Reload the current WebView.
1665 currentWebView.reload();
1667 // Consume the event.
1669 } else if (menuItemId == R.id.user_agent_firefox_on_linux) { // User Agent - Firefox on Linux.
1670 // Update the user agent.
1671 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
1673 // Reload the current WebView.
1674 currentWebView.reload();
1676 // Consume the event.
1678 } else if (menuItemId == R.id.user_agent_chromium_on_linux) { // User Agent - Chromium on Linux.
1679 // Update the user agent.
1680 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
1682 // Reload the current WebView.
1683 currentWebView.reload();
1685 // Consume the event.
1687 } else if (menuItemId == R.id.user_agent_firefox_on_windows) { // User Agent - Firefox on Windows.
1688 // Update the user agent.
1689 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
1691 // Reload the current WebView.
1692 currentWebView.reload();
1694 // Consume the event.
1696 } else if (menuItemId == R.id.user_agent_chrome_on_windows) { // User Agent - Chrome on Windows.
1697 // Update the user agent.
1698 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
1700 // Reload the current WebView.
1701 currentWebView.reload();
1703 // Consume the event.
1705 } else if (menuItemId == R.id.user_agent_edge_on_windows) { // User Agent - Edge on Windows.
1706 // Update the user agent.
1707 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
1709 // Reload the current WebView.
1710 currentWebView.reload();
1712 // Consume the event.
1714 } else if (menuItemId == R.id.user_agent_internet_explorer_on_windows) { // User Agent - Internet Explorer on Windows.
1715 // Update the user agent.
1716 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
1718 // Reload the current WebView.
1719 currentWebView.reload();
1721 // Consume the event.
1723 } else if (menuItemId == R.id.user_agent_safari_on_macos) { // User Agent - Safari on macOS.
1724 // Update the user agent.
1725 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
1727 // Reload the current WebView.
1728 currentWebView.reload();
1730 // Consume the event.
1732 } else if (menuItemId == R.id.user_agent_custom) { // User Agent - Custom.
1733 // Update the user agent.
1734 currentWebView.getSettings().setUserAgentString(sharedPreferences.getString(getString(R.string.custom_user_agent_key), getString(R.string.custom_user_agent_default_value)));
1736 // Reload the current WebView.
1737 currentWebView.reload();
1739 // Consume the event.
1741 } else if (menuItemId == R.id.font_size) { // Font size.
1742 // Instantiate the font size dialog.
1743 DialogFragment fontSizeDialogFragment = FontSizeDialog.displayDialog(currentWebView.getSettings().getTextZoom());
1745 // Show the font size dialog.
1746 fontSizeDialogFragment.show(getSupportFragmentManager(), getString(R.string.font_size));
1748 // Consume the event.
1750 } else if (menuItemId == R.id.swipe_to_refresh) { // Swipe to refresh.
1751 // Toggle the stored status of swipe to refresh.
1752 currentWebView.setSwipeToRefresh(!currentWebView.getSwipeToRefresh());
1754 // Update the swipe refresh layout.
1755 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
1756 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
1757 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
1758 } else { // Swipe to refresh is disabled.
1759 // Disable the swipe refresh layout.
1760 swipeRefreshLayout.setEnabled(false);
1763 // Consume the event.
1765 } else if (menuItemId == R.id.wide_viewport) { // Wide viewport.
1766 // Toggle the viewport.
1767 currentWebView.getSettings().setUseWideViewPort(!currentWebView.getSettings().getUseWideViewPort());
1769 // Consume the event.
1771 } else if (menuItemId == R.id.display_images) { // Display images.
1772 // Toggle the displaying of images.
1773 if (currentWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1774 // Disable loading of images.
1775 currentWebView.getSettings().setLoadsImagesAutomatically(false);
1777 // Reload the website to remove existing images.
1778 currentWebView.reload();
1779 } else { // Images are not currently loaded automatically.
1780 // Enable loading of images. Missing images will be loaded without the need for a reload.
1781 currentWebView.getSettings().setLoadsImagesAutomatically(true);
1784 // Consume the event.
1786 } else if (menuItemId == R.id.dark_webview) { // Dark WebView.
1787 // Check to see if dark WebView is supported by this WebView.
1788 if ((Build.VERSION.SDK_INT >= 33) && WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) { // The device is running API >= 33 and algorithmic darkening is supported.
1789 // Toggle algorithmic darkening.
1790 WebSettingsCompat.setAlgorithmicDarkeningAllowed(currentWebView.getSettings(), !WebSettingsCompat.isAlgorithmicDarkeningAllowed(currentWebView.getSettings()));
1791 } else if ((Build.VERSION.SDK_INT < 33) && WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) { // The device is running API < 33 and the WebView supports force dark.
1792 // Toggle the dark WebView setting.
1793 //noinspection deprecation
1794 if (WebSettingsCompat.getForceDark(currentWebView.getSettings()) == WebSettingsCompat.FORCE_DARK_ON) { // Dark WebView is currently enabled.
1795 // Turn off dark WebView.
1796 //noinspection deprecation
1797 WebSettingsCompat.setForceDark(currentWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
1798 } else { // Dark WebView is currently disabled.
1799 // Turn on dark WebView.
1800 //noinspection deprecation
1801 WebSettingsCompat.setForceDark(currentWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
1805 // Consume the event.
1807 } else if (menuItemId == R.id.find_on_page) { // Find on page.
1808 // Get a handle for the views.
1809 Toolbar toolbar = findViewById(R.id.toolbar);
1810 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
1811 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
1813 // Set the minimum height of the find on page linear layout to match the toolbar.
1814 findOnPageLinearLayout.setMinimumHeight(toolbar.getHeight());
1816 // Hide the toolbar.
1817 toolbar.setVisibility(View.GONE);
1819 // Show the find on page linear layout.
1820 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1822 // Display the keyboard. The app must wait 200 ms before running the command to work around a bug in Android.
1823 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1824 findOnPageEditText.postDelayed(() -> {
1825 // Set the focus on the find on page edit text.
1826 findOnPageEditText.requestFocus();
1828 // Get a handle for the input method manager.
1829 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1831 // Remove the lint warning below that the input method manager might be null.
1832 assert inputMethodManager != null;
1834 // Display the keyboard. `0` sets no input flags.
1835 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1838 // Consume the event.
1840 } else if (menuItemId == R.id.print) { // Print.
1841 // Get a print manager instance.
1842 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1844 // Remove the lint error below that print manager might be null.
1845 assert printManager != null;
1847 // Create a print document adapter from the current WebView.
1848 PrintDocumentAdapter printDocumentAdapter = currentWebView.createPrintDocumentAdapter(getString(R.string.print));
1850 // Print the document.
1851 printManager.print(getString(R.string.privacy_browser_webpage), printDocumentAdapter, null);
1853 // Consume the event.
1855 } else if (menuItemId == R.id.save_url) { // Save URL.
1856 // Check the download preference.
1857 if (downloadWithExternalApp) { // Download with an external app.
1858 downloadUrlWithExternalApp(currentWebView.getCurrentUrl());
1859 } else { // Handle the download inside of Privacy Browser.
1860 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
1861 new PrepareSaveDialog(this, this, getSupportFragmentManager(), currentWebView.getSettings().getUserAgentString(),
1862 currentWebView.getAcceptCookies()).execute(currentWebView.getCurrentUrl());
1865 // Consume the event.
1867 } else if (menuItemId == R.id.save_archive) {
1868 // Open the file picker with a default file name built from the current domain name.
1869 saveWebpageArchiveActivityResultLauncher.launch(currentWebView.getCurrentDomainName() + ".mht");
1871 // Consume the event.
1873 } else if (menuItemId == R.id.save_image) { // Save image.
1874 // Open the file picker with a default file name built from the current domain name.
1875 saveWebpageImageActivityResultLauncher.launch(currentWebView.getCurrentDomainName() + ".png");
1877 // Consume the event.
1879 } else if (menuItemId == R.id.add_to_homescreen) { // Add to homescreen.
1880 // Instantiate the create home screen shortcut dialog.
1881 DialogFragment createHomeScreenShortcutDialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView.getTitle(), currentWebView.getUrl(),
1882 currentWebView.getFavoriteOrDefaultIcon());
1884 // Show the create home screen shortcut dialog.
1885 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
1887 // Consume the event.
1889 } else if (menuItemId == R.id.view_source) { // View source.
1890 // Create an intent to launch the view source activity.
1891 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
1893 // Add the variables to the intent.
1894 viewSourceIntent.putExtra(ViewSourceActivityKt.CURRENT_URL, currentWebView.getUrl());
1895 viewSourceIntent.putExtra(ViewSourceActivityKt.USER_AGENT, currentWebView.getSettings().getUserAgentString());
1898 startActivity(viewSourceIntent);
1900 // Consume the event.
1902 } else if (menuItemId == R.id.share_message) { // Share a message.
1903 // Prepare the share string.
1904 String shareString = currentWebView.getTitle() + " – " + currentWebView.getUrl();
1906 // Create the share intent.
1907 Intent shareMessageIntent = new Intent(Intent.ACTION_SEND);
1909 // Add the share string to the intent.
1910 shareMessageIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1912 // Set the MIME type.
1913 shareMessageIntent.setType("text/plain");
1915 // Set the intent to open in a new task.
1916 shareMessageIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1919 startActivity(Intent.createChooser(shareMessageIntent, getString(R.string.share_message)));
1921 // Consume the event.
1923 } else if (menuItemId == R.id.share_url) { // Share URL.
1924 // Create the share intent.
1925 Intent shareUrlIntent = new Intent(Intent.ACTION_SEND);
1927 // Add the URL to the intent.
1928 shareUrlIntent.putExtra(Intent.EXTRA_TEXT, currentWebView.getUrl());
1930 // Add the title to the intent.
1931 shareUrlIntent.putExtra(Intent.EXTRA_SUBJECT, currentWebView.getTitle());
1933 // Set the MIME type.
1934 shareUrlIntent.setType("text/plain");
1936 // Set the intent to open in a new task.
1937 shareUrlIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1940 startActivity(Intent.createChooser(shareUrlIntent, getString(R.string.share_url)));
1942 // Consume the event.
1944 } else if (menuItemId == R.id.open_with_app) { // Open with app.
1945 // Open the URL with an outside app.
1946 openWithApp(currentWebView.getUrl());
1948 // Consume the event.
1950 } else if (menuItemId == R.id.open_with_browser) { // Open with browser.
1951 // Open the URL with an outside browser.
1952 openWithBrowser(currentWebView.getUrl());
1954 // Consume the event.
1956 } else if (menuItemId == R.id.add_or_edit_domain) { // Add or edit domain.
1957 // Reapply the domain settings on returning to `MainWebViewActivity`.
1958 reapplyDomainSettingsOnRestart = true;
1960 // Check if domain settings currently exist.
1961 if (currentWebView.getDomainSettingsApplied()) { // Edit the current domain settings.
1962 // Create an intent to launch the domains activity.
1963 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1965 // Add the extra information to the intent.
1966 domainsIntent.putExtra(DomainsActivity.LOAD_DOMAIN, currentWebView.getDomainSettingsDatabaseId());
1967 domainsIntent.putExtra(DomainsActivity.CLOSE_ON_BACK, true);
1968 domainsIntent.putExtra(DomainsActivity.CURRENT_URL, currentWebView.getUrl());
1969 domainsIntent.putExtra(DomainsActivity.CURRENT_IP_ADDRESSES, currentWebView.getCurrentIpAddresses());
1971 // Get the current certificate.
1972 SslCertificate sslCertificate = currentWebView.getCertificate();
1974 // Check to see if the SSL certificate is populated.
1975 if (sslCertificate != null) {
1976 // Extract the certificate to strings.
1977 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1978 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1979 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1980 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1981 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1982 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1983 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1984 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1986 // Add the certificate to the intent.
1987 domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_TO_CNAME, issuedToCName);
1988 domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_TO_ONAME, issuedToOName);
1989 domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_TO_UNAME, issuedToUName);
1990 domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_BY_CNAME, issuedByCName);
1991 domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_BY_ONAME, issuedByOName);
1992 domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_BY_UNAME, issuedByUName);
1993 domainsIntent.putExtra(DomainsActivity.SSL_START_DATE, startDateLong);
1994 domainsIntent.putExtra(DomainsActivity.SSL_END_DATE, endDateLong);
1998 startActivity(domainsIntent);
1999 } else { // Add a new domain.
2000 // Get the current URI.
2001 Uri currentUri = Uri.parse(currentWebView.getUrl());
2003 // Get the current domain from the URI.
2004 String currentDomain = currentUri.getHost();
2006 // Set an empty domain if it is null.
2007 if (currentDomain == null)
2010 // Create the domain and store the database ID.
2011 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
2013 // Create an intent to launch the domains activity.
2014 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2016 // Add the extra information to the intent.
2017 domainsIntent.putExtra(DomainsActivity.LOAD_DOMAIN, newDomainDatabaseId);
2018 domainsIntent.putExtra(DomainsActivity.CLOSE_ON_BACK, true);
2019 domainsIntent.putExtra(DomainsActivity.CURRENT_URL, currentWebView.getUrl());
2020 domainsIntent.putExtra(DomainsActivity.CURRENT_IP_ADDRESSES, currentWebView.getCurrentIpAddresses());
2022 // Get the current certificate.
2023 SslCertificate sslCertificate = currentWebView.getCertificate();
2025 // Check to see if the SSL certificate is populated.
2026 if (sslCertificate != null) {
2027 // Extract the certificate to strings.
2028 String issuedToCName = sslCertificate.getIssuedTo().getCName();
2029 String issuedToOName = sslCertificate.getIssuedTo().getOName();
2030 String issuedToUName = sslCertificate.getIssuedTo().getUName();
2031 String issuedByCName = sslCertificate.getIssuedBy().getCName();
2032 String issuedByOName = sslCertificate.getIssuedBy().getOName();
2033 String issuedByUName = sslCertificate.getIssuedBy().getUName();
2034 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
2035 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
2037 // Add the certificate to the intent.
2038 domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_TO_CNAME, issuedToCName);
2039 domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_TO_ONAME, issuedToOName);
2040 domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_TO_UNAME, issuedToUName);
2041 domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_BY_CNAME, issuedByCName);
2042 domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_BY_ONAME, issuedByOName);
2043 domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_BY_UNAME, issuedByUName);
2044 domainsIntent.putExtra(DomainsActivity.SSL_START_DATE, startDateLong);
2045 domainsIntent.putExtra(DomainsActivity.SSL_END_DATE, endDateLong);
2049 startActivity(domainsIntent);
2052 // Consume the event.
2054 } else { // There is no match with the options menu. Pass the event up to the parent method.
2055 // Don't consume the event.
2056 return super.onOptionsItemSelected(menuItem);
2060 // removeAllCookies is deprecated, but it is required for API < 21.
2062 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2063 // Get a handle for the shared preferences.
2064 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2066 // Get the menu item ID.
2067 int menuItemId = menuItem.getItemId();
2069 // Run the commands that correspond to the selected menu item.
2070 if (menuItemId == R.id.clear_and_exit) { // Clear and exit.
2071 // Clear and exit Privacy Browser.
2073 } else if (menuItemId == R.id.home) { // Home.
2074 // Load the homepage.
2075 loadUrl(currentWebView, sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
2076 } else if (menuItemId == R.id.back) { // Back.
2077 // Check if the WebView can go back.
2078 if (currentWebView.canGoBack()) {
2079 // Get the current web back forward list.
2080 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
2082 // Get the previous entry URL.
2083 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
2085 // Apply the domain settings.
2086 applyDomainSettings(currentWebView, previousUrl, false, false, false);
2088 // Load the previous website in the history.
2089 currentWebView.goBack();
2091 } else if (menuItemId == R.id.forward) { // Forward.
2092 // Check if the WebView can go forward.
2093 if (currentWebView.canGoForward()) {
2094 // Get the current web back forward list.
2095 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
2097 // Get the next entry URL.
2098 String nextUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() + 1).getUrl();
2100 // Apply the domain settings.
2101 applyDomainSettings(currentWebView, nextUrl, false, false, false);
2103 // Load the next website in the history.
2104 currentWebView.goForward();
2106 } else if (menuItemId == R.id.history) { // History.
2107 // Instantiate the URL history dialog.
2108 DialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(currentWebView.getWebViewFragmentId());
2110 // Show the URL history dialog.
2111 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2112 } else if (menuItemId == R.id.open) { // Open.
2113 // Instantiate the open file dialog.
2114 DialogFragment openDialogFragment = new OpenDialog();
2116 // Show the open file dialog.
2117 openDialogFragment.show(getSupportFragmentManager(), getString(R.string.open));
2118 } else if (menuItemId == R.id.requests) { // Requests.
2119 // Populate the resource requests.
2120 RequestsActivity.resourceRequests = currentWebView.getResourceRequests();
2122 // Create an intent to launch the Requests activity.
2123 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2125 // Add the block third-party requests status to the intent.
2126 requestsIntent.putExtra("block_all_third_party_requests", currentWebView.getBlockAllThirdPartyRequests());
2129 startActivity(requestsIntent);
2130 } else if (menuItemId == R.id.downloads) { // Downloads.
2131 // Try the default system download manager.
2133 // Launch the default system Download Manager.
2134 Intent defaultDownloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2136 // Launch as a new task so that the download manager and Privacy Browser show as separate windows in the recent tasks list.
2137 defaultDownloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2140 startActivity(defaultDownloadManagerIntent);
2141 } catch (Exception defaultDownloadManagerException) {
2142 // Try a generic file manager.
2144 // Create a generic file manager intent.
2145 Intent genericFileManagerIntent = new Intent(Intent.ACTION_VIEW);
2147 // Open the download directory.
2148 genericFileManagerIntent.setDataAndType(Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()), DocumentsContract.Document.MIME_TYPE_DIR);
2150 // Launch as a new task so that the file manager and Privacy Browser show as separate windows in the recent tasks list.
2151 genericFileManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2154 startActivity(genericFileManagerIntent);
2155 } catch (Exception genericFileManagerException) {
2156 // Try an alternate file manager.
2158 // Create an alternate file manager intent.
2159 Intent alternateFileManagerIntent = new Intent(Intent.ACTION_VIEW);
2161 // Open the download directory.
2162 alternateFileManagerIntent.setDataAndType(Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()), "resource/folder");
2164 // Launch as a new task so that the file manager and Privacy Browser show as separate windows in the recent tasks list.
2165 alternateFileManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2167 // Open the alternate file manager.
2168 startActivity(alternateFileManagerIntent);
2169 } catch (Exception alternateFileManagerException) {
2170 // Display a snackbar.
2171 Snackbar.make(currentWebView, R.string.no_file_manager_detected, Snackbar.LENGTH_INDEFINITE).show();
2175 } else if (menuItemId == R.id.domains) { // Domains.
2176 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2177 reapplyDomainSettingsOnRestart = true;
2179 // Launch the domains activity.
2180 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2182 // Add the extra information to the intent.
2183 domainsIntent.putExtra(DomainsActivity.CURRENT_URL, currentWebView.getUrl());
2184 domainsIntent.putExtra(DomainsActivity.CURRENT_IP_ADDRESSES, currentWebView.getCurrentIpAddresses());
2186 // Get the current certificate.
2187 SslCertificate sslCertificate = currentWebView.getCertificate();
2189 // Check to see if the SSL certificate is populated.
2190 if (sslCertificate != null) {
2191 // Extract the certificate to strings.
2192 String issuedToCName = sslCertificate.getIssuedTo().getCName();
2193 String issuedToOName = sslCertificate.getIssuedTo().getOName();
2194 String issuedToUName = sslCertificate.getIssuedTo().getUName();
2195 String issuedByCName = sslCertificate.getIssuedBy().getCName();
2196 String issuedByOName = sslCertificate.getIssuedBy().getOName();
2197 String issuedByUName = sslCertificate.getIssuedBy().getUName();
2198 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
2199 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
2201 // Add the certificate to the intent.
2202 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
2203 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
2204 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
2205 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
2206 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
2207 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
2208 domainsIntent.putExtra("ssl_start_date", startDateLong);
2209 domainsIntent.putExtra("ssl_end_date", endDateLong);
2213 startActivity(domainsIntent);
2214 } else if (menuItemId == R.id.settings) { // Settings.
2215 // Set the flag to reapply app settings on restart when returning from Settings.
2216 reapplyAppSettingsOnRestart = true;
2218 // Set the flag to reapply the domain settings on restart when returning from Settings.
2219 reapplyDomainSettingsOnRestart = true;
2221 // Launch the settings activity.
2222 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2223 startActivity(settingsIntent);
2224 } else if (menuItemId == R.id.import_export) { // Import/Export.
2225 // Create an intent to launch the import/export activity.
2226 Intent importExportIntent = new Intent(this, ImportExportActivity.class);
2229 startActivity(importExportIntent);
2230 } else if (menuItemId == R.id.logcat) { // Logcat.
2231 // Create an intent to launch the logcat activity.
2232 Intent logcatIntent = new Intent(this, LogcatActivity.class);
2235 startActivity(logcatIntent);
2236 } else if (menuItemId == R.id.webview_devtools) { // WebView Dev.
2237 // Create a WebView DevTools intent.
2238 Intent webViewDevToolsIntent = new Intent("com.android.webview.SHOW_DEV_UI");
2240 // Launch as a new task so that the WebView DevTools and Privacy Browser show as a separate windows in the recent tasks list.
2241 webViewDevToolsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2244 startActivity(webViewDevToolsIntent);
2245 } else if (menuItemId == R.id.guide) { // Guide.
2246 // Create an intent to launch the guide activity.
2247 Intent guideIntent = new Intent(this, GuideActivity.class);
2250 startActivity(guideIntent);
2251 } else if (menuItemId == R.id.about) { // About
2252 // Create an intent to launch the about activity.
2253 Intent aboutIntent = new Intent(this, AboutActivity.class);
2255 // Create a string array for the blocklist versions.
2256 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],
2257 ultraList.get(0).get(0)[0], ultraPrivacy.get(0).get(0)[0]};
2259 // Add the blocklist versions to the intent.
2260 aboutIntent.putExtra(AboutActivity.BLOCKLIST_VERSIONS, blocklistVersions);
2263 startActivity(aboutIntent);
2266 // Close the navigation drawer.
2267 drawerLayout.closeDrawer(GravityCompat.START);
2272 public void onPostCreate(Bundle savedInstanceState) {
2273 // Run the default commands.
2274 super.onPostCreate(savedInstanceState);
2276 // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished. This creates the navigation drawer icon.
2277 actionBarDrawerToggle.syncState();
2281 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2282 // Get the hit test result.
2283 final WebView.HitTestResult hitTestResult = currentWebView.getHitTestResult();
2285 // Define the URL strings.
2286 final String imageUrl;
2287 final String linkUrl;
2289 // Get handles for the system managers.
2290 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2292 // Remove the lint errors below that the clipboard manager might be null.
2293 assert clipboardManager != null;
2295 // Process the link according to the type.
2296 switch (hitTestResult.getType()) {
2297 // `SRC_ANCHOR_TYPE` is a link.
2298 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2299 // Get the target URL.
2300 linkUrl = hitTestResult.getExtra();
2302 // Set the target URL as the title of the `ContextMenu`.
2303 menu.setHeaderTitle(linkUrl);
2305 // Add an Open in New Tab entry.
2306 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2307 // Load the link URL in a new tab and move to it.
2308 addNewTab(linkUrl, true);
2310 // Consume the event.
2314 // Add an Open in Background entry.
2315 menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
2316 // Load the link URL in a new tab but do not move to it.
2317 addNewTab(linkUrl, false);
2319 // Consume the event.
2323 // Add an Open with App entry.
2324 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2325 openWithApp(linkUrl);
2327 // Consume the event.
2331 // Add an Open with Browser entry.
2332 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2333 openWithBrowser(linkUrl);
2335 // Consume the event.
2339 // Add a Copy URL entry.
2340 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2341 // Save the link URL in a `ClipData`.
2342 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2344 // Set the `ClipData` as the clipboard's primary clip.
2345 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2347 // Consume the event.
2351 // Add a Save URL entry.
2352 menu.add(R.string.save_url).setOnMenuItemClickListener((MenuItem item) -> {
2353 // Check the download preference.
2354 if (downloadWithExternalApp) { // Download with an external app.
2355 downloadUrlWithExternalApp(linkUrl);
2356 } else { // Handle the download inside of Privacy Browser.
2357 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2358 new PrepareSaveDialog(this, this, getSupportFragmentManager(), currentWebView.getSettings().getUserAgentString(),
2359 currentWebView.getAcceptCookies()).execute(linkUrl);
2362 // Consume the event.
2366 // Add an empty Cancel entry, which by default closes the context menu.
2367 menu.add(R.string.cancel);
2370 // `IMAGE_TYPE` is an image.
2371 case WebView.HitTestResult.IMAGE_TYPE:
2372 // Get the image URL.
2373 imageUrl = hitTestResult.getExtra();
2375 // Remove the incorrect lint warning below that the image URL might be null.
2376 assert imageUrl != null;
2378 // Set the context menu title.
2379 if (imageUrl.startsWith("data:")) { // The image data is contained in within the URL, making it exceedingly long.
2380 // Truncate the image URL before making it the title.
2381 menu.setHeaderTitle(imageUrl.substring(0, 100));
2382 } else { // The image URL does not contain the full image data.
2383 // Set the image URL as the title of the context menu.
2384 menu.setHeaderTitle(imageUrl);
2387 // Add an Open in New Tab entry.
2388 menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2389 // Load the image in a new tab.
2390 addNewTab(imageUrl, true);
2392 // Consume the event.
2396 // Add an Open with App entry.
2397 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2398 // Open the image URL with an external app.
2399 openWithApp(imageUrl);
2401 // Consume the event.
2405 // Add an Open with Browser entry.
2406 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2407 // Open the image URL with an external browser.
2408 openWithBrowser(imageUrl);
2410 // Consume the event.
2414 // Add a View Image entry.
2415 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2416 // Load the image in the current tab.
2417 loadUrl(currentWebView, imageUrl);
2419 // Consume the event.
2423 // Add a Save Image entry.
2424 menu.add(R.string.save_image).setOnMenuItemClickListener((MenuItem item) -> {
2425 // Check the download preference.
2426 if (downloadWithExternalApp) { // Download with an external app.
2427 downloadUrlWithExternalApp(imageUrl);
2428 } else { // Handle the download inside of Privacy Browser.
2429 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2430 new PrepareSaveDialog(this, this, getSupportFragmentManager(), currentWebView.getSettings().getUserAgentString(),
2431 currentWebView.getAcceptCookies()).execute(imageUrl);
2434 // Consume the event.
2438 // Add a Copy URL entry.
2439 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2440 // Save the image URL in a clip data.
2441 ClipData imageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2443 // Set the clip data as the clipboard's primary clip.
2444 clipboardManager.setPrimaryClip(imageTypeClipData);
2446 // Consume the event.
2450 // Add an empty Cancel entry, which by default closes the context menu.
2451 menu.add(R.string.cancel);
2454 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2455 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2456 // Get the image URL.
2457 imageUrl = hitTestResult.getExtra();
2459 // Instantiate a handler.
2460 Handler handler = new Handler();
2462 // Get a message from the handler.
2463 Message message = handler.obtainMessage();
2465 // Request the image details from the last touched node be returned in the message.
2466 currentWebView.requestFocusNodeHref(message);
2468 // Get the link URL from the message data.
2469 linkUrl = message.getData().getString("url");
2471 // Set the link URL as the title of the context menu.
2472 menu.setHeaderTitle(linkUrl);
2474 // Add an Open in New Tab entry.
2475 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2476 // Load the link URL in a new tab and move to it.
2477 addNewTab(linkUrl, true);
2479 // Consume the event.
2483 // Add an Open in Background entry.
2484 menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
2485 // Lod the link URL in a new tab but do not move to it.
2486 addNewTab(linkUrl, false);
2488 // Consume the event.
2492 // Add an Open Image in New Tab entry.
2493 menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2494 // Load the image in a new tab and move to it.
2495 addNewTab(imageUrl, true);
2497 // Consume the event.
2501 // Add an Open with App entry.
2502 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2503 // Open the link URL with an external app.
2504 openWithApp(linkUrl);
2506 // Consume the event.
2510 // Add an Open with Browser entry.
2511 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2512 // Open the link URL with an external browser.
2513 openWithBrowser(linkUrl);
2515 // Consume the event.
2519 // Add a View Image entry.
2520 menu.add(R.string.view_image).setOnMenuItemClickListener((MenuItem item) -> {
2521 // View the image in the current tab.
2522 loadUrl(currentWebView, imageUrl);
2524 // Consume the event.
2528 // Add a Save Image entry.
2529 menu.add(R.string.save_image).setOnMenuItemClickListener((MenuItem item) -> {
2530 // Check the download preference.
2531 if (downloadWithExternalApp) { // Download with an external app.
2532 downloadUrlWithExternalApp(imageUrl);
2533 } else { // Handle the download inside of Privacy Browser.
2534 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2535 new PrepareSaveDialog(this, this, getSupportFragmentManager(), currentWebView.getSettings().getUserAgentString(),
2536 currentWebView.getAcceptCookies()).execute(imageUrl);
2539 // Consume the event.
2543 // Add a Copy URL entry.
2544 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2545 // Save the link URL in a clip data.
2546 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2548 // Set the clip data as the clipboard's primary clip.
2549 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2551 // Consume the event.
2555 // Add a Save URL entry.
2556 menu.add(R.string.save_url).setOnMenuItemClickListener((MenuItem item) -> {
2557 // Check the download preference.
2558 if (downloadWithExternalApp) { // Download with an external app.
2559 downloadUrlWithExternalApp(linkUrl);
2560 } else { // Handle the download inside of Privacy Browser.
2561 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2562 new PrepareSaveDialog(this, this, getSupportFragmentManager(), currentWebView.getSettings().getUserAgentString(),
2563 currentWebView.getAcceptCookies()).execute(linkUrl);
2566 // Consume the event.
2570 // Add an empty Cancel entry, which by default closes the context menu.
2571 menu.add(R.string.cancel);
2574 case WebView.HitTestResult.EMAIL_TYPE:
2575 // Get the target URL.
2576 linkUrl = hitTestResult.getExtra();
2578 // Set the target URL as the title of the `ContextMenu`.
2579 menu.setHeaderTitle(linkUrl);
2581 // Add a Write Email entry.
2582 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2583 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2584 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2586 // Parse the url and set it as the data for the `Intent`.
2587 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2589 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2590 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2594 startActivity(emailIntent);
2595 } catch (ActivityNotFoundException exception) {
2596 // Display a snackbar.
2597 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
2600 // Consume the event.
2604 // Add a Copy Email Address entry.
2605 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2606 // Save the email address in a `ClipData`.
2607 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2609 // Set the `ClipData` as the clipboard's primary clip.
2610 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2612 // Consume the event.
2616 // Add an empty Cancel entry, which by default closes the context menu.
2617 menu.add(R.string.cancel);
2623 public void onCreateBookmark(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2624 // Get a handle for the bookmarks list view.
2625 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2628 Dialog dialog = dialogFragment.getDialog();
2630 // Remove the incorrect lint warning below that the dialog might be null.
2631 assert dialog != null;
2633 // Get the views from the dialog fragment.
2634 EditText createBookmarkNameEditText = dialog.findViewById(R.id.create_bookmark_name_edittext);
2635 EditText createBookmarkUrlEditText = dialog.findViewById(R.id.create_bookmark_url_edittext);
2637 // Extract the strings from the edit texts.
2638 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2639 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2641 // Create a favorite icon byte array output stream.
2642 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2644 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2645 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2647 // Convert the favorite icon byte array stream to a byte array.
2648 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2650 // Display the new bookmark below the current items in the (0 indexed) list.
2651 int newBookmarkDisplayOrder = bookmarksListView.getCount();
2653 // Create the bookmark.
2654 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2656 // Update the bookmarks cursor with the current contents of this folder.
2657 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2659 // Update the list view.
2660 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2662 // Scroll to the new bookmark.
2663 bookmarksListView.setSelection(newBookmarkDisplayOrder);
2667 public void onCreateBookmarkFolder(DialogFragment dialogFragment, @NonNull Bitmap favoriteIconBitmap) {
2668 // Get a handle for the bookmarks list view.
2669 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2672 Dialog dialog = dialogFragment.getDialog();
2674 // Remove the incorrect lint warning below that the dialog might be null.
2675 assert dialog != null;
2677 // Get handles for the views in the dialog fragment.
2678 EditText folderNameEditText = dialog.findViewById(R.id.folder_name_edittext);
2679 RadioButton defaultIconRadioButton = dialog.findViewById(R.id.default_icon_radiobutton);
2680 ImageView defaultIconImageView = dialog.findViewById(R.id.default_icon_imageview);
2682 // Get new folder name string.
2683 String folderNameString = folderNameEditText.getText().toString();
2685 // Create a folder icon bitmap.
2686 Bitmap folderIconBitmap;
2688 // Set the folder icon bitmap according to the dialog.
2689 if (defaultIconRadioButton.isChecked()) { // Use the default folder icon.
2690 // Get the default folder icon drawable.
2691 Drawable folderIconDrawable = defaultIconImageView.getDrawable();
2693 // Convert the folder icon drawable to a bitmap drawable.
2694 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2696 // Convert the folder icon bitmap drawable to a bitmap.
2697 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2698 } else { // Use the WebView favorite icon.
2699 // Copy the favorite icon bitmap to the folder icon bitmap.
2700 folderIconBitmap = favoriteIconBitmap;
2703 // Create a folder icon byte array output stream.
2704 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2706 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2707 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2709 // Convert the folder icon byte array stream to a byte array.
2710 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2712 // Move all the bookmarks down one in the display order.
2713 for (int i = 0; i < bookmarksListView.getCount(); i++) {
2714 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2715 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2718 // Create the folder, which will be placed at the top of the `ListView`.
2719 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2721 // Update the bookmarks cursor with the current contents of this folder.
2722 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2724 // Update the list view.
2725 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2727 // Scroll to the new folder.
2728 bookmarksListView.setSelection(0);
2732 public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId, @NonNull Bitmap favoriteIconBitmap) {
2733 // Remove the incorrect lint warning below that the dialog fragment might be null.
2734 assert dialogFragment != null;
2737 Dialog dialog = dialogFragment.getDialog();
2739 // Remove the incorrect lint warning below that the dialog might be null.
2740 assert dialog != null;
2742 // Get handles for the views from the dialog.
2743 RadioButton currentFolderIconRadioButton = dialog.findViewById(R.id.current_icon_radiobutton);
2744 RadioButton defaultFolderIconRadioButton = dialog.findViewById(R.id.default_icon_radiobutton);
2745 ImageView defaultFolderIconImageView = dialog.findViewById(R.id.default_icon_imageview);
2746 EditText editFolderNameEditText = dialog.findViewById(R.id.folder_name_edittext);
2748 // Get the new folder name.
2749 String newFolderNameString = editFolderNameEditText.getText().toString();
2751 // Check if the favorite icon has changed.
2752 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
2753 // Update the name in the database.
2754 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2755 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
2756 // Create the new folder icon Bitmap.
2757 Bitmap folderIconBitmap;
2759 // Populate the new folder icon bitmap.
2760 if (defaultFolderIconRadioButton.isChecked()) {
2761 // Get the default folder icon drawable.
2762 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2764 // Convert the folder icon drawable to a bitmap drawable.
2765 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2767 // Convert the folder icon bitmap drawable to a bitmap.
2768 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2769 } else { // Use the `WebView` favorite icon.
2770 // Copy the favorite icon bitmap to the folder icon bitmap.
2771 folderIconBitmap = favoriteIconBitmap;
2774 // Create a folder icon byte array output stream.
2775 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2777 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2778 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2780 // Convert the folder icon byte array stream to a byte array.
2781 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2783 // Update the folder icon in the database.
2784 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, newFolderIconByteArray);
2785 } else { // The folder icon and the name have changed.
2786 // Get the new folder icon bitmap.
2787 Bitmap folderIconBitmap;
2788 if (defaultFolderIconRadioButton.isChecked()) {
2789 // Get the default folder icon drawable.
2790 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2792 // Convert the folder icon drawable to a bitmap drawable.
2793 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2795 // Convert the folder icon bitmap drawable to a bitmap.
2796 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2797 } else { // Use the `WebView` favorite icon.
2798 // Copy the favorite icon bitmap to the folder icon bitmap.
2799 folderIconBitmap = favoriteIconBitmap;
2802 // Create a folder icon byte array output stream.
2803 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2805 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2806 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2808 // Convert the folder icon byte array stream to a byte array.
2809 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2811 // Update the folder name and icon in the database.
2812 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, newFolderIconByteArray);
2815 // Update the bookmarks cursor with the current contents of this folder.
2816 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2818 // Update the list view.
2819 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2822 // Process the results of a file browse.
2824 public void onActivityResult(int requestCode, int resultCode, Intent returnedIntent) {
2825 // Run the default commands.
2826 super.onActivityResult(requestCode, resultCode, returnedIntent);
2828 // Run the commands that correlate to the specified request code.
2829 switch (requestCode) {
2830 case BROWSE_FILE_UPLOAD_REQUEST_CODE:
2831 // Pass the file to the WebView.
2832 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, returnedIntent));
2835 case BROWSE_OPEN_REQUEST_CODE:
2836 // Don't do anything if the user pressed back from the file picker.
2837 if (resultCode == Activity.RESULT_OK) {
2838 // Get a handle for the open dialog fragment.
2839 DialogFragment openDialogFragment = (DialogFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.open));
2841 // Only update the file name if the dialog still exists.
2842 if (openDialogFragment != null) {
2843 // Get a handle for the open dialog.
2844 Dialog openDialog = openDialogFragment.getDialog();
2846 // Remove the incorrect lint warning below that the dialog might be null.
2847 assert openDialog != null;
2849 // Get a handle for the file name edit text.
2850 EditText fileNameEditText = openDialog.findViewById(R.id.file_name_edittext);
2852 // Get the file name URI from the intent.
2853 Uri fileNameUri = returnedIntent.getData();
2855 // Get the file name string from the URI.
2856 String fileNameString = fileNameUri.toString();
2858 // Set the file name text.
2859 fileNameEditText.setText(fileNameString);
2861 // Move the cursor to the end of the file name edit text.
2862 fileNameEditText.setSelection(fileNameString.length());
2869 private void loadUrlFromTextBox() {
2870 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
2871 String unformattedUrlString = urlEditText.getText().toString().trim();
2873 // Initialize the formatted URL string.
2876 // Check to see if the unformatted URL string is a valid URL. Otherwise, convert it into a search.
2877 if (unformattedUrlString.startsWith("content://")) { // This is a Content URL.
2878 // Load the entire content URL.
2879 url = unformattedUrlString;
2880 } else if (Patterns.WEB_URL.matcher(unformattedUrlString).matches() || unformattedUrlString.startsWith("http://") || unformattedUrlString.startsWith("https://") ||
2881 unformattedUrlString.startsWith("file://")) { // This is a standard URL.
2882 // Add `https://` at the beginning if there is no protocol. Otherwise the app will segfault.
2883 if (!unformattedUrlString.startsWith("http") && !unformattedUrlString.startsWith("file://")) {
2884 unformattedUrlString = "https://" + unformattedUrlString;
2887 // Initialize the unformatted URL.
2888 URL unformattedUrl = null;
2890 // Convert the unformatted URL string to a URL, then to a URI, and then back to a string, which sanitizes the input and adds in any missing components.
2892 unformattedUrl = new URL(unformattedUrlString);
2893 } catch (MalformedURLException e) {
2894 e.printStackTrace();
2897 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2898 String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2899 String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2900 String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2901 String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2902 String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2905 Uri.Builder uri = new Uri.Builder();
2906 uri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2908 // Decode the URI as a UTF-8 string in.
2910 url = URLDecoder.decode(uri.build().toString(), "UTF-8");
2911 } catch (UnsupportedEncodingException exception) {
2912 // Do nothing. The formatted URL string will remain blank.
2914 } else if (!unformattedUrlString.isEmpty()){ // This is not a URL, but rather a search string.
2915 // Create an encoded URL String.
2916 String encodedUrlString;
2918 // Sanitize the search input.
2920 encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2921 } catch (UnsupportedEncodingException exception) {
2922 encodedUrlString = "";
2925 // Add the base search URL.
2926 url = searchURL + encodedUrlString;
2929 // 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.
2930 urlEditText.clearFocus();
2933 loadUrl(currentWebView, url);
2936 private void loadUrl(NestedScrollWebView nestedScrollWebView, String url) {
2937 // Sanitize the URL.
2938 url = sanitizeUrl(url);
2940 // Apply the domain settings and load the URL.
2941 applyDomainSettings(nestedScrollWebView, url, true, false, true);
2944 public void findPreviousOnPage(View view) {
2945 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
2946 currentWebView.findNext(false);
2949 public void findNextOnPage(View view) {
2950 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2951 currentWebView.findNext(true);
2954 public void closeFindOnPage(View view) {
2955 // Get a handle for the views.
2956 Toolbar toolbar = findViewById(R.id.toolbar);
2957 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
2958 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
2960 // Delete the contents of `find_on_page_edittext`.
2961 findOnPageEditText.setText(null);
2963 // Clear the highlighted phrases if the WebView is not null.
2964 if (currentWebView != null) {
2965 currentWebView.clearMatches();
2968 // Hide the find on page linear layout.
2969 findOnPageLinearLayout.setVisibility(View.GONE);
2971 // Show the toolbar.
2972 toolbar.setVisibility(View.VISIBLE);
2974 // Get a handle for the input method manager.
2975 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
2977 // Remove the lint warning below that the input method manager might be null.
2978 assert inputMethodManager != null;
2980 // Hide the keyboard.
2981 inputMethodManager.hideSoftInputFromWindow(toolbar.getWindowToken(), 0);
2985 public void onApplyNewFontSize(DialogFragment dialogFragment) {
2986 // Remove the incorrect lint warning below that the dialog fragment might be null.
2987 assert dialogFragment != null;
2990 Dialog dialog = dialogFragment.getDialog();
2992 // Remove the incorrect lint warning below tha the dialog might be null.
2993 assert dialog != null;
2995 // Get a handle for the font size edit text.
2996 EditText fontSizeEditText = dialog.findViewById(R.id.font_size_edittext);
2998 // Initialize the new font size variable with the current font size.
2999 int newFontSize = currentWebView.getSettings().getTextZoom();
3001 // Get the font size from the edit text.
3003 newFontSize = Integer.parseInt(fontSizeEditText.getText().toString());
3004 } catch (Exception exception) {
3005 // If the edit text does not contain a valid font size do nothing.
3008 // Apply the new font size.
3009 currentWebView.getSettings().setTextZoom(newFontSize);
3013 public void onOpen(DialogFragment dialogFragment) {
3015 Dialog dialog = dialogFragment.getDialog();
3017 // Remove the incorrect lint warning below that the dialog might be null.
3018 assert dialog != null;
3020 // Get handles for the views.
3021 EditText fileNameEditText = dialog.findViewById(R.id.file_name_edittext);
3022 CheckBox mhtCheckBox = dialog.findViewById(R.id.mht_checkbox);
3024 // Get the file path string.
3025 String openFilePath = fileNameEditText.getText().toString();
3027 // Apply the domain settings. This resets the favorite icon and removes any domain settings.
3028 applyDomainSettings(currentWebView, openFilePath, true, false, false);
3030 // Open the file according to the type.
3031 if (mhtCheckBox.isChecked()) { // Force opening of an MHT file.
3033 // Get the MHT file input stream.
3034 InputStream mhtFileInputStream = getContentResolver().openInputStream(Uri.parse(openFilePath));
3036 // Create a temporary MHT file.
3037 File temporaryMhtFile = File.createTempFile("temporary_mht_file", ".mht", getCacheDir());
3039 // Get a file output stream for the temporary MHT file.
3040 FileOutputStream temporaryMhtFileOutputStream = new FileOutputStream(temporaryMhtFile);
3042 // Create a transfer byte array.
3043 byte[] transferByteArray = new byte[1024];
3045 // Create an integer to track the number of bytes read.
3048 // Copy the temporary MHT file input stream to the MHT output stream.
3049 while ((bytesRead = mhtFileInputStream.read(transferByteArray)) > 0) {
3050 temporaryMhtFileOutputStream.write(transferByteArray, 0, bytesRead);
3053 // Flush the temporary MHT file output stream.
3054 temporaryMhtFileOutputStream.flush();
3056 // Close the streams.
3057 temporaryMhtFileOutputStream.close();
3058 mhtFileInputStream.close();
3060 // Load the temporary MHT file.
3061 currentWebView.loadUrl(temporaryMhtFile.toString());
3062 } catch (Exception exception) {
3063 // Display a snackbar.
3064 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
3066 } else { // Let the WebView handle opening of the file.
3068 currentWebView.loadUrl(openFilePath);
3072 private void downloadUrlWithExternalApp(String url) {
3073 // Create a download intent. Not specifying the action type will display the maximum number of options.
3074 Intent downloadIntent = new Intent();
3076 // Set the URI and the mime type.
3077 downloadIntent.setDataAndType(Uri.parse(url), "text/html");
3079 // Flag the intent to open in a new task.
3080 downloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3082 // Show the chooser.
3083 startActivity(Intent.createChooser(downloadIntent, getString(R.string.download_with_external_app)));
3086 public void onSaveUrl(@NonNull String originalUrlString, @NonNull String fileNameString, @NonNull DialogFragment dialogFragment) {
3087 // Store the URL. This will be used in the save URL activity result launcher.
3088 if (originalUrlString.startsWith("data:")) {
3089 // Save the original URL.
3090 saveUrlString = originalUrlString;
3093 Dialog dialog = dialogFragment.getDialog();
3095 // Remove the incorrect lint warning below that the dialog might be null.
3096 assert dialog != null;
3098 // Get a handle for the dialog URL edit text.
3099 EditText dialogUrlEditText = dialog.findViewById(R.id.url_edittext);
3101 // Get the URL from the edit text, which may have been modified.
3102 saveUrlString = dialogUrlEditText.getText().toString();
3105 // Open the file picker.
3106 saveUrlActivityResultLauncher.launch(fileNameString);
3109 // Remove the warning that `OnTouchListener()` needs to override `performClick()`, as the only purpose of setting the `OnTouchListener()` is to make it do nothing.
3110 @SuppressLint("ClickableViewAccessibility")
3111 private void initializeApp() {
3112 // Get a handle for the input method.
3113 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
3115 // Remove the lint warning below that the input method manager might be null.
3116 assert inputMethodManager != null;
3118 // Initialize the gray foreground color spans for highlighting the URLs.
3119 initialGrayColorSpan = new ForegroundColorSpan(getColor(R.color.gray_500));
3120 finalGrayColorSpan = new ForegroundColorSpan(getColor(R.color.gray_500));
3122 // Get the current theme status.
3123 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
3125 // Set the red color span according to the theme.
3126 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
3127 redColorSpan = new ForegroundColorSpan(getColor(R.color.red_a700));
3129 redColorSpan = new ForegroundColorSpan(getColor(R.color.red_900));
3132 // Remove the formatting from the URL edit text when the user is editing the text.
3133 urlEditText.setOnFocusChangeListener((View v, boolean hasFocus) -> {
3134 if (hasFocus) { // The user is editing the URL text box.
3135 // Remove the highlighting.
3136 urlEditText.getText().removeSpan(redColorSpan);
3137 urlEditText.getText().removeSpan(initialGrayColorSpan);
3138 urlEditText.getText().removeSpan(finalGrayColorSpan);
3139 } else { // The user has stopped editing the URL text box.
3140 // Move to the beginning of the string.
3141 urlEditText.setSelection(0);
3143 // Reapply the highlighting.
3148 // Set the go button on the keyboard to load the URL in `urlTextBox`.
3149 urlEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
3150 // If the event is a key-down event on the `enter` button, load the URL.
3151 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
3152 // Load the URL into the mainWebView and consume the event.
3153 loadUrlFromTextBox();
3155 // If the enter key was pressed, consume the event.
3158 // If any other key was pressed, do not consume the event.
3163 // Create an Orbot status broadcast receiver.
3164 orbotStatusBroadcastReceiver = new BroadcastReceiver() {
3166 public void onReceive(Context context, Intent intent) {
3167 // Store the content of the status message in `orbotStatus`.
3168 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
3170 // If Privacy Browser is waiting on the proxy, load the website now that Orbot is connected.
3171 if ((orbotStatus != null) && orbotStatus.equals(ProxyHelper.ORBOT_STATUS_ON) && waitingForProxy) {
3172 // Reset the waiting for proxy status.
3173 waitingForProxy = false;
3175 // Get a list of the current fragments.
3176 List<Fragment> fragmentList = getSupportFragmentManager().getFragments();
3178 // Check each fragment to see if it is a waiting for proxy dialog. Sometimes more than one is displayed.
3179 for (int i = 0; i < fragmentList.size(); i++) {
3180 // Get the fragment tag.
3181 String fragmentTag = fragmentList.get(i).getTag();
3183 // Check to see if it is the waiting for proxy dialog.
3184 if ((fragmentTag!= null) && fragmentTag.equals(getString(R.string.waiting_for_proxy_dialog))) {
3185 // Dismiss the waiting for proxy dialog.
3186 ((DialogFragment) fragmentList.get(i)).dismiss();
3190 // Reload existing URLs and load any URLs that are waiting for the proxy.
3191 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3192 // Get the WebView tab fragment.
3193 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3195 // Get the fragment view.
3196 View fragmentView = webViewTabFragment.getView();
3198 // Only process the WebViews if they exist.
3199 if (fragmentView != null) {
3200 // Get the nested scroll WebView from the tab fragment.
3201 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3203 // Get the waiting for proxy URL string.
3204 String waitingForProxyUrlString = nestedScrollWebView.getWaitingForProxyUrlString();
3206 // Load the pending URL if it exists.
3207 if (!waitingForProxyUrlString.isEmpty()) { // A URL is waiting to be loaded.
3209 loadUrl(nestedScrollWebView, waitingForProxyUrlString);
3211 // Reset the waiting for proxy URL string.
3212 nestedScrollWebView.setWaitingForProxyUrlString("");
3213 } else { // No URL is waiting to be loaded.
3214 // Reload the existing URL.
3215 nestedScrollWebView.reload();
3223 // Register the Orbot status broadcast receiver on `this` context.
3224 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
3226 // Get handles for views that need to be modified.
3227 LinearLayout bookmarksHeaderLinearLayout = findViewById(R.id.bookmarks_header_linearlayout);
3228 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
3229 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
3230 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
3231 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
3232 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
3234 // Update the web view pager every time a tab is modified.
3235 webViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
3237 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
3242 public void onPageSelected(int position) {
3243 // Close the find on page bar if it is open.
3244 closeFindOnPage(null);
3246 // Set the current WebView.
3247 setCurrentWebView(position);
3249 // Select the corresponding tab if it does not match the currently selected page. This will happen if the page was scrolled by creating a new tab.
3250 if (tabLayout.getSelectedTabPosition() != position) {
3251 // Wait until the new tab has been created.
3252 tabLayout.post(() -> {
3253 // Get a handle for the tab.
3254 TabLayout.Tab tab = tabLayout.getTabAt(position);
3256 // Assert that the tab is not null.
3266 public void onPageScrollStateChanged(int state) {
3271 // Display the View SSL Certificate dialog when the currently selected tab is reselected.
3272 tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
3274 public void onTabSelected(TabLayout.Tab tab) {
3275 // Select the same page in the view pager.
3276 webViewPager.setCurrentItem(tab.getPosition());
3280 public void onTabUnselected(TabLayout.Tab tab) {
3285 public void onTabReselected(TabLayout.Tab tab) {
3286 // Instantiate the View SSL Certificate dialog.
3287 DialogFragment viewSslCertificateDialogFragment = ViewSslCertificateDialog.displayDialog(currentWebView.getWebViewFragmentId(), currentWebView.getFavoriteOrDefaultIcon());
3289 // Display the View SSL Certificate dialog.
3290 viewSslCertificateDialogFragment.show(getSupportFragmentManager(), getString(R.string.view_ssl_certificate));
3294 // Set a touch listener on the bookmarks header linear layout so that touches don't pass through to the button underneath.
3295 bookmarksHeaderLinearLayout.setOnTouchListener((view, motionEvent) -> {
3296 // Consume the touch.
3300 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
3301 launchBookmarksActivityFab.setOnClickListener(v -> {
3302 // Get a copy of the favorite icon bitmap.
3303 Bitmap favoriteIconBitmap = currentWebView.getFavoriteOrDefaultIcon();
3305 // Create a favorite icon byte array output stream.
3306 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3308 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
3309 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
3311 // Convert the favorite icon byte array stream to a byte array.
3312 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
3314 // Create an intent to launch the bookmarks activity.
3315 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
3317 // Add the extra information to the intent.
3318 bookmarksIntent.putExtra("current_url", currentWebView.getUrl());
3319 bookmarksIntent.putExtra("current_title", currentWebView.getTitle());
3320 bookmarksIntent.putExtra("current_folder", currentBookmarksFolder);
3321 bookmarksIntent.putExtra("favorite_icon_byte_array", favoriteIconByteArray);
3324 startActivity(bookmarksIntent);
3327 // Set the create new bookmark folder FAB to display an alert dialog.
3328 createBookmarkFolderFab.setOnClickListener(v -> {
3329 // Create a create bookmark folder dialog.
3330 DialogFragment createBookmarkFolderDialog = CreateBookmarkFolderDialog.createBookmarkFolder(currentWebView.getFavoriteOrDefaultIcon());
3332 // Show the create bookmark folder dialog.
3333 createBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.create_folder));
3336 // Set the create new bookmark FAB to display an alert dialog.
3337 createBookmarkFab.setOnClickListener(view -> {
3338 // Instantiate the create bookmark dialog.
3339 DialogFragment createBookmarkDialog = CreateBookmarkDialog.createBookmark(currentWebView.getUrl(), currentWebView.getTitle(), currentWebView.getFavoriteOrDefaultIcon());
3341 // Display the create bookmark dialog.
3342 createBookmarkDialog.show(getSupportFragmentManager(), getString(R.string.create_bookmark));
3345 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
3346 findOnPageEditText.addTextChangedListener(new TextWatcher() {
3348 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
3353 public void onTextChanged(CharSequence s, int start, int before, int count) {
3358 public void afterTextChanged(Editable s) {
3359 // 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.
3360 if (currentWebView != null) {
3361 currentWebView.findAllAsync(findOnPageEditText.getText().toString());
3366 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
3367 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
3368 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
3369 // Hide the soft keyboard.
3370 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
3372 // Consume the event.
3374 } else { // A different key was pressed.
3375 // Do not consume the event.
3380 // Implement swipe to refresh.
3381 swipeRefreshLayout.setOnRefreshListener(() -> {
3382 // Reload the website.
3383 currentWebView.reload();
3386 // Store the default progress view offsets for use later in `initializeWebView()`.
3387 defaultProgressViewStartOffset = swipeRefreshLayout.getProgressViewStartOffset();
3388 defaultProgressViewEndOffset = swipeRefreshLayout.getProgressViewEndOffset();
3390 // Set the refresh color scheme according to the theme.
3391 swipeRefreshLayout.setColorSchemeResources(R.color.blue_text);
3393 // Initialize a color background typed value.
3394 TypedValue colorBackgroundTypedValue = new TypedValue();
3396 // Get the color background from the theme.
3397 getTheme().resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true);
3399 // Get the color background int from the typed value.
3400 int colorBackgroundInt = colorBackgroundTypedValue.data;
3402 // Set the swipe refresh background color.
3403 swipeRefreshLayout.setProgressBackgroundColorSchemeColor(colorBackgroundInt);
3405 // The drawer titles identify the drawer layouts in accessibility mode.
3406 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
3407 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
3409 // Load the bookmarks folder.
3410 loadBookmarksFolder();
3412 // Handle clicks on bookmarks.
3413 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
3414 // Convert the id from long to int to match the format of the bookmarks database.
3415 int databaseId = (int) id;
3417 // Get the bookmark cursor for this ID.
3418 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseId);
3420 // Move the bookmark cursor to the first row.
3421 bookmarkCursor.moveToFirst();
3423 // Act upon the bookmark according to the type.
3424 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
3425 // Store the new folder name in `currentBookmarksFolder`.
3426 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME));
3428 // Load the new folder.
3429 loadBookmarksFolder();
3430 } else { // The selected bookmark is not a folder.
3431 // Load the bookmark URL.
3432 loadUrl(currentWebView, bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_URL)));
3434 // Close the bookmarks drawer.
3435 drawerLayout.closeDrawer(GravityCompat.END);
3438 // Close the `Cursor`.
3439 bookmarkCursor.close();
3442 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
3443 // Convert the database ID from `long` to `int`.
3444 int databaseId = (int) id;
3446 // Find out if the selected bookmark is a folder.
3447 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
3449 // Check to see if the bookmark is a folder.
3450 if (isFolder) { // The bookmark is a folder.
3451 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
3452 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME));
3454 // Instantiate the edit folder bookmark dialog.
3455 DialogFragment editBookmarkFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId, currentWebView.getFavoriteOrDefaultIcon());
3457 // Show the edit folder bookmark dialog.
3458 editBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.edit_folder));
3459 } else { // The bookmark is not a folder.
3460 // Get the bookmark cursor for this ID.
3461 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseId);
3463 // Move the bookmark cursor to the first row.
3464 bookmarkCursor.moveToFirst();
3466 // Load the bookmark in a new tab.
3467 addNewTab(bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_URL)), true);
3469 // Close the bookmarks drawer.
3470 drawerLayout.closeDrawer(GravityCompat.END);
3473 // Consume the event.
3477 // The drawer listener is used to update the navigation menu.
3478 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
3480 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
3484 public void onDrawerOpened(@NonNull View drawerView) {
3488 public void onDrawerClosed(@NonNull View drawerView) {
3489 // Reset the drawer icon when the drawer is closed. Otherwise, it is an arrow if the drawer is open when the app is restarted.
3490 actionBarDrawerToggle.syncState();
3494 public void onDrawerStateChanged(int newState) {
3495 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // A drawer is opening or closing.
3496 // Update the navigation menu items if the WebView is not null.
3497 if (currentWebView != null) {
3498 navigationBackMenuItem.setEnabled(currentWebView.canGoBack());
3499 navigationForwardMenuItem.setEnabled(currentWebView.canGoForward());
3500 navigationHistoryMenuItem.setEnabled((currentWebView.canGoBack() || currentWebView.canGoForward()));
3501 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
3503 // Hide the keyboard (if displayed).
3504 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
3507 // Clear the focus from from the URL text box. This removes any text selection markers and context menus, which otherwise draw above the open drawers.
3508 urlEditText.clearFocus();
3510 // Clear the focus from from the WebView if it is not null, which can happen if a user opens a drawer while the browser is being resumed.
3511 if (currentWebView != null) {
3512 // Clearing the focus from the WebView removes any text selection markers and context menus, which otherwise draw above the open drawers.
3513 currentWebView.clearFocus();
3519 // Inflate a bare WebView to get the default user agent. It is not used to render content on the screen.
3520 @SuppressLint("InflateParams") View webViewLayout = getLayoutInflater().inflate(R.layout.bare_webview, null, false);
3522 // Get a handle for the WebView.
3523 WebView bareWebView = webViewLayout.findViewById(R.id.bare_webview);
3525 // Store the default user agent.
3526 webViewDefaultUserAgent = bareWebView.getSettings().getUserAgentString();
3528 // Destroy the bare WebView.
3529 bareWebView.destroy();
3532 private void applyAppSettings() {
3533 // Get a handle for the shared preferences.
3534 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3536 // Store the values from the shared preferences in variables.
3537 incognitoModeEnabled = sharedPreferences.getBoolean(getString(R.string.incognito_mode_key), false);
3538 sanitizeTrackingQueries = sharedPreferences.getBoolean(getString(R.string.tracking_queries_key), true);
3539 sanitizeAmpRedirects = sharedPreferences.getBoolean(getString(R.string.amp_redirects_key), true);
3540 proxyMode = sharedPreferences.getString(getString(R.string.proxy_key), getString(R.string.proxy_default_value));
3541 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean(getString(R.string.full_screen_browsing_mode_key), false);
3542 hideAppBar = sharedPreferences.getBoolean(getString(R.string.hide_app_bar_key), true);
3543 downloadWithExternalApp = sharedPreferences.getBoolean(getString(R.string.download_with_external_app_key), false);
3544 scrollAppBar = sharedPreferences.getBoolean(getString(R.string.scroll_app_bar_key), true);
3546 // Apply the saved proxy mode if the app has been restarted.
3547 if (savedProxyMode != null) {
3548 // Apply the saved proxy mode.
3549 proxyMode = savedProxyMode;
3551 // Reset the saved proxy mode.
3552 savedProxyMode = null;
3555 // Get the search string.
3556 String searchString = sharedPreferences.getString(getString(R.string.search_key), getString(R.string.search_default_value));
3558 // Set the search string.
3559 if (searchString.equals(getString(R.string.custom_url_item)))
3560 searchURL = sharedPreferences.getString(getString(R.string.search_custom_url_key), getString(R.string.search_custom_url_default_value));
3562 searchURL = searchString;
3567 // Adjust the layout and scrolling parameters according to the position of the app bar.
3568 if (bottomAppBar) { // The app bar is on the bottom.
3570 if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) { // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
3571 // Reset the WebView padding to fill the available space.
3572 swipeRefreshLayout.setPadding(0, 0, 0, 0);
3573 } else { // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
3574 // Move the WebView above the app bar layout.
3575 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight);
3577 // Show the app bar if it is scrolled off the screen.
3578 if (appBarLayout.getTranslationY() != 0) {
3579 // Animate the bottom app bar onto the screen.
3580 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0);
3583 objectAnimator.start();
3586 } else { // The app bar is on the top.
3587 // Get the current layout parameters. Using coordinator layout parameters allows the `setBehavior()` command and using app bar layout parameters allows the `setScrollFlags()` command.
3588 CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
3589 AppBarLayout.LayoutParams toolbarLayoutParams = (AppBarLayout.LayoutParams) toolbar.getLayoutParams();
3590 AppBarLayout.LayoutParams findOnPageLayoutParams = (AppBarLayout.LayoutParams) findOnPageLinearLayout.getLayoutParams();
3591 AppBarLayout.LayoutParams tabsLayoutParams = (AppBarLayout.LayoutParams) tabsLinearLayout.getLayoutParams();
3593 // Add the scrolling behavior to the layout parameters.
3595 // Enable scrolling of the app bar.
3596 swipeRefreshLayoutParams.setBehavior(new AppBarLayout.ScrollingViewBehavior());
3597 toolbarLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3598 findOnPageLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3599 tabsLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3601 // Disable scrolling of the app bar.
3602 swipeRefreshLayoutParams.setBehavior(null);
3603 toolbarLayoutParams.setScrollFlags(0);
3604 findOnPageLayoutParams.setScrollFlags(0);
3605 tabsLayoutParams.setScrollFlags(0);
3607 // Expand the app bar if it is currently collapsed.
3608 appBarLayout.setExpanded(true);
3611 // Set the app bar scrolling for each WebView.
3612 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3613 // Get the WebView tab fragment.
3614 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3616 // Get the fragment view.
3617 View fragmentView = webViewTabFragment.getView();
3619 // Only modify the WebViews if they exist.
3620 if (fragmentView != null) {
3621 // Get the nested scroll WebView from the tab fragment.
3622 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3624 // Set the app bar scrolling.
3625 nestedScrollWebView.setNestedScrollingEnabled(scrollAppBar);
3630 // Update the full screen browsing mode settings.
3631 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
3632 // Update the visibility of the app bar, which might have changed in the settings.
3634 // Hide the tab linear layout.
3635 tabsLinearLayout.setVisibility(View.GONE);
3637 // Hide the action bar.
3640 // Show the tab linear layout.
3641 tabsLinearLayout.setVisibility(View.VISIBLE);
3643 // Show the action bar.
3647 /* Hide the system bars.
3648 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3649 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
3650 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3651 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3653 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
3654 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3655 } else { // Privacy Browser is not in full screen browsing mode.
3656 // 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.
3657 inFullScreenBrowsingMode = false;
3659 // Show the tab linear layout.
3660 tabsLinearLayout.setVisibility(View.VISIBLE);
3662 // Show the action bar.
3665 // Remove the `SYSTEM_UI` flags from the root frame layout.
3666 rootFrameLayout.setSystemUiVisibility(0);
3671 public void navigateHistory(@NonNull String url, int steps) {
3672 // Apply the domain settings.
3673 applyDomainSettings(currentWebView, url, false, false, false);
3675 // Load the history entry.
3676 currentWebView.goBackOrForward(steps);
3680 public void pinnedErrorGoBack() {
3681 // Get the current web back forward list.
3682 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
3684 // Get the previous entry URL.
3685 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
3687 // Apply the domain settings.
3688 applyDomainSettings(currentWebView, previousUrl, false, false, false);
3691 currentWebView.goBack();
3694 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
3695 @SuppressLint("SetJavaScriptEnabled")
3696 private void applyDomainSettings(NestedScrollWebView nestedScrollWebView, String url, boolean resetTab, boolean reloadWebsite, boolean loadUrl) {
3697 // Store the current URL.
3698 nestedScrollWebView.setCurrentUrl(url);
3700 // Parse the URL into a URI.
3701 Uri uri = Uri.parse(url);
3703 // Extract the domain from `uri`.
3704 String newHostName = uri.getHost();
3706 // Strings don't like to be null.
3707 if (newHostName == null) {
3711 // Apply the domain settings if a new domain is being loaded or if the new domain is blank. This allows the user to set temporary settings for JavaScript, cookies, DOM storage, etc.
3712 if (!nestedScrollWebView.getCurrentDomainName().equals(newHostName) || newHostName.equals("")) {
3713 // Set the new host name as the current domain name.
3714 nestedScrollWebView.setCurrentDomainName(newHostName);
3716 // Reset the ignoring of pinned domain information.
3717 nestedScrollWebView.setIgnorePinnedDomainInformation(false);
3719 // Clear any pinned SSL certificate or IP addresses.
3720 nestedScrollWebView.clearPinnedSslCertificate();
3721 nestedScrollWebView.setPinnedIpAddresses("");
3723 // Reset the favorite icon if specified.
3725 // Initialize the favorite icon.
3726 nestedScrollWebView.initializeFavoriteIcon();
3728 // Get the current page position.
3729 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
3731 // Get the corresponding tab.
3732 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
3734 // Update the tab if it isn't null, which sometimes happens when restarting from the background.
3736 // Get the tab custom view.
3737 View tabCustomView = tab.getCustomView();
3739 // Remove the warning below that the tab custom view might be null.
3740 assert tabCustomView != null;
3742 // Get the tab views.
3743 ImageView tabFavoriteIconImageView = tabCustomView.findViewById(R.id.favorite_icon_imageview);
3744 TextView tabTitleTextView = tabCustomView.findViewById(R.id.title_textview);
3746 // Set the default favorite icon as the favorite icon for this tab.
3747 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(nestedScrollWebView.getFavoriteOrDefaultIcon(), 64, 64, true));
3749 // Set the loading title text.
3750 tabTitleTextView.setText(R.string.loading);
3754 // Get a full domain name cursor.
3755 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3757 // Initialize `domainSettingsSet`.
3758 Set<String> domainSettingsSet = new HashSet<>();
3760 // Get the domain name column index.
3761 int domainNameColumnIndex = domainNameCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.DOMAIN_NAME);
3763 // Populate the domain settings set.
3764 for (int i = 0; i < domainNameCursor.getCount(); i++) {
3765 // Move the domains cursor to the current row.
3766 domainNameCursor.moveToPosition(i);
3768 // Store the domain name in the domain settings set.
3769 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3772 // Close the domain name cursor.
3773 domainNameCursor.close();
3775 // Initialize the domain name in database variable.
3776 String domainNameInDatabase = null;
3778 // Check the hostname against the domain settings set.
3779 if (domainSettingsSet.contains(newHostName)) { // The hostname is contained in the domain settings set.
3780 // Record the domain name in the database.
3781 domainNameInDatabase = newHostName;
3783 // Set the domain settings applied tracker to true.
3784 nestedScrollWebView.setDomainSettingsApplied(true);
3785 } else { // The hostname is not contained in the domain settings set.
3786 // Set the domain settings applied tracker to false.
3787 nestedScrollWebView.setDomainSettingsApplied(false);
3790 // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3791 while (!nestedScrollWebView.getDomainSettingsApplied() && newHostName.contains(".")) { // Stop checking if domain settings are already applied or there are no more `.` in the hostname.
3792 if (domainSettingsSet.contains("*." + newHostName)) { // Check the host name prepended by `*.`.
3793 // Set the domain settings applied tracker to true.
3794 nestedScrollWebView.setDomainSettingsApplied(true);
3796 // Store the applied domain names as it appears in the database.
3797 domainNameInDatabase = "*." + newHostName;
3800 // Strip out the lowest subdomain of of the host name.
3801 newHostName = newHostName.substring(newHostName.indexOf(".") + 1);
3805 // Get a handle for the shared preferences.
3806 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3808 // Store the general preference information.
3809 String defaultFontSizeString = sharedPreferences.getString(getString(R.string.font_size_key), getString(R.string.font_size_default_value));
3810 String defaultUserAgentName = sharedPreferences.getString(getString(R.string.user_agent_key), getString(R.string.user_agent_default_value));
3811 boolean defaultSwipeToRefresh = sharedPreferences.getBoolean(getString(R.string.swipe_to_refresh_key), true);
3812 String webViewTheme = sharedPreferences.getString(getString(R.string.webview_theme_key), getString(R.string.webview_theme_default_value));
3813 boolean wideViewport = sharedPreferences.getBoolean(getString(R.string.wide_viewport_key), true);
3814 boolean displayWebpageImages = sharedPreferences.getBoolean(getString(R.string.display_webpage_images_key), true);
3816 // Get the WebView theme entry values string array.
3817 String[] webViewThemeEntryValuesStringArray = getResources().getStringArray(R.array.webview_theme_entry_values);
3819 // Get a handle for the cookie manager.
3820 CookieManager cookieManager = CookieManager.getInstance();
3822 // Initialize the user agent array adapter and string array.
3823 ArrayAdapter<CharSequence> userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item);
3824 String[] userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
3826 if (nestedScrollWebView.getDomainSettingsApplied()) { // The url has custom domain settings.
3827 // Remove the incorrect lint warning below that the domain name in database might be null.
3828 assert domainNameInDatabase != null;
3830 // Get a cursor for the current host.
3831 Cursor currentDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3833 // Move to the first position.
3834 currentDomainSettingsCursor.moveToFirst();
3836 // Get the settings from the cursor.
3837 nestedScrollWebView.setDomainSettingsDatabaseId(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ID)));
3838 nestedScrollWebView.getSettings().setJavaScriptEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3839 nestedScrollWebView.setAcceptCookies(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.COOKIES)) == 1);
3840 nestedScrollWebView.getSettings().setDomStorageEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3841 // Form data can be removed once the minimum API >= 26.
3842 boolean saveFormData = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3843 nestedScrollWebView.setEasyListEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3844 nestedScrollWebView.setEasyPrivacyEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3845 nestedScrollWebView.setFanboysAnnoyanceListEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(
3846 DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3847 nestedScrollWebView.setFanboysSocialBlockingListEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(
3848 DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3849 nestedScrollWebView.setUltraListEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ULTRALIST)) == 1);
3850 nestedScrollWebView.setUltraPrivacyEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_ULTRAPRIVACY)) == 1);
3851 nestedScrollWebView.setBlockAllThirdPartyRequests(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(
3852 DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
3853 String userAgentName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.USER_AGENT));
3854 int fontSize = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.FONT_SIZE));
3855 int swipeToRefreshInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
3856 int webViewThemeInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.WEBVIEW_THEME));
3857 int wideViewportInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.WIDE_VIEWPORT));
3858 int displayWebpageImagesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.DISPLAY_IMAGES));
3859 boolean pinnedSslCertificate = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3860 String pinnedSslIssuedToCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3861 String pinnedSslIssuedToOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3862 String pinnedSslIssuedToUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3863 String pinnedSslIssuedByCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3864 String pinnedSslIssuedByOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3865 String pinnedSslIssuedByUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3866 Date pinnedSslStartDate = new Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_START_DATE)));
3867 Date pinnedSslEndDate = new Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_END_DATE)));
3868 boolean pinnedIpAddresses = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.PINNED_IP_ADDRESSES)) == 1);
3869 String pinnedHostIpAddresses = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.IP_ADDRESSES));
3871 // Close the current host domain settings cursor.
3872 currentDomainSettingsCursor.close();
3874 // If there is a pinned SSL certificate, store it in the WebView.
3875 if (pinnedSslCertificate) {
3876 nestedScrollWebView.setPinnedSslCertificate(pinnedSslIssuedToCName, pinnedSslIssuedToOName, pinnedSslIssuedToUName, pinnedSslIssuedByCName, pinnedSslIssuedByOName, pinnedSslIssuedByUName,
3877 pinnedSslStartDate, pinnedSslEndDate);
3880 // If there is a pinned IP address, store it in the WebView.
3881 if (pinnedIpAddresses) {
3882 nestedScrollWebView.setPinnedIpAddresses(pinnedHostIpAddresses);
3885 // Apply the cookie domain settings.
3886 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptCookies());
3888 // Apply the form data setting if the API < 26.
3889 if (Build.VERSION.SDK_INT < 26) {
3890 nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
3893 // Apply the font size.
3894 try { // Try the specified font size to see if it is valid.
3895 if (fontSize == 0) { // Apply the default font size.
3896 // Try to set the font size from the value in the app settings.
3897 nestedScrollWebView.getSettings().setTextZoom(Integer.parseInt(defaultFontSizeString));
3898 } else { // Apply the font size from domain settings.
3899 nestedScrollWebView.getSettings().setTextZoom(fontSize);
3901 } catch (Exception exception) { // The specified font size is invalid
3902 // Set the font size to be 100%
3903 nestedScrollWebView.getSettings().setTextZoom(100);
3906 // Set the user agent.
3907 if (userAgentName.equals(getString(R.string.system_default_user_agent))) { // Use the system default user agent.
3908 // Get the array position of the default user agent name.
3909 int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3911 // Set the user agent according to the system default.
3912 switch (defaultUserAgentArrayPosition) {
3913 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
3914 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3915 nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
3918 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3919 // Set the user agent to `""`, which uses the default value.
3920 nestedScrollWebView.getSettings().setUserAgentString("");
3923 case SETTINGS_CUSTOM_USER_AGENT:
3924 // Set the default custom user agent.
3925 nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString(getString(R.string.custom_user_agent_key), getString(R.string.custom_user_agent_default_value)));
3929 // Get the user agent string from the user agent data array
3930 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
3932 } else { // Set the user agent according to the stored name.
3933 // Get the array position of the user agent name.
3934 int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
3936 switch (userAgentArrayPosition) {
3937 case UNRECOGNIZED_USER_AGENT: // The user agent name contains a custom user agent.
3938 nestedScrollWebView.getSettings().setUserAgentString(userAgentName);
3941 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3942 // Set the user agent to `""`, which uses the default value.
3943 nestedScrollWebView.getSettings().setUserAgentString("");
3947 // Get the user agent string from the user agent data array.
3948 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3952 // Set swipe to refresh.
3953 switch (swipeToRefreshInt) {
3954 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
3955 // Store the swipe to refresh status in the nested scroll WebView.
3956 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
3958 // Update the swipe refresh layout.
3959 if (defaultSwipeToRefresh) { // Swipe to refresh is enabled.
3960 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
3961 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
3962 } else { // Swipe to refresh is disabled.
3963 // Disable the swipe refresh layout.
3964 swipeRefreshLayout.setEnabled(false);
3968 case DomainsDatabaseHelper.ENABLED:
3969 // Store the swipe to refresh status in the nested scroll WebView.
3970 nestedScrollWebView.setSwipeToRefresh(true);
3972 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
3973 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
3976 case DomainsDatabaseHelper.DISABLED:
3977 // Store the swipe to refresh status in the nested scroll WebView.
3978 nestedScrollWebView.setSwipeToRefresh(false);
3980 // Disable swipe to refresh.
3981 swipeRefreshLayout.setEnabled(false);
3985 // Check to see if WebView themes are supported.
3986 if ((Build.VERSION.SDK_INT >= 33) && WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) { // The device is running API >= 33 and algorithmic darkening is supported.
3987 // Set the WebView theme.
3988 switch (webViewThemeInt) {
3989 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
3990 // Set the WebView theme. A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
3991 if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) { // The light theme is selected.
3992 // Turn off algorithmic darkening.
3993 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), false);
3994 } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) { // The dark theme is selected.
3995 // Turn on algorithmic darkening.
3996 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), true);
3997 } else { // The system default theme is selected.
3998 // Get the current system theme status.
3999 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4001 // Set the algorithmic darkening according to the current system theme status.
4002 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES));
4006 case DomainsDatabaseHelper.LIGHT_THEME:
4007 // Turn off algorithmic darkening.
4008 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), false);
4011 case DomainsDatabaseHelper.DARK_THEME:
4012 // Turn on algorithmic darkening.
4013 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), true);
4016 } else if ((Build.VERSION.SDK_INT < 33) && WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) { // The device is running API < 33 and the WebView supports force dark.
4017 // Set the WebView theme.
4018 switch (webViewThemeInt) {
4019 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4020 // Set the WebView theme. A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
4021 if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) { // The light theme is selected.
4022 // Turn off the WebView dark mode.
4023 //noinspection deprecation
4024 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4025 } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) { // The dark theme is selected.
4026 // Turn on the WebView dark mode.
4027 //noinspection deprecation
4028 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4029 } else { // The system default theme is selected.
4030 // Get the current system theme status.
4031 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4033 // Set the WebView theme according to the current system theme status.
4034 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) { // The system is in day mode.
4035 // Turn off the WebView dark mode.
4036 //noinspection deprecation
4037 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4038 } else { // The system is in night mode.
4039 // Turn on the WebView dark mode.
4040 //noinspection deprecation
4041 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4046 case DomainsDatabaseHelper.LIGHT_THEME:
4047 // Turn off the WebView dark mode.
4048 //noinspection deprecation
4049 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4052 case DomainsDatabaseHelper.DARK_THEME:
4053 // Turn on the WebView dark mode.
4054 //noinspection deprecation
4055 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4060 // Set the viewport.
4061 switch (wideViewportInt) {
4062 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4063 nestedScrollWebView.getSettings().setUseWideViewPort(wideViewport);
4066 case DomainsDatabaseHelper.ENABLED:
4067 nestedScrollWebView.getSettings().setUseWideViewPort(true);
4070 case DomainsDatabaseHelper.DISABLED:
4071 nestedScrollWebView.getSettings().setUseWideViewPort(false);
4075 // Set the loading of webpage images.
4076 switch (displayWebpageImagesInt) {
4077 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4078 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
4081 case DomainsDatabaseHelper.ENABLED:
4082 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(true);
4085 case DomainsDatabaseHelper.DISABLED:
4086 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(false);
4090 // Set a background on the URL relative layout to indicate that custom domain settings are being used.
4091 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.domain_settings_url_background, null));
4092 } else { // The new URL does not have custom domain settings. Load the defaults.
4093 // Store the values from the shared preferences.
4094 nestedScrollWebView.getSettings().setJavaScriptEnabled(sharedPreferences.getBoolean(getString(R.string.javascript_key), false));
4095 nestedScrollWebView.setAcceptCookies(sharedPreferences.getBoolean(getString(R.string.cookies_key), false));
4096 nestedScrollWebView.getSettings().setDomStorageEnabled(sharedPreferences.getBoolean(getString(R.string.dom_storage_key), false));
4097 boolean saveFormData = sharedPreferences.getBoolean(getString(R.string.save_form_data_key), false); // Form data can be removed once the minimum API >= 26.
4098 nestedScrollWebView.setEasyListEnabled(sharedPreferences.getBoolean(getString(R.string.easylist_key), true));
4099 nestedScrollWebView.setEasyPrivacyEnabled(sharedPreferences.getBoolean(getString(R.string.easyprivacy_key), true));
4100 nestedScrollWebView.setFanboysAnnoyanceListEnabled(sharedPreferences.getBoolean(getString(R.string.fanboys_annoyance_list_key), true));
4101 nestedScrollWebView.setFanboysSocialBlockingListEnabled(sharedPreferences.getBoolean(getString(R.string.fanboys_social_blocking_list_key), true));
4102 nestedScrollWebView.setUltraListEnabled(sharedPreferences.getBoolean(getString(R.string.ultralist_key), true));
4103 nestedScrollWebView.setUltraPrivacyEnabled(sharedPreferences.getBoolean(getString(R.string.ultraprivacy_key), true));
4104 nestedScrollWebView.setBlockAllThirdPartyRequests(sharedPreferences.getBoolean(getString(R.string.block_all_third_party_requests_key), false));
4106 // Apply the default cookie setting.
4107 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptCookies());
4109 // Apply the default font size setting.
4111 // Try to set the font size from the value in the app settings.
4112 nestedScrollWebView.getSettings().setTextZoom(Integer.parseInt(defaultFontSizeString));
4113 } catch (Exception exception) {
4114 // If the app settings value is invalid, set the font size to 100%.
4115 nestedScrollWebView.getSettings().setTextZoom(100);
4118 // Apply the form data setting if the API < 26.
4119 if (Build.VERSION.SDK_INT < 26) {
4120 nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
4123 // Store the swipe to refresh status in the nested scroll WebView.
4124 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
4126 // Update the swipe refresh layout.
4127 if (defaultSwipeToRefresh) { // Swipe to refresh is enabled.
4128 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
4129 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
4130 } else { // Swipe to refresh is disabled.
4131 // Disable the swipe refresh layout.
4132 swipeRefreshLayout.setEnabled(false);
4135 // Reset the pinned variables.
4136 nestedScrollWebView.setDomainSettingsDatabaseId(-1);
4138 // Get the array position of the user agent name.
4139 int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
4141 // Set the user agent.
4142 switch (userAgentArrayPosition) {
4143 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
4144 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
4145 nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
4148 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4149 // Set the user agent to `""`, which uses the default value.
4150 nestedScrollWebView.getSettings().setUserAgentString("");
4153 case SETTINGS_CUSTOM_USER_AGENT:
4154 // Set the default custom user agent.
4155 nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString(getString(R.string.custom_user_agent_key), getString(R.string.custom_user_agent_default_value)));
4159 // Get the user agent string from the user agent data array
4160 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4163 // Apply the WebView theme if supported by the installed WebView.
4164 if ((Build.VERSION.SDK_INT >= 33) && WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) { // The device is running API >= 33 and algorithmic darkening is supported.
4165 // Set the WebView theme. A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
4166 if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) { // the light theme is selected.
4167 // Turn off algorithmic darkening.
4168 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), false);
4169 } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) { // The dark theme is selected.
4170 // Turn on algorithmic darkening.
4171 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), true);
4172 } else { // The system default theme is selected.
4173 // Get the current system theme status.
4174 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4176 // Set the algorithmic darkening according to the current system theme status.
4177 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), currentThemeStatus == Configuration.UI_MODE_NIGHT_YES);
4179 } else if ((Build.VERSION.SDK_INT < 33) && WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) { // The device is running API < 33 and the WebView supports force dark.
4180 // Set the WebView theme. A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
4181 if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) { // The light theme is selected.
4182 // Turn off the WebView dark mode.
4183 //noinspection deprecation
4184 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4185 } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) { // The dark theme is selected.
4186 // Turn on the WebView dark mode.
4187 //noinspection deprecation
4188 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4189 } else { // The system default theme is selected.
4190 // Get the current system theme status.
4191 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4193 // Set the WebView theme according to the current system theme status.
4194 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) { // The system is in day mode.
4195 // Turn off the WebView dark mode.
4196 //noinspection deprecation
4197 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4198 } else { // The system is in night mode.
4199 // Turn on the WebView dark mode.
4200 //noinspection deprecation
4201 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4206 // Set the viewport.
4207 nestedScrollWebView.getSettings().setUseWideViewPort(wideViewport);
4209 // Set the loading of webpage images.
4210 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
4212 // Set a transparent background on the URL relative layout.
4213 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.color.transparent, null));
4216 // Close the domains database helper.
4217 domainsDatabaseHelper.close();
4219 // Update the privacy icons.
4220 updatePrivacyIcons(true);
4223 // Reload the website if returning from the Domains activity.
4224 if (reloadWebsite) {
4225 nestedScrollWebView.reload();
4228 // Load the URL if directed. This makes sure that the domain settings are properly loaded before the URL. By using `loadUrl()`, instead of `loadUrlFromBase()`, the Referer header will never be sent.
4230 nestedScrollWebView.loadUrl(url);
4234 private void applyProxy(boolean reloadWebViews) {
4235 // Set the proxy according to the mode.
4236 proxyHelper.setProxy(getApplicationContext(), appBarLayout, proxyMode);
4238 // Reset the waiting for proxy tracker.
4239 waitingForProxy = false;
4241 // Get the current theme status.
4242 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4244 // Update the user interface and reload the WebViews if requested.
4245 switch (proxyMode) {
4246 case ProxyHelper.NONE:
4247 // Initialize a color background typed value.
4248 TypedValue colorBackgroundTypedValue = new TypedValue();
4250 // Get the color background from the theme.
4251 getTheme().resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true);
4253 // Get the color background int from the typed value.
4254 int colorBackgroundInt = colorBackgroundTypedValue.data;
4256 // Set the default app bar layout background.
4257 appBarLayout.setBackgroundColor(colorBackgroundInt);
4260 case ProxyHelper.TOR:
4261 // Set the app bar background to indicate proxying through Orbot is enabled.
4262 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4263 appBarLayout.setBackgroundResource(R.color.blue_50);
4265 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4268 // Check to see if Orbot is installed.
4270 // Get the package manager.
4271 PackageManager packageManager = getPackageManager();
4273 // Check to see if Orbot is in the list. This will throw an error and drop to the catch section if it isn't installed.
4274 packageManager.getPackageInfo("org.torproject.android", 0);
4276 // Check to see if the proxy is ready.
4277 if (!orbotStatus.equals(ProxyHelper.ORBOT_STATUS_ON)) { // Orbot is not ready.
4278 // Set the waiting for proxy status.
4279 waitingForProxy = true;
4281 // Show the waiting for proxy dialog if it isn't already displayed.
4282 if (getSupportFragmentManager().findFragmentByTag(getString(R.string.waiting_for_proxy_dialog)) == null) {
4283 // Get a handle for the waiting for proxy alert dialog.
4284 DialogFragment waitingForProxyDialogFragment = new WaitingForProxyDialog();
4286 // Try to show the dialog. Sometimes the window is not yet active if returning from Settings.
4288 // Show the waiting for proxy alert dialog.
4289 waitingForProxyDialogFragment.show(getSupportFragmentManager(), getString(R.string.waiting_for_proxy_dialog));
4290 } catch (Exception waitingForTorException) {
4291 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
4292 pendingDialogsArrayList.add(new PendingDialog(waitingForProxyDialogFragment, getString(R.string.waiting_for_proxy_dialog)));
4296 } catch (PackageManager.NameNotFoundException exception) { // Orbot is not installed.
4297 // Show the Orbot not installed dialog if it is not already displayed.
4298 if (getSupportFragmentManager().findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
4299 // Get a handle for the Orbot not installed alert dialog.
4300 DialogFragment orbotNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode);
4302 // Try to show the dialog. Sometimes the window is not yet active if returning from Settings.
4304 // Display the Orbot not installed alert dialog.
4305 orbotNotInstalledDialogFragment.show(getSupportFragmentManager(), getString(R.string.proxy_not_installed_dialog));
4306 } catch (Exception orbotNotInstalledException) {
4307 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
4308 pendingDialogsArrayList.add(new PendingDialog(orbotNotInstalledDialogFragment, getString(R.string.proxy_not_installed_dialog)));
4314 case ProxyHelper.I2P:
4315 // Set the app bar background to indicate proxying through Orbot is enabled.
4316 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4317 appBarLayout.setBackgroundResource(R.color.blue_50);
4319 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4321 // Get the package manager.
4322 PackageManager packageManager = getPackageManager();
4324 // Check to see if I2P is installed.
4326 // Check to see if the F-Droid flavor is installed. This will throw an error and drop to the catch section if it isn't installed.
4327 packageManager.getPackageInfo("net.i2p.android.router", 0);
4328 } catch (PackageManager.NameNotFoundException fdroidException) { // The F-Droid flavor is not installed.
4330 // Check to see if the Google Play flavor is installed. This will throw an error and drop to the catch section if it isn't installed.
4331 packageManager.getPackageInfo("net.i2p.android", 0);
4332 } catch (PackageManager.NameNotFoundException googlePlayException) { // The Google Play flavor is not installed.
4333 // Sow the I2P not installed dialog if it is not already displayed.
4334 if (getSupportFragmentManager().findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
4335 // Get a handle for the waiting for proxy alert dialog.
4336 DialogFragment i2pNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode);
4338 // Try to show the dialog. Sometimes the window is not yet active if returning from Settings.
4340 // Display the I2P not installed alert dialog.
4341 i2pNotInstalledDialogFragment.show(getSupportFragmentManager(), getString(R.string.proxy_not_installed_dialog));
4342 } catch (Exception i2pNotInstalledException) {
4343 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
4344 pendingDialogsArrayList.add(new PendingDialog(i2pNotInstalledDialogFragment, getString(R.string.proxy_not_installed_dialog)));
4351 case ProxyHelper.CUSTOM:
4352 // Set the app bar background to indicate proxying through Orbot is enabled.
4353 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4354 appBarLayout.setBackgroundResource(R.color.blue_50);
4356 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4361 // Reload the WebViews if requested and not waiting for the proxy.
4362 if (reloadWebViews && !waitingForProxy) {
4363 // Reload the WebViews.
4364 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4365 // Get the WebView tab fragment.
4366 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4368 // Get the fragment view.
4369 View fragmentView = webViewTabFragment.getView();
4371 // Only reload the WebViews if they exist.
4372 if (fragmentView != null) {
4373 // Get the nested scroll WebView from the tab fragment.
4374 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4376 // Reload the WebView.
4377 nestedScrollWebView.reload();
4383 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
4384 // Only update the privacy icons if the options menu and the current WebView have already been populated.
4385 if ((optionsMenu != null) && (currentWebView != null)) {
4386 // Update the privacy icon.
4387 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is enabled.
4388 optionsPrivacyMenuItem.setIcon(R.drawable.javascript_enabled);
4389 } else if (currentWebView.getAcceptCookies()) { // JavaScript is disabled but cookies are enabled.
4390 optionsPrivacyMenuItem.setIcon(R.drawable.warning);
4391 } else { // All the dangerous features are disabled.
4392 optionsPrivacyMenuItem.setIcon(R.drawable.privacy_mode);
4395 // Update the cookies icon.
4396 if (currentWebView.getAcceptCookies()) {
4397 optionsCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
4399 optionsCookiesMenuItem.setIcon(R.drawable.cookies_disabled);
4402 // Update the refresh icon.
4403 if (optionsRefreshMenuItem.getTitle() == getString(R.string.refresh)) { // The refresh icon is displayed.
4404 // Set the icon. Once the minimum API is >= 26, the blue and black icons can be combined with a tint list.
4405 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled);
4406 } else { // The stop icon is displayed.
4407 // Set the icon. Once the minimum API is >= 26, the blue and black icons can be combined with a tint list.
4408 optionsRefreshMenuItem.setIcon(R.drawable.close_blue);
4411 // `invalidateOptionsMenu()` calls `onPrepareOptionsMenu()` and redraws the icons in the app bar.
4412 if (runInvalidateOptionsMenu) {
4413 invalidateOptionsMenu();
4418 private void highlightUrlText() {
4419 // Only highlight the URL text if the box is not currently selected.
4420 if (!urlEditText.hasFocus()) {
4421 // Get the URL string.
4422 String urlString = urlEditText.getText().toString();
4424 // Highlight the URL according to the protocol.
4425 if (urlString.startsWith("file://") || urlString.startsWith("content://")) { // This is a file or content URL.
4426 // De-emphasize everything before the file name.
4427 urlEditText.getText().setSpan(initialGrayColorSpan, 0, urlString.lastIndexOf("/") + 1,Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4428 } else { // This is a web URL.
4429 // Get the index of the `/` immediately after the domain name.
4430 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
4432 // Create a base URL string.
4435 // Get the base URL.
4436 if (endOfDomainName > 0) { // There is at least one character after the base URL.
4437 // Get the base URL.
4438 baseUrl = urlString.substring(0, endOfDomainName);
4439 } else { // There are no characters after the base URL.
4440 // Set the base URL to be the entire URL string.
4441 baseUrl = urlString;
4444 // Get the index of the last `.` in the domain.
4445 int lastDotIndex = baseUrl.lastIndexOf(".");
4447 // Get the index of the penultimate `.` in the domain.
4448 int penultimateDotIndex = baseUrl.lastIndexOf(".", lastDotIndex - 1);
4450 // Markup the beginning of the URL.
4451 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
4452 urlEditText.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4454 // De-emphasize subdomains.
4455 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
4456 urlEditText.getText().setSpan(initialGrayColorSpan, 7, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4458 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
4459 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
4460 // De-emphasize the protocol and the additional subdomains.
4461 urlEditText.getText().setSpan(initialGrayColorSpan, 0, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4462 } else { // There is only one subdomain in the domain name.
4463 // De-emphasize only the protocol.
4464 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4468 // De-emphasize the text after the domain name.
4469 if (endOfDomainName > 0) {
4470 urlEditText.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4476 private void loadBookmarksFolder() {
4477 // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
4478 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
4480 // Populate the bookmarks cursor adapter.
4481 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
4483 public View newView(Context context, Cursor cursor, ViewGroup parent) {
4484 // Inflate the individual item layout.
4485 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
4489 public void bindView(View view, Context context, Cursor cursor) {
4490 // Get handles for the views.
4491 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
4492 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
4494 // Get the favorite icon byte array from the cursor.
4495 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.FAVORITE_ICON));
4497 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
4498 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
4500 // Display the bitmap in `bookmarkFavoriteIcon`.
4501 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
4503 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
4504 String bookmarkNameString = cursor.getString(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME));
4505 bookmarkNameTextView.setText(bookmarkNameString);
4507 // Make the font bold for folders.
4508 if (cursor.getInt(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
4509 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
4510 } else { // Reset the font to default for normal bookmarks.
4511 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
4516 // Get a handle for the bookmarks list view.
4517 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
4519 // Populate the list view with the adapter.
4520 bookmarksListView.setAdapter(bookmarksCursorAdapter);
4522 // Get a handle for the bookmarks title text view.
4523 TextView bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
4525 // Set the bookmarks drawer title.
4526 if (currentBookmarksFolder.isEmpty()) {
4527 bookmarksTitleTextView.setText(R.string.bookmarks);
4529 bookmarksTitleTextView.setText(currentBookmarksFolder);
4533 private void openWithApp(String url) {
4534 // Create an open with app intent with `ACTION_VIEW`.
4535 Intent openWithAppIntent = new Intent(Intent.ACTION_VIEW);
4537 // Set the URI but not the MIME type. This should open all available apps.
4538 openWithAppIntent.setData(Uri.parse(url));
4540 // Flag the intent to open in a new task.
4541 openWithAppIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4545 // Show the chooser.
4546 startActivity(openWithAppIntent);
4547 } catch (ActivityNotFoundException exception) { // There are no apps available to open the URL.
4548 // Show a snackbar with the error.
4549 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
4553 private void openWithBrowser(String url) {
4554 // Create an open with browser intent with `ACTION_VIEW`.
4555 Intent openWithBrowserIntent = new Intent(Intent.ACTION_VIEW);
4557 // Set the URI and the MIME type. `"text/html"` should load browser options.
4558 openWithBrowserIntent.setDataAndType(Uri.parse(url), "text/html");
4560 // Flag the intent to open in a new task.
4561 openWithBrowserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4565 // Show the chooser.
4566 startActivity(openWithBrowserIntent);
4567 } catch (ActivityNotFoundException exception) { // There are no browsers available to open the URL.
4568 // Show a snackbar with the error.
4569 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
4573 private String sanitizeUrl(String url) {
4574 // Sanitize tracking queries.
4575 if (sanitizeTrackingQueries)
4576 url = sanitizeUrlHelper.sanitizeTrackingQueries(url);
4578 // Sanitize AMP redirects.
4579 if (sanitizeAmpRedirects)
4580 url = sanitizeUrlHelper.sanitizeAmpRedirects(url);
4582 // Return the sanitized URL.
4586 public void finishedPopulatingBlocklists(ArrayList<ArrayList<List<String[]>>> combinedBlocklists) {
4587 // Store the blocklists.
4588 easyList = combinedBlocklists.get(0);
4589 easyPrivacy = combinedBlocklists.get(1);
4590 fanboysAnnoyanceList = combinedBlocklists.get(2);
4591 fanboysSocialList = combinedBlocklists.get(3);
4592 ultraList = combinedBlocklists.get(4);
4593 ultraPrivacy = combinedBlocklists.get(5);
4595 // Check to see if the activity has been restarted with a saved state.
4596 if ((savedStateArrayList == null) || (savedStateArrayList.size() == 0)) { // The activity has not been restarted or it was restarted on start to force the night theme.
4597 // Add the first tab.
4598 addNewTab("", true);
4599 } else { // The activity has been restarted.
4600 // Restore each tab. Once the minimum API >= 24, a `forEach()` command can be used.
4601 for (int i = 0; i < savedStateArrayList.size(); i++) {
4603 tabLayout.addTab(tabLayout.newTab());
4606 TabLayout.Tab newTab = tabLayout.getTabAt(i);
4608 // Remove the lint warning below that the current tab might be null.
4609 assert newTab != null;
4611 // Set a custom view on the new tab.
4612 newTab.setCustomView(R.layout.tab_custom_view);
4614 // Add the new page.
4615 webViewPagerAdapter.restorePage(savedStateArrayList.get(i), savedNestedScrollWebViewStateArrayList.get(i));
4618 // Reset the saved state variables.
4619 savedStateArrayList = null;
4620 savedNestedScrollWebViewStateArrayList = null;
4622 // Restore the selected tab position.
4623 if (savedTabPosition == 0) { // The first tab is selected.
4624 // Set the first page as the current WebView.
4625 setCurrentWebView(0);
4626 } else { // the first tab is not selected.
4627 // Move to the selected tab.
4628 webViewPager.setCurrentItem(savedTabPosition);
4631 // Get the intent that started the app.
4632 Intent intent = getIntent();
4634 // Reset the intent. This prevents a duplicate tab from being created on restart.
4635 setIntent(new Intent());
4637 // Get the information from the intent.
4638 String intentAction = intent.getAction();
4639 Uri intentUriData = intent.getData();
4640 String intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT);
4642 // Determine if this is a web search.
4643 boolean isWebSearch = ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH));
4645 // 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.
4646 if (intentUriData != null || intentStringExtra != null || isWebSearch) {
4647 // Get the shared preferences.
4648 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4650 // Create a URL string.
4653 // If the intent action is a web search, perform the search.
4654 if (isWebSearch) { // The intent is a web search.
4655 // Create an encoded URL string.
4656 String encodedUrlString;
4658 // Sanitize the search input and convert it to a search.
4660 encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
4661 } catch (UnsupportedEncodingException exception) {
4662 encodedUrlString = "";
4665 // Add the base search URL.
4666 url = searchURL + encodedUrlString;
4667 } else if (intentUriData != null) { // The intent contains a URL formatted as a URI.
4668 // Set the intent data as the URL.
4669 url = intentUriData.toString();
4670 } else { // The intent contains a string, which might be a URL.
4671 // Set the intent string as the URL.
4672 url = intentStringExtra;
4675 // Add a new tab if specified in the preferences.
4676 if (sharedPreferences.getBoolean(getString(R.string.open_intents_in_new_tab_key), true)) { // Load the URL in a new tab.
4677 // Set the loading new intent flag.
4678 loadingNewIntent = true;
4681 addNewTab(url, true);
4682 } else { // Load the URL in the current tab.
4684 loadUrl(currentWebView, url);
4690 public void addTab(View view) {
4691 // Add a new tab with a blank URL.
4692 addNewTab("", true);
4695 private void addNewTab(String url, boolean moveToTab) {
4696 // Clear the focus from the URL edit text, so that it will be populated with the information from the new tab.
4697 urlEditText.clearFocus();
4699 // Get the new page number. The page numbers are 0 indexed, so the new page number will match the current count.
4700 int newTabNumber = tabLayout.getTabCount();
4703 tabLayout.addTab(tabLayout.newTab());
4706 TabLayout.Tab newTab = tabLayout.getTabAt(newTabNumber);
4708 // Remove the lint warning below that the current tab might be null.
4709 assert newTab != null;
4711 // Set a custom view on the new tab.
4712 newTab.setCustomView(R.layout.tab_custom_view);
4714 // Add the new WebView page.
4715 webViewPagerAdapter.addPage(newTabNumber, webViewPager, url, moveToTab);
4717 // Show the app bar if it is at the bottom of the screen and the new tab is taking focus.
4718 if (bottomAppBar && moveToTab && (appBarLayout.getTranslationY() != 0)) {
4719 // Animate the bottom app bar onto the screen.
4720 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0);
4723 objectAnimator.start();
4727 public void closeTab(View view) {
4728 // Run the command according to the number of tabs.
4729 if (tabLayout.getTabCount() > 1) { // There is more than one tab open.
4730 // Close the current tab.
4732 } else { // There is only one tab open.
4737 private void closeCurrentTab() {
4738 // Get the current tab number.
4739 int currentTabNumber = tabLayout.getSelectedTabPosition();
4741 // Delete the current tab.
4742 tabLayout.removeTabAt(currentTabNumber);
4744 // Delete the current page. If the selected page number did not change during the delete (because the newly selected tab has has same number as the previously deleted tab), it will return true,
4745 // meaning that the current WebView must be reset. Otherwise it will happen automatically as the selected tab number changes.
4746 if (webViewPagerAdapter.deletePage(currentTabNumber, webViewPager)) {
4747 setCurrentWebView(currentTabNumber);
4751 private void exitFullScreenVideo() {
4752 // Re-enable the screen timeout.
4753 fullScreenVideoFrameLayout.setKeepScreenOn(false);
4755 // Unset the full screen video flag.
4756 displayingFullScreenVideo = false;
4758 // Remove all the views from the full screen video frame layout.
4759 fullScreenVideoFrameLayout.removeAllViews();
4761 // Hide the full screen video frame layout.
4762 fullScreenVideoFrameLayout.setVisibility(View.GONE);
4764 // Enable the sliding drawers.
4765 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
4767 // Show the coordinator layout.
4768 coordinatorLayout.setVisibility(View.VISIBLE);
4770 // Apply the appropriate full screen mode flags.
4771 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
4772 // Hide the app bar if specified.
4774 // Hide the tab linear layout.
4775 tabsLinearLayout.setVisibility(View.GONE);
4777 // Hide the action bar.
4781 /* Hide the system bars.
4782 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4783 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4784 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4785 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4787 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
4788 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
4789 } else { // Switch to normal viewing mode.
4790 // Remove the `SYSTEM_UI` flags from the root frame layout.
4791 rootFrameLayout.setSystemUiVisibility(0);
4795 private void clearAndExit() {
4796 // Get a handle for the shared preferences.
4797 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4799 // Close the bookmarks cursor and database.
4800 bookmarksCursor.close();
4801 bookmarksDatabaseHelper.close();
4803 // Get the status of the clear everything preference.
4804 boolean clearEverything = sharedPreferences.getBoolean(getString(R.string.clear_everything_key), true);
4806 // Get a handle for the runtime.
4807 Runtime runtime = Runtime.getRuntime();
4809 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
4810 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
4811 String privateDataDirectoryString = getApplicationInfo().dataDir;
4814 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_cookies_key), true)) {
4815 // Request the cookies be deleted.
4816 CookieManager.getInstance().removeAllCookies(null);
4818 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4820 // Two commands must be used because `Runtime.exec()` does not like `*`.
4821 Process deleteCookiesProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
4822 Process deleteCookiesJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
4824 // Wait until the processes have finished.
4825 deleteCookiesProcess.waitFor();
4826 deleteCookiesJournalProcess.waitFor();
4827 } catch (Exception exception) {
4828 // Do nothing if an error is thrown.
4832 // Clear DOM storage.
4833 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_dom_storage_key), true)) {
4834 // Ask `WebStorage` to clear the DOM storage.
4835 WebStorage webStorage = WebStorage.getInstance();
4836 webStorage.deleteAllData();
4838 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4840 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4841 Process deleteLocalStorageProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
4843 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
4844 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
4845 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
4846 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
4847 Process deleteDatabaseProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
4849 // Wait until the processes have finished.
4850 deleteLocalStorageProcess.waitFor();
4851 deleteIndexProcess.waitFor();
4852 deleteQuotaManagerProcess.waitFor();
4853 deleteQuotaManagerJournalProcess.waitFor();
4854 deleteDatabaseProcess.waitFor();
4855 } catch (Exception exception) {
4856 // Do nothing if an error is thrown.
4860 // Clear form data if the API < 26.
4861 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_form_data_key), true))) {
4862 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
4863 webViewDatabase.clearFormData();
4865 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4867 // A string array must be used because the database contains a space and `Runtime.exec` will not otherwise escape the string correctly.
4868 Process deleteWebDataProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
4869 Process deleteWebDataJournalProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
4871 // Wait until the processes have finished.
4872 deleteWebDataProcess.waitFor();
4873 deleteWebDataJournalProcess.waitFor();
4874 } catch (Exception exception) {
4875 // Do nothing if an error is thrown.
4879 // Clear the logcat.
4880 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_logcat_key), true)) {
4882 // Clear the logcat. `-c` clears the logcat. `-b all` clears all the buffers (instead of just crash, main, and system).
4883 Process process = Runtime.getRuntime().exec("logcat -b all -c");
4885 // Wait for the process to finish.
4887 } catch (IOException|InterruptedException exception) {
4893 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_cache_key), true)) {
4894 // Clear the cache from each WebView.
4895 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4896 // Get the WebView tab fragment.
4897 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4899 // Get the WebView fragment view.
4900 View webViewFragmentView = webViewTabFragment.getView();
4902 // Only clear the cache if the WebView exists.
4903 if (webViewFragmentView != null) {
4904 // Get the nested scroll WebView from the tab fragment.
4905 NestedScrollWebView nestedScrollWebView = webViewFragmentView.findViewById(R.id.nestedscroll_webview);
4907 // Clear the cache for this WebView.
4908 nestedScrollWebView.clearCache(true);
4912 // Manually delete the cache directories.
4914 // Delete the main cache directory.
4915 Process deleteCacheProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/cache");
4917 // Delete the secondary `Service Worker` cache directory.
4918 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4919 Process deleteServiceWorkerProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Default/Service Worker/"});
4921 // Wait until the processes have finished.
4922 deleteCacheProcess.waitFor();
4923 deleteServiceWorkerProcess.waitFor();
4924 } catch (Exception exception) {
4925 // Do nothing if an error is thrown.
4929 // Wipe out each WebView.
4930 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4931 // Get the WebView tab fragment.
4932 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4934 // Get the WebView frame layout.
4935 FrameLayout webViewFrameLayout = (FrameLayout) webViewTabFragment.getView();
4937 // Only wipe out the WebView if it exists.
4938 if (webViewFrameLayout != null) {
4939 // Get the nested scroll WebView from the tab fragment.
4940 NestedScrollWebView nestedScrollWebView = webViewFrameLayout.findViewById(R.id.nestedscroll_webview);
4942 // Clear SSL certificate preferences for this WebView.
4943 nestedScrollWebView.clearSslPreferences();
4945 // Clear the back/forward history for this WebView.
4946 nestedScrollWebView.clearHistory();
4948 // Remove all the views from the frame layout.
4949 webViewFrameLayout.removeAllViews();
4951 // Destroy the internal state of the WebView.
4952 nestedScrollWebView.destroy();
4956 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
4957 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
4958 if (clearEverything) {
4960 // Delete the folder.
4961 Process deleteAppWebviewProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
4963 // Wait until the process has finished.
4964 deleteAppWebviewProcess.waitFor();
4965 } catch (Exception exception) {
4966 // Do nothing if an error is thrown.
4970 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
4971 finishAndRemoveTask();
4973 // Remove the terminated program from RAM. The status code is `0`.
4977 public void bookmarksBack(View view) {
4978 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
4979 // close the bookmarks drawer.
4980 drawerLayout.closeDrawer(GravityCompat.END);
4981 } else { // A subfolder is displayed.
4982 // Place the former parent folder in `currentFolder`.
4983 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolderName(currentBookmarksFolder);
4985 // Load the new folder.
4986 loadBookmarksFolder();
4990 private void setCurrentWebView(int pageNumber) {
4991 // Stop the swipe to refresh indicator if it is running
4992 swipeRefreshLayout.setRefreshing(false);
4994 // Get the WebView tab fragment.
4995 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(pageNumber);
4997 // Get the fragment view.
4998 View webViewFragmentView = webViewTabFragment.getView();
5000 // Set the current WebView if the fragment view is not null.
5001 if (webViewFragmentView != null) { // The fragment has been populated.
5002 // Store the current WebView.
5003 currentWebView = webViewFragmentView.findViewById(R.id.nestedscroll_webview);
5005 // Update the status of swipe to refresh.
5006 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
5007 // Enable the swipe refresh layout if the WebView is scrolled all the way to the top. It is updated every time the scroll changes.
5008 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
5009 } else { // Swipe to refresh is disabled.
5010 // Disable the swipe refresh layout.
5011 swipeRefreshLayout.setEnabled(false);
5014 // Get a handle for the cookie manager.
5015 CookieManager cookieManager = CookieManager.getInstance();
5017 // Set the cookie status.
5018 cookieManager.setAcceptCookie(currentWebView.getAcceptCookies());
5020 // Update the privacy icons. `true` redraws the icons in the app bar.
5021 updatePrivacyIcons(true);
5023 // Get a handle for the input method manager.
5024 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
5026 // Remove the lint warning below that the input method manager might be null.
5027 assert inputMethodManager != null;
5029 // Get the current URL.
5030 String url = currentWebView.getUrl();
5032 // Update the URL edit text if not loading a new intent. Otherwise, this will be handled by `onPageStarted()` (if called) and `onPageFinished()`.
5033 if (!loadingNewIntent) { // A new intent is not being loaded.
5034 if ((url == null) || url.equals("about:blank")) { // The WebView is blank.
5035 // Display the hint in the URL edit text.
5036 urlEditText.setText("");
5038 // Request focus for the URL text box.
5039 urlEditText.requestFocus();
5041 // Display the keyboard.
5042 inputMethodManager.showSoftInput(urlEditText, 0);
5043 } else { // The WebView has a loaded URL.
5044 // Clear the focus from the URL text box.
5045 urlEditText.clearFocus();
5047 // Hide the soft keyboard.
5048 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
5050 // Display the current URL in the URL text box.
5051 urlEditText.setText(url);
5053 // Highlight the URL text.
5056 } else { // A new intent is being loaded.
5057 // Reset the loading new intent tracker.
5058 loadingNewIntent = false;
5061 // Set the background to indicate the domain settings status.
5062 if (currentWebView.getDomainSettingsApplied()) {
5063 // Set a background on the URL relative layout to indicate that custom domain settings are being used.
5064 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.domain_settings_url_background, null));
5066 // Remove any background on the URL relative layout.
5067 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.color.transparent, null));
5069 } else { // The fragment has not been populated. Try again in 100 milliseconds.
5070 // Create a handler to set the current WebView.
5071 Handler setCurrentWebViewHandler = new Handler();
5073 // Create a runnable to set the current WebView.
5074 Runnable setCurrentWebWebRunnable = () -> {
5075 // Set the current WebView.
5076 setCurrentWebView(pageNumber);
5079 // Try setting the current WebView again after 100 milliseconds.
5080 setCurrentWebViewHandler.postDelayed(setCurrentWebWebRunnable, 100);
5084 @SuppressLint("ClickableViewAccessibility")
5086 public void initializeWebView(@NonNull NestedScrollWebView nestedScrollWebView, int pageNumber, @NonNull ProgressBar progressBar, @NonNull String url, boolean restoringState) {
5087 // Get a handle for the shared preferences.
5088 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
5090 // Get the WebView theme.
5091 String webViewTheme = sharedPreferences.getString(getString(R.string.webview_theme_key), getString(R.string.webview_theme_default_value));
5093 // Get the WebView theme entry values string array.
5094 String[] webViewThemeEntryValuesStringArray = getResources().getStringArray(R.array.webview_theme_entry_values);
5096 // Apply the WebView theme if supported by the installed WebView.
5097 if ((Build.VERSION.SDK_INT >= 33) && WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) { // The device is running API >= 33 and algorithmic darkening is supported.
5098 // Set the WebView them. A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
5099 if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) { // The light theme is selected.
5100 // Turn off algorithmic darkening.
5101 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), false);
5103 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
5104 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
5105 nestedScrollWebView.setVisibility(View.VISIBLE);
5106 } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) { // The dark theme is selected.
5107 // Turn on algorithmic darkening.
5108 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), true);
5110 // The system default theme is selected.
5111 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
5113 // Set the algorithmic darkening according to the current system theme status.
5114 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) { // The system is in day mode.
5115 // Turn off algorithmic darkening.
5116 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), false);
5118 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
5119 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
5120 nestedScrollWebView.setVisibility(View.VISIBLE);
5121 } else { // The system is in night mode.
5122 // Turn on algorithmic darkening.
5123 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), true);
5126 } else if ((Build.VERSION.SDK_INT < 33) && WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) { // The device is running API < 33 and the WebView supports force dark.
5127 // Set the WebView theme. A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
5128 if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) { // The light theme is selected.
5129 // Turn off the WebView dark mode.
5130 //noinspection deprecation
5131 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
5133 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
5134 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
5135 nestedScrollWebView.setVisibility(View.VISIBLE);
5136 } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) { // The dark theme is selected.
5137 // Turn on the WebView dark mode.
5138 //noinspection deprecation
5139 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
5140 } else { // The system default theme is selected.
5141 // Get the current system theme status.
5142 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
5144 // Set the WebView theme according to the current system theme status.
5145 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) { // The system is in day mode.
5146 // Turn off the WebView dark mode.
5147 //noinspection deprecation
5148 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
5150 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
5151 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
5152 nestedScrollWebView.setVisibility(View.VISIBLE);
5153 } else { // The system is in night mode.
5154 // Turn on the WebView dark mode.
5155 //noinspection deprecation
5156 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
5161 // Get a handle for the activity
5162 Activity activity = this;
5164 // Get a handle for the input method manager.
5165 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
5167 // Instantiate the blocklist helper.
5168 BlocklistHelper blocklistHelper = new BlocklistHelper();
5170 // Remove the lint warning below that the input method manager might be null.
5171 assert inputMethodManager != null;
5173 // Set the app bar scrolling.
5174 nestedScrollWebView.setNestedScrollingEnabled(scrollAppBar);
5176 // Allow pinch to zoom.
5177 nestedScrollWebView.getSettings().setBuiltInZoomControls(true);
5179 // Hide zoom controls.
5180 nestedScrollWebView.getSettings().setDisplayZoomControls(false);
5182 // Don't allow mixed content (HTTP and HTTPS) on the same website.
5183 nestedScrollWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW);
5185 // Set the WebView to load in overview mode (zoomed out to the maximum width).
5186 nestedScrollWebView.getSettings().setLoadWithOverviewMode(true);
5188 // Explicitly disable geolocation.
5189 nestedScrollWebView.getSettings().setGeolocationEnabled(false);
5191 // Allow loading of file:// URLs. This is necessary for opening MHT web archives, which are copies into a temporary cache location.
5192 nestedScrollWebView.getSettings().setAllowFileAccess(true);
5194 // Create a double-tap gesture detector to toggle full-screen mode.
5195 GestureDetector doubleTapGestureDetector = new GestureDetector(getApplicationContext(), new GestureDetector.SimpleOnGestureListener() {
5196 // Override `onDoubleTap()`. All other events are handled using the default settings.
5198 public boolean onDoubleTap(MotionEvent event) {
5199 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
5200 // Toggle the full screen browsing mode tracker.
5201 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
5203 // Toggle the full screen browsing mode.
5204 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
5205 // Hide the app bar if specified.
5206 if (hideAppBar) { // The app bar is hidden.
5207 // Close the find on page bar if it is visible.
5208 closeFindOnPage(null);
5210 // Hide the tab linear layout.
5211 tabsLinearLayout.setVisibility(View.GONE);
5213 // Hide the action bar.
5216 // Set layout and scrolling parameters according to the position of the app bar.
5217 if (bottomAppBar) { // The app bar is at the bottom.
5218 // Reset the WebView padding to fill the available space.
5219 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5220 } else { // The app bar is at the top.
5221 // Check to see if the app bar is normally scrolled.
5222 if (scrollAppBar) { // The app bar is scrolled when it is displayed.
5223 // Get the swipe refresh layout parameters.
5224 CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
5226 // Remove the off-screen scrolling layout.
5227 swipeRefreshLayoutParams.setBehavior(null);
5228 } else { // The app bar is not scrolled when it is displayed.
5229 // Remove the padding from the top of the swipe refresh layout.
5230 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5232 // The swipe refresh circle must be moved above the now removed status bar location.
5233 swipeRefreshLayout.setProgressViewOffset(false, -200, defaultProgressViewEndOffset);
5236 } else { // The app bar is not hidden.
5237 // Adjust the UI for the bottom app bar.
5239 // Adjust the UI according to the scrolling of the app bar.
5241 // Reset the WebView padding to fill the available space.
5242 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5244 // Move the WebView above the app bar layout.
5245 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight);
5250 /* Hide the system bars.
5251 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5252 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5253 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5254 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5256 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5257 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5258 } else { // Switch to normal viewing mode.
5259 // Show the app bar if it was hidden.
5261 // Show the tab linear layout.
5262 tabsLinearLayout.setVisibility(View.VISIBLE);
5264 // Show the action bar.
5268 // Set layout and scrolling parameters according to the position of the app bar.
5269 if (bottomAppBar) { // The app bar is at the bottom.
5272 // Reset the WebView padding to fill the available space.
5273 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5275 // Move the WebView above the app bar layout.
5276 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight);
5278 } else { // The app bar is at the top.
5279 // Check to see if the app bar is normally scrolled.
5280 if (scrollAppBar) { // The app bar is scrolled when it is displayed.
5281 // Get the swipe refresh layout parameters.
5282 CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
5284 // Add the off-screen scrolling layout.
5285 swipeRefreshLayoutParams.setBehavior(new AppBarLayout.ScrollingViewBehavior());
5286 } else { // The app bar is not scrolled when it is displayed.
5287 // The swipe refresh layout must be manually moved below the app bar layout.
5288 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0);
5290 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5291 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight);
5295 // Remove the `SYSTEM_UI` flags from the root frame layout.
5296 rootFrameLayout.setSystemUiVisibility(0);
5299 // Consume the double-tap.
5301 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
5307 public boolean onFling(MotionEvent motionEvent1, MotionEvent motionEvent2, float velocityX, float velocityY) {
5308 // Scroll the bottom app bar if enabled.
5309 if (bottomAppBar && scrollAppBar && !objectAnimator.isRunning()) {
5310 // Calculate the Y change.
5311 float motionY = motionEvent2.getY() - motionEvent1.getY();
5313 // Scroll the app bar if the change is greater than 50 pixels.
5315 // Animate the bottom app bar onto the screen.
5316 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0);
5317 } else if (motionY < -50) {
5318 // Animate the bottom app bar off the screen.
5319 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", appBarLayout.getHeight());
5323 objectAnimator.start();
5326 // Do not consume the event.
5331 // Pass all touch events on the WebView through the double-tap gesture detector.
5332 nestedScrollWebView.setOnTouchListener((View view, MotionEvent event) -> {
5333 // Call `performClick()` on the view, which is required for accessibility.
5334 view.performClick();
5336 // Send the event to the gesture detector.
5337 return doubleTapGestureDetector.onTouchEvent(event);
5340 // Register the WebView for a context menu. This is used to see link targets and download images.
5341 registerForContextMenu(nestedScrollWebView);
5343 // Allow the downloading of files.
5344 nestedScrollWebView.setDownloadListener((String downloadUrl, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
5345 // Check the download preference.
5346 if (downloadWithExternalApp) { // Download with an external app.
5347 downloadUrlWithExternalApp(downloadUrl);
5348 } else { // Handle the download inside of Privacy Browser.
5349 // Define a formatted file size string.
5350 String formattedFileSizeString;
5352 // Process the content length if it contains data.
5353 if (contentLength > 0) { // The content length is greater than 0.
5354 // Format the content length as a string.
5355 formattedFileSizeString = NumberFormat.getInstance().format(contentLength) + " " + getString(R.string.bytes);
5356 } else { // The content length is not greater than 0.
5357 // Set the formatted file size string to be `unknown size`.
5358 formattedFileSizeString = getString(R.string.unknown_size);
5361 // Get the file name from the content disposition.
5362 String fileNameString = PrepareSaveDialog.getFileNameFromHeaders(this, contentDisposition, mimetype, downloadUrl);
5364 // Instantiate the save dialog.
5365 DialogFragment saveDialogFragment = SaveDialog.saveUrl(downloadUrl, formattedFileSizeString, fileNameString, userAgent,
5366 nestedScrollWebView.getAcceptCookies());
5368 // Try to show the dialog. The download listener continues to function even when the WebView is paused. Attempting to display a dialog in that state leads to a crash.
5370 // Show the save dialog. It must be named `save_dialog` so that the file picker can update the file name.
5371 saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
5372 } catch (Exception exception) { // The dialog could not be shown.
5373 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
5374 pendingDialogsArrayList.add(new PendingDialog(saveDialogFragment, getString(R.string.save_dialog)));
5379 // Update the find on page count.
5380 nestedScrollWebView.setFindListener(new WebView.FindListener() {
5381 // Get a handle for `findOnPageCountTextView`.
5382 final TextView findOnPageCountTextView = findViewById(R.id.find_on_page_count_textview);
5385 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
5386 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
5387 // Set `findOnPageCountTextView` to `0/0`.
5388 findOnPageCountTextView.setText(R.string.zero_of_zero);
5389 } else if (isDoneCounting) { // There are matches.
5390 // `activeMatchOrdinal` is zero-based.
5391 int activeMatch = activeMatchOrdinal + 1;
5393 // Build the match string.
5394 String matchString = activeMatch + "/" + numberOfMatches;
5396 // Set `findOnPageCountTextView`.
5397 findOnPageCountTextView.setText(matchString);
5402 // Process scroll changes.
5403 nestedScrollWebView.setOnScrollChangeListener((view, scrollX, scrollY, oldScrollX, oldScrollY) -> {
5404 // Set the swipe to refresh status.
5405 if (nestedScrollWebView.getSwipeToRefresh()) {
5406 // Only enable swipe to refresh if the WebView is scrolled to the top.
5407 swipeRefreshLayout.setEnabled(nestedScrollWebView.getScrollY() == 0);
5409 // Disable swipe to refresh.
5410 swipeRefreshLayout.setEnabled(false);
5413 // Reinforce the system UI visibility flags if in full screen browsing mode.
5414 // This hides the status and navigation bars, which are displayed if other elements are shown, like dialog boxes, the options menu, or the keyboard.
5415 if (inFullScreenBrowsingMode) {
5416 /* Hide the system bars.
5417 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5418 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5419 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5420 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5422 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5423 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5427 // Set the web chrome client.
5428 nestedScrollWebView.setWebChromeClient(new WebChromeClient() {
5429 // Update the progress bar when a page is loading.
5431 public void onProgressChanged(WebView view, int progress) {
5432 // Update the progress bar.
5433 progressBar.setProgress(progress);
5435 // Set the visibility of the progress bar.
5436 if (progress < 100) {
5437 // Show the progress bar.
5438 progressBar.setVisibility(View.VISIBLE);
5440 // Hide the progress bar.
5441 progressBar.setVisibility(View.GONE);
5443 //Stop the swipe to refresh indicator if it is running
5444 swipeRefreshLayout.setRefreshing(false);
5446 // Make the current WebView visible. If this is a new tab, the current WebView would have been created invisible in `webview_framelayout` to prevent a white background splash in night mode.
5447 nestedScrollWebView.setVisibility(View.VISIBLE);
5451 // Set the favorite icon when it changes.
5453 public void onReceivedIcon(WebView view, Bitmap icon) {
5454 // Only update the favorite icon if the website has finished loading.
5455 if (progressBar.getVisibility() == View.GONE) {
5456 // Store the new favorite icon.
5457 nestedScrollWebView.setFavoriteOrDefaultIcon(icon);
5459 // Get the current page position.
5460 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5462 // Get the current tab.
5463 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
5465 // Check to see if the tab has been populated.
5467 // Get the custom view from the tab.
5468 View tabView = tab.getCustomView();
5470 // Check to see if the custom tab view has been populated.
5471 if (tabView != null) {
5472 // Get the favorite icon image view from the tab.
5473 ImageView tabFavoriteIconImageView = tabView.findViewById(R.id.favorite_icon_imageview);
5475 // Display the favorite icon in the tab.
5476 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
5482 // Save a copy of the title when it changes.
5484 public void onReceivedTitle(WebView view, String title) {
5485 // Get the current page position.
5486 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5488 // Get the current tab.
5489 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
5491 // Only populate the title text view if the tab has been fully created.
5493 // Get the custom view from the tab.
5494 View tabView = tab.getCustomView();
5496 // Only populate the title text view if the tab view has been fully populated.
5497 if (tabView != null) {
5498 // Get the title text view from the tab.
5499 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
5501 // Set the title according to the URL.
5502 if (title.equals("about:blank")) {
5503 // Set the title to indicate a new tab.
5504 tabTitleTextView.setText(R.string.new_tab);
5506 // Set the title as the tab text.
5507 tabTitleTextView.setText(title);
5513 // Enter full screen video.
5515 public void onShowCustomView(View video, CustomViewCallback callback) {
5516 // Set the full screen video flag.
5517 displayingFullScreenVideo = true;
5519 // Hide the keyboard.
5520 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
5522 // Hide the coordinator layout.
5523 coordinatorLayout.setVisibility(View.GONE);
5525 /* Hide the system bars.
5526 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5527 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5528 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5529 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5531 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5532 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5534 // Disable the sliding drawers.
5535 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
5537 // Add the video view to the full screen video frame layout.
5538 fullScreenVideoFrameLayout.addView(video);
5540 // Show the full screen video frame layout.
5541 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
5543 // Disable the screen timeout while the video is playing. YouTube does this automatically, but not all other videos do.
5544 fullScreenVideoFrameLayout.setKeepScreenOn(true);
5547 // Exit full screen video.
5549 public void onHideCustomView() {
5550 // Exit the full screen video.
5551 exitFullScreenVideo();
5556 public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
5557 // Store the file path callback.
5558 fileChooserCallback = filePathCallback;
5560 // Create an intent to open a chooser based on the file chooser parameters.
5561 Intent fileChooserIntent = fileChooserParams.createIntent();
5563 // Get a handle for the package manager.
5564 PackageManager packageManager = getPackageManager();
5566 // Check to see if the file chooser intent resolves to an installed package.
5567 if (fileChooserIntent.resolveActivity(packageManager) != null) { // The file chooser intent is fine.
5568 // Start the file chooser intent.
5569 startActivityForResult(fileChooserIntent, BROWSE_FILE_UPLOAD_REQUEST_CODE);
5570 } else { // The file chooser intent will cause a crash.
5571 // Create a generic intent to open a chooser.
5572 Intent genericFileChooserIntent = new Intent(Intent.ACTION_GET_CONTENT);
5574 // Request an openable file.
5575 genericFileChooserIntent.addCategory(Intent.CATEGORY_OPENABLE);
5577 // Set the file type to everything.
5578 genericFileChooserIntent.setType("*/*");
5580 // Start the generic file chooser intent.
5581 startActivityForResult(genericFileChooserIntent, BROWSE_FILE_UPLOAD_REQUEST_CODE);
5587 nestedScrollWebView.setWebViewClient(new WebViewClient() {
5588 // `shouldOverrideUrlLoading` makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
5589 // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
5591 public boolean shouldOverrideUrlLoading(WebView view, String url) {
5592 // Sanitize the url.
5593 url = sanitizeUrl(url);
5595 // Handle the URL according to the type.
5596 if (url.startsWith("http")) { // Load the URL in Privacy Browser.
5597 // Load the URL. By using `loadUrl()`, instead of `loadUrlFromBase()`, the Referer header will never be sent.
5598 loadUrl(nestedScrollWebView, url);
5600 // Returning true indicates that Privacy Browser is manually handling the loading of the URL.
5601 // Custom headers cannot be added if false is returned and the WebView handles the loading of the URL.
5603 } else if (url.startsWith("mailto:")) { // Load the email address in an external email program.
5604 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
5605 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
5607 // Parse the url and set it as the data for the intent.
5608 emailIntent.setData(Uri.parse(url));
5610 // Open the email program in a new task instead of as part of Privacy Browser.
5611 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5615 startActivity(emailIntent);
5616 } catch (ActivityNotFoundException exception) {
5617 // Display a snackbar.
5618 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
5622 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5624 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
5625 // Open the dialer and load the phone number, but wait for the user to place the call.
5626 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
5628 // Add the phone number to the intent.
5629 dialIntent.setData(Uri.parse(url));
5631 // Open the dialer in a new task instead of as part of Privacy Browser.
5632 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5636 startActivity(dialIntent);
5637 } catch (ActivityNotFoundException exception) {
5638 // Display a snackbar.
5639 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
5642 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5644 } else { // Load a system chooser to select an app that can handle the URL.
5645 // Open an app that can handle the URL.
5646 Intent genericIntent = new Intent(Intent.ACTION_VIEW);
5648 // Add the URL to the intent.
5649 genericIntent.setData(Uri.parse(url));
5651 // List all apps that can handle the URL instead of just opening the first one.
5652 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
5654 // Open the app in a new task instead of as part of Privacy Browser.
5655 genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5657 // Start the app or display a snackbar if no app is available to handle the URL.
5659 startActivity(genericIntent);
5660 } catch (ActivityNotFoundException exception) {
5661 Snackbar.make(nestedScrollWebView, getString(R.string.unrecognized_url) + " " + url, Snackbar.LENGTH_SHORT).show();
5664 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5669 // Check requests against the block lists. The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
5671 public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest webResourceRequest) {
5673 String url = webResourceRequest.getUrl().toString();
5675 // Check to see if the resource request is for the main URL.
5676 if (url.equals(nestedScrollWebView.getCurrentUrl())) {
5677 // `return null` loads the resource request, which should never be blocked if it is the main URL.
5681 // Wait until the blocklists have been populated. When Privacy Browser is being resumed after having the process killed in the background it will try to load the URLs immediately.
5682 while (ultraPrivacy == null) {
5683 // The wait must be synchronized, which only lets one thread run on it at a time, or `java.lang.IllegalMonitorStateException` is thrown.
5684 synchronized (this) {
5686 // Check to see if the blocklists have been populated after 100 ms.
5688 } catch (InterruptedException exception) {
5694 // Create an empty web resource response to be used if the resource request is blocked.
5695 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
5697 // Reset the whitelist results tracker.
5698 String[] whitelistResultStringArray = null;
5700 // Initialize the third party request tracker.
5701 boolean isThirdPartyRequest = false;
5703 // Get the current URL. `.getUrl()` throws an error because operations on the WebView cannot be made from this thread.
5704 String currentBaseDomain = nestedScrollWebView.getCurrentDomainName();
5706 // Store a copy of the current domain for use in later requests.
5707 String currentDomain = currentBaseDomain;
5709 // Get the request host name.
5710 String requestBaseDomain = webResourceRequest.getUrl().getHost();
5712 // Only check for third-party requests if the current base domain is not empty and the request domain is not null.
5713 if (!currentBaseDomain.isEmpty() && (requestBaseDomain != null)) {
5714 // Determine the current base domain.
5715 while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
5716 // Remove the first subdomain.
5717 currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
5720 // Determine the request base domain.
5721 while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
5722 // Remove the first subdomain.
5723 requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
5726 // Update the third party request tracker.
5727 isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
5730 // Get the current WebView page position.
5731 int webViewPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5733 // Determine if the WebView is currently displayed.
5734 boolean webViewDisplayed = (webViewPagePosition == tabLayout.getSelectedTabPosition());
5736 // Block third-party requests if enabled.
5737 if (isThirdPartyRequest && nestedScrollWebView.getBlockAllThirdPartyRequests()) {
5738 // Add the result to the resource requests.
5739 nestedScrollWebView.addResourceRequest(new String[]{BlocklistHelper.REQUEST_THIRD_PARTY, url});
5741 // Increment the blocked requests counters.
5742 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5743 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS);
5745 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5746 if (webViewDisplayed) {
5747 // Updating the UI must be run from the UI thread.
5748 activity.runOnUiThread(() -> {
5749 // Update the menu item titles.
5750 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5752 // Update the options menu if it has been populated.
5753 if (optionsMenu != null) {
5754 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5755 optionsBlockAllThirdPartyRequestsMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " +
5756 getString(R.string.block_all_third_party_requests));
5761 // Return an empty web resource response.
5762 return emptyWebResourceResponse;
5765 // Check UltraList if it is enabled.
5766 if (nestedScrollWebView.getUltraListEnabled()) {
5767 // Check the URL against UltraList.
5768 String[] ultraListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraList);
5770 // Process the UltraList results.
5771 if (ultraListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched UltraList's blacklist.
5772 // Add the result to the resource requests.
5773 nestedScrollWebView.addResourceRequest(new String[] {ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]});
5775 // Increment the blocked requests counters.
5776 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5777 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRALIST);
5779 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5780 if (webViewDisplayed) {
5781 // Updating the UI must be run from the UI thread.
5782 activity.runOnUiThread(() -> {
5783 // Update the menu item titles.
5784 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5786 // Update the options menu if it has been populated.
5787 if (optionsMenu != null) {
5788 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5789 optionsUltraListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRALIST) + " - " + getString(R.string.ultralist));
5794 // The resource request was blocked. Return an empty web resource response.
5795 return emptyWebResourceResponse;
5796 } else if (ultraListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched UltraList's whitelist.
5797 // Add a whitelist entry to the resource requests array.
5798 nestedScrollWebView.addResourceRequest(new String[] {ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]});
5800 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
5805 // Check UltraPrivacy if it is enabled.
5806 if (nestedScrollWebView.getUltraPrivacyEnabled()) {
5807 // Check the URL against UltraPrivacy.
5808 String[] ultraPrivacyResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraPrivacy);
5810 // Process the UltraPrivacy results.
5811 if (ultraPrivacyResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched UltraPrivacy's blacklist.
5812 // Add the result to the resource requests.
5813 nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5814 ultraPrivacyResults[5]});
5816 // Increment the blocked requests counters.
5817 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5818 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRAPRIVACY);
5820 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5821 if (webViewDisplayed) {
5822 // Updating the UI must be run from the UI thread.
5823 activity.runOnUiThread(() -> {
5824 // Update the menu item titles.
5825 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5827 // Update the options menu if it has been populated.
5828 if (optionsMenu != null) {
5829 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5830 optionsUltraPrivacyMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRAPRIVACY) + " - " + getString(R.string.ultraprivacy));
5835 // The resource request was blocked. Return an empty web resource response.
5836 return emptyWebResourceResponse;
5837 } else if (ultraPrivacyResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched UltraPrivacy's whitelist.
5838 // Add a whitelist entry to the resource requests array.
5839 nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5840 ultraPrivacyResults[5]});
5842 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
5847 // Check EasyList if it is enabled.
5848 if (nestedScrollWebView.getEasyListEnabled()) {
5849 // Check the URL against EasyList.
5850 String[] easyListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyList);
5852 // Process the EasyList results.
5853 if (easyListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched EasyList's blacklist.
5854 // Add the result to the resource requests.
5855 nestedScrollWebView.addResourceRequest(new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]});
5857 // Increment the blocked requests counters.
5858 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5859 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASYLIST);
5861 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5862 if (webViewDisplayed) {
5863 // Updating the UI must be run from the UI thread.
5864 activity.runOnUiThread(() -> {
5865 // Update the menu item titles.
5866 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5868 // Update the options menu if it has been populated.
5869 if (optionsMenu != null) {
5870 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5871 optionsEasyListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASYLIST) + " - " + getString(R.string.easylist));
5876 // The resource request was blocked. Return an empty web resource response.
5877 return emptyWebResourceResponse;
5878 } else if (easyListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched EasyList's whitelist.
5879 // Update the whitelist result string array tracker.
5880 whitelistResultStringArray = new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]};
5884 // Check EasyPrivacy if it is enabled.
5885 if (nestedScrollWebView.getEasyPrivacyEnabled()) {
5886 // Check the URL against EasyPrivacy.
5887 String[] easyPrivacyResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyPrivacy);
5889 // Process the EasyPrivacy results.
5890 if (easyPrivacyResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched EasyPrivacy's blacklist.
5891 // Add the result to the resource requests.
5892 nestedScrollWebView.addResourceRequest(new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4],
5893 easyPrivacyResults[5]});
5895 // Increment the blocked requests counters.
5896 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5897 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASYPRIVACY);
5899 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5900 if (webViewDisplayed) {
5901 // Updating the UI must be run from the UI thread.
5902 activity.runOnUiThread(() -> {
5903 // Update the menu item titles.
5904 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5906 // Update the options menu if it has been populated.
5907 if (optionsMenu != null) {
5908 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5909 optionsEasyPrivacyMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASYPRIVACY) + " - " + getString(R.string.easyprivacy));
5914 // The resource request was blocked. Return an empty web resource response.
5915 return emptyWebResourceResponse;
5916 } else if (easyPrivacyResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched EasyPrivacy's whitelist.
5917 // Update the whitelist result string array tracker.
5918 whitelistResultStringArray = new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5]};
5922 // Check Fanboy’s Annoyance List if it is enabled.
5923 if (nestedScrollWebView.getFanboysAnnoyanceListEnabled()) {
5924 // Check the URL against Fanboy's Annoyance List.
5925 String[] fanboysAnnoyanceListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList);
5927 // Process the Fanboy's Annoyance List results.
5928 if (fanboysAnnoyanceListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched Fanboy's Annoyance List's blacklist.
5929 // Add the result to the resource requests.
5930 nestedScrollWebView.addResourceRequest(new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5931 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]});
5933 // Increment the blocked requests counters.
5934 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5935 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST);
5937 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5938 if (webViewDisplayed) {
5939 // Updating the UI must be run from the UI thread.
5940 activity.runOnUiThread(() -> {
5941 // Update the menu item titles.
5942 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5944 // Update the options menu if it has been populated.
5945 if (optionsMenu != null) {
5946 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5947 optionsFanboysAnnoyanceListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " +
5948 getString(R.string.fanboys_annoyance_list));
5953 // The resource request was blocked. Return an empty web resource response.
5954 return emptyWebResourceResponse;
5955 } else if (fanboysAnnoyanceListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)){ // The resource request matched Fanboy's Annoyance List's whitelist.
5956 // Update the whitelist result string array tracker.
5957 whitelistResultStringArray = new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5958 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]};
5960 } else if (nestedScrollWebView.getFanboysSocialBlockingListEnabled()) { // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
5961 // Check the URL against Fanboy's Annoyance List.
5962 String[] fanboysSocialListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysSocialList);
5964 // Process the Fanboy's Social Blocking List results.
5965 if (fanboysSocialListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched Fanboy's Social Blocking List's blacklist.
5966 // Add the result to the resource requests.
5967 nestedScrollWebView.addResourceRequest(new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5968 fanboysSocialListResults[4], fanboysSocialListResults[5]});
5970 // Increment the blocked requests counters.
5971 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5972 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST);
5974 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5975 if (webViewDisplayed) {
5976 // Updating the UI must be run from the UI thread.
5977 activity.runOnUiThread(() -> {
5978 // Update the menu item titles.
5979 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5981 // Update the options menu if it has been populated.
5982 if (optionsMenu != null) {
5983 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5984 optionsFanboysSocialBlockingListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " +
5985 getString(R.string.fanboys_social_blocking_list));
5990 // The resource request was blocked. Return an empty web resource response.
5991 return emptyWebResourceResponse;
5992 } else if (fanboysSocialListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched Fanboy's Social Blocking List's whitelist.
5993 // Update the whitelist result string array tracker.
5994 whitelistResultStringArray = new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5995 fanboysSocialListResults[4], fanboysSocialListResults[5]};
5999 // Add the request to the log because it hasn't been processed by any of the previous checks.
6000 if (whitelistResultStringArray != null) { // The request was processed by a whitelist.
6001 nestedScrollWebView.addResourceRequest(whitelistResultStringArray);
6002 } else { // The request didn't match any blocklist entry. Log it as a default request.
6003 nestedScrollWebView.addResourceRequest(new String[]{BlocklistHelper.REQUEST_DEFAULT, url});
6006 // The resource request has not been blocked. `return null` loads the requested resource.
6010 // Handle HTTP authentication requests.
6012 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
6013 // Store the handler.
6014 nestedScrollWebView.setHttpAuthHandler(handler);
6016 // Instantiate an HTTP authentication dialog.
6017 DialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm, nestedScrollWebView.getWebViewFragmentId());
6019 // Show the HTTP authentication dialog.
6020 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
6024 public void onPageStarted(WebView view, String url, Bitmap favicon) {
6025 // Get the app bar layout height. This can't be done in `applyAppSettings()` because the app bar is not yet populated there.
6026 // This should only be populated if it is greater than 0 because otherwise it will be reset to 0 if the app bar is hidden in full screen browsing mode.
6027 if (appBarLayout.getHeight() > 0) appBarHeight = appBarLayout.getHeight();
6029 // Set the padding and layout settings according to the position of the app bar.
6030 if (bottomAppBar) { // The app bar is on the bottom.
6032 if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) { // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
6033 // Reset the WebView padding to fill the available space.
6034 swipeRefreshLayout.setPadding(0, 0, 0, 0);
6035 } else { // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
6036 // Move the WebView above the app bar layout.
6037 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight);
6039 } else { // The app bar is on the top.
6040 // Set the top padding of the swipe refresh layout according to the app bar scrolling preference. This can't be done in `appAppSettings()` because the app bar is not yet populated there.
6041 if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) {
6042 // No padding is needed because it will automatically be placed below the app bar layout due to the scrolling layout behavior.
6043 swipeRefreshLayout.setPadding(0, 0, 0, 0);
6045 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
6046 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10, defaultProgressViewEndOffset);
6048 // The swipe refresh layout must be manually moved below the app bar layout.
6049 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0);
6051 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
6052 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight);
6056 // Reset the list of resource requests.
6057 nestedScrollWebView.clearResourceRequests();
6059 // Reset the requests counters.
6060 nestedScrollWebView.resetRequestsCounters();
6062 // Get the current page position.
6063 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
6065 // Update the URL text bar if the page is currently selected and the URL edit text is not currently being edited.
6066 if ((tabLayout.getSelectedTabPosition() == currentPagePosition) && !urlEditText.hasFocus()) {
6067 // Display the formatted URL text.
6068 urlEditText.setText(url);
6070 // Apply text highlighting to the URL text box.
6073 // Hide the keyboard.
6074 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
6077 // Reset the list of host IP addresses.
6078 nestedScrollWebView.setCurrentIpAddresses("");
6080 // Get a URI for the current URL.
6081 Uri currentUri = Uri.parse(url);
6083 // Get the IP addresses for the host.
6084 new GetHostIpAddresses(activity, getSupportFragmentManager(), nestedScrollWebView).execute(currentUri.getHost());
6086 // Replace Refresh with Stop if the options menu has been created. (The first WebView typically begins loading before the menu items are instantiated.)
6087 if (optionsMenu != null) {
6089 optionsRefreshMenuItem.setTitle(R.string.stop);
6091 // Set the icon if it is displayed in the AppBar.
6092 if (displayAdditionalAppBarIcons)
6093 optionsRefreshMenuItem.setIcon(R.drawable.close_blue);
6098 public void onPageFinished(WebView view, String url) {
6099 // Flush any cookies to persistent storage. The cookie manager has become very lazy about flushing cookies in recent versions.
6100 if (nestedScrollWebView.getAcceptCookies()) {
6101 CookieManager.getInstance().flush();
6104 // Update the Refresh menu item if the options menu has been created.
6105 if (optionsMenu != null) {
6106 // Reset the Refresh title.
6107 optionsRefreshMenuItem.setTitle(R.string.refresh);
6109 // Reset the icon if it is displayed in the app bar.
6110 if (displayAdditionalAppBarIcons)
6111 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled);
6114 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
6115 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
6116 String privateDataDirectoryString = getApplicationInfo().dataDir;
6118 // Clear the cache, history, and logcat if Incognito Mode is enabled.
6119 if (incognitoModeEnabled) {
6120 // Clear the cache. `true` includes disk files.
6121 nestedScrollWebView.clearCache(true);
6123 // Clear the back/forward history.
6124 nestedScrollWebView.clearHistory();
6126 // Manually delete cache folders.
6128 // Delete the main cache directory.
6129 Runtime.getRuntime().exec("rm -rf " + privateDataDirectoryString + "/cache");
6130 } catch (IOException exception) {
6131 // Do nothing if an error is thrown.
6134 // Clear the logcat.
6136 // Clear the logcat. `-c` clears the logcat. `-b all` clears all the buffers (instead of just crash, main, and system).
6137 Runtime.getRuntime().exec("logcat -b all -c");
6138 } catch (IOException exception) {
6143 // Clear the `Service Worker` directory.
6145 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
6146 Runtime.getRuntime().exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Default/Service Worker/"});
6147 } catch (IOException exception) {
6151 // Get the current page position.
6152 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
6154 // 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.
6155 String currentUrl = nestedScrollWebView.getUrl();
6157 // Get the current tab.
6158 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
6160 // Update the URL text bar if the page is currently selected and the user is not currently typing in the URL edit text.
6161 // Crash records show that, in some crazy way, it is possible for the current URL to be blank at this point.
6162 // Probably some sort of race condition when Privacy Browser is being resumed.
6163 if ((tabLayout.getSelectedTabPosition() == currentPagePosition) && !urlEditText.hasFocus() && (currentUrl != null)) {
6164 // Check to see if the URL is `about:blank`.
6165 if (currentUrl.equals("about:blank")) { // The WebView is blank.
6166 // Display the hint in the URL edit text.
6167 urlEditText.setText("");
6169 // Request focus for the URL text box.
6170 urlEditText.requestFocus();
6172 // Display the keyboard.
6173 inputMethodManager.showSoftInput(urlEditText, 0);
6175 // Apply the domain settings. This clears any settings from the previous domain.
6176 applyDomainSettings(nestedScrollWebView, "", true, false, false);
6178 // Only populate the title text view if the tab has been fully created.
6180 // Get the custom view from the tab.
6181 View tabView = tab.getCustomView();
6183 // Remove the incorrect warning below that the current tab view might be null.
6184 assert tabView != null;
6186 // Get the title text view from the tab.
6187 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
6189 // Set the title as the tab text.
6190 tabTitleTextView.setText(R.string.new_tab);
6192 } else { // The WebView has loaded a webpage.
6193 // Update the URL edit text if it is not currently being edited.
6194 if (!urlEditText.hasFocus()) {
6195 // Sanitize the current URL. This removes unwanted URL elements that were added by redirects, so that they won't be included if the URL is shared.
6196 String sanitizedUrl = sanitizeUrl(currentUrl);
6198 // Display the final URL. Getting the URL from the WebView instead of using the one provided by `onPageFinished()` makes websites like YouTube function correctly.
6199 urlEditText.setText(sanitizedUrl);
6201 // Apply text highlighting to the URL.
6205 // Only populate the title text view if the tab has been fully created.
6207 // Get the custom view from the tab.
6208 View tabView = tab.getCustomView();
6210 // Remove the incorrect warning below that the current tab view might be null.
6211 assert tabView != null;
6213 // Get the title text view from the tab.
6214 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
6216 // Set the title as the tab text. Sometimes `onReceivedTitle()` is not called, especially when navigating history.
6217 tabTitleTextView.setText(nestedScrollWebView.getTitle());
6223 // Handle SSL Certificate errors. Suppress the lint warning that ignoring the error might be dangerous.
6224 @SuppressLint("WebViewClientOnReceivedSslError")
6226 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
6227 // Get the current website SSL certificate.
6228 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
6230 // Extract the individual pieces of information from the current website SSL certificate.
6231 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
6232 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
6233 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
6234 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
6235 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
6236 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
6237 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
6238 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
6240 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
6241 if (nestedScrollWebView.hasPinnedSslCertificate()) {
6242 // Get the pinned SSL certificate.
6243 Pair<String[], Date[]> pinnedSslCertificatePair = nestedScrollWebView.getPinnedSslCertificate();
6245 // Extract the arrays from the array list.
6246 String[] pinnedSslCertificateStringArray = pinnedSslCertificatePair.getFirst();
6247 Date[] pinnedSslCertificateDateArray = pinnedSslCertificatePair.getSecond();
6249 // Check if the current SSL certificate matches the pinned certificate.
6250 if (currentWebsiteIssuedToCName.equals(pinnedSslCertificateStringArray[0]) && currentWebsiteIssuedToOName.equals(pinnedSslCertificateStringArray[1]) &&
6251 currentWebsiteIssuedToUName.equals(pinnedSslCertificateStringArray[2]) && currentWebsiteIssuedByCName.equals(pinnedSslCertificateStringArray[3]) &&
6252 currentWebsiteIssuedByOName.equals(pinnedSslCertificateStringArray[4]) && currentWebsiteIssuedByUName.equals(pinnedSslCertificateStringArray[5]) &&
6253 currentWebsiteSslStartDate.equals(pinnedSslCertificateDateArray[0]) && currentWebsiteSslEndDate.equals(pinnedSslCertificateDateArray[1])) {
6255 // An SSL certificate is pinned and matches the current domain certificate. Proceed to the website without displaying an error.
6258 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
6259 // Store the SSL error handler.
6260 nestedScrollWebView.setSslErrorHandler(handler);
6262 // Instantiate an SSL certificate error alert dialog.
6263 DialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error, nestedScrollWebView.getWebViewFragmentId());
6265 // Try to show the dialog. The SSL error handler continues to function even when the WebView is paused. Attempting to display a dialog in that state leads to a crash.
6267 // Show the SSL certificate error dialog.
6268 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
6269 } catch (Exception exception) {
6270 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
6271 pendingDialogsArrayList.add(new PendingDialog(sslCertificateErrorDialogFragment, getString(R.string.ssl_certificate_error)));
6277 // Check to see if the state is being restored.
6278 if (restoringState) { // The state is being restored.
6279 // Resume the nested scroll WebView JavaScript timers.
6280 nestedScrollWebView.resumeTimers();
6281 } else if (pageNumber == 0) { // The first page is being loaded.
6282 // Set this nested scroll WebView as the current WebView.
6283 currentWebView = nestedScrollWebView;
6285 // Initialize the URL to load string.
6286 String urlToLoadString;
6288 // Get the intent that started the app.
6289 Intent launchingIntent = getIntent();
6291 // Reset the intent. This prevents a duplicate tab from being created on restart.
6292 setIntent(new Intent());
6294 // Get the information from the intent.
6295 String launchingIntentAction = launchingIntent.getAction();
6296 Uri launchingIntentUriData = launchingIntent.getData();
6297 String launchingIntentStringExtra = launchingIntent.getStringExtra(Intent.EXTRA_TEXT);
6299 // Parse the launching intent URL.
6300 if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) { // The intent contains a search string.
6301 // Create an encoded URL string.
6302 String encodedUrlString;
6304 // Sanitize the search input and convert it to a search.
6306 encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
6307 } catch (UnsupportedEncodingException exception) {
6308 encodedUrlString = "";
6311 // Store the web search as the URL to load.
6312 urlToLoadString = searchURL + encodedUrlString;
6313 } else if (launchingIntentUriData != null) { // The launching intent contains a URL formatted as a URI.
6314 // Store the URI as a URL.
6315 urlToLoadString = launchingIntentUriData.toString();
6316 } else if (launchingIntentStringExtra != null) { // The launching intent contains text that might be a URL.
6318 urlToLoadString = launchingIntentStringExtra;
6319 } else if (!url.equals("")) { // The activity has been restarted.
6320 // Load the saved URL.
6321 urlToLoadString = url;
6322 } else { // The is no URL in the intent.
6323 // Store the homepage to be loaded.
6324 urlToLoadString = sharedPreferences.getString("homepage", getString(R.string.homepage_default_value));
6327 // Load the website if not waiting for the proxy.
6328 if (waitingForProxy) { // Store the URL to be loaded in the Nested Scroll WebView.
6329 nestedScrollWebView.setWaitingForProxyUrlString(urlToLoadString);
6330 } else { // Load the URL.
6331 loadUrl(nestedScrollWebView, urlToLoadString);
6334 // Reset the intent. This prevents a duplicate tab from being created on a subsequent restart if loading an link from a new intent on restart.
6335 // For example, this prevents a duplicate tab if a link is loaded from the Guide after changing the theme in the guide and then changing the theme again in the main activity.
6336 setIntent(new Intent());
6337 } else { // This is not the first tab.
6339 loadUrl(nestedScrollWebView, url);
6341 // Set the focus and display the keyboard if the URL is blank.
6342 if (url.equals("")) {
6343 // Request focus for the URL text box.
6344 urlEditText.requestFocus();
6346 // Create a display keyboard handler.
6347 Handler displayKeyboardHandler = new Handler();
6349 // Create a display keyboard runnable.
6350 Runnable displayKeyboardRunnable = () -> {
6351 // Display the keyboard.
6352 inputMethodManager.showSoftInput(urlEditText, 0);
6355 // Display the keyboard after 100 milliseconds, which leaves enough time for the tab to transition.
6356 displayKeyboardHandler.postDelayed(displayKeyboardRunnable, 100);