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.print.PrintDocumentAdapter;
56 import android.print.PrintManager;
57 import android.provider.DocumentsContract;
58 import android.provider.OpenableColumns;
59 import android.text.Editable;
60 import android.text.Spanned;
61 import android.text.TextWatcher;
62 import android.text.style.ForegroundColorSpan;
63 import android.util.Patterns;
64 import android.util.TypedValue;
65 import android.view.ContextMenu;
66 import android.view.GestureDetector;
67 import android.view.KeyEvent;
68 import android.view.Menu;
69 import android.view.MenuItem;
70 import android.view.MotionEvent;
71 import android.view.View;
72 import android.view.ViewGroup;
73 import android.view.WindowManager;
74 import android.view.inputmethod.InputMethodManager;
75 import android.webkit.CookieManager;
76 import android.webkit.HttpAuthHandler;
77 import android.webkit.SslErrorHandler;
78 import android.webkit.ValueCallback;
79 import android.webkit.WebBackForwardList;
80 import android.webkit.WebChromeClient;
81 import android.webkit.WebResourceRequest;
82 import android.webkit.WebResourceResponse;
83 import android.webkit.WebSettings;
84 import android.webkit.WebStorage;
85 import android.webkit.WebView;
86 import android.webkit.WebViewClient;
87 import android.webkit.WebViewDatabase;
88 import android.widget.ArrayAdapter;
89 import android.widget.CheckBox;
90 import android.widget.CursorAdapter;
91 import android.widget.EditText;
92 import android.widget.FrameLayout;
93 import android.widget.ImageView;
94 import android.widget.LinearLayout;
95 import android.widget.ListView;
96 import android.widget.ProgressBar;
97 import android.widget.RadioButton;
98 import android.widget.RelativeLayout;
99 import android.widget.TextView;
101 import androidx.activity.OnBackPressedCallback;
102 import androidx.activity.result.ActivityResultCallback;
103 import androidx.activity.result.ActivityResultLauncher;
104 import androidx.activity.result.contract.ActivityResultContracts;
105 import androidx.annotation.NonNull;
106 import androidx.appcompat.app.ActionBar;
107 import androidx.appcompat.app.ActionBarDrawerToggle;
108 import androidx.appcompat.app.AppCompatActivity;
109 import androidx.appcompat.app.AppCompatDelegate;
110 import androidx.appcompat.widget.Toolbar;
111 import androidx.coordinatorlayout.widget.CoordinatorLayout;
112 import androidx.core.content.res.ResourcesCompat;
113 import androidx.core.view.GravityCompat;
114 import androidx.drawerlayout.widget.DrawerLayout;
115 import androidx.fragment.app.DialogFragment;
116 import androidx.fragment.app.Fragment;
117 import androidx.preference.PreferenceManager;
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 final ExecutorService executorService = Executors.newFixedThreadPool(4);
194 public static String orbotStatus = "unknown";
195 public static final 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) {
394 // Initialize the file name string from the file URI last path segment.
395 String temporaryFileNameString = fileUri.getLastPathSegment();
397 // Query the exact file name if the API >= 26.
398 if (Build.VERSION.SDK_INT >= 26) {
399 // Get a cursor from the content resolver.
400 Cursor contentResolverCursor = resultLauncherActivityHandle.getContentResolver().query(fileUri, null, null, null);
402 // Move to the fist row.
403 contentResolverCursor.moveToFirst();
405 // Get the file name from the cursor.
406 temporaryFileNameString = contentResolverCursor.getString(contentResolverCursor.getColumnIndexOrThrow(OpenableColumns.DISPLAY_NAME));
409 contentResolverCursor.close();
412 // Save the final file name string so it can be used inside the lambdas. This will no longer be needed once this activity has transitioned to Kotlin.
413 String finalFileNameString = temporaryFileNameString;
416 // Create a temporary MHT file.
417 File temporaryMhtFile = File.createTempFile("temporary_mht_file", ".mht", getCacheDir());
418 currentWebView.saveWebArchive(temporaryMhtFile.toString(), false, callbackValue -> {
419 if (callbackValue != null) { // The temporary MHT file was saved successfully.
421 // Create a temporary MHT file input stream.
422 FileInputStream temporaryMhtFileInputStream = new FileInputStream(temporaryMhtFile);
424 // Get an output stream for the save webpage file path.
425 OutputStream mhtOutputStream = getContentResolver().openOutputStream(fileUri);
427 // Create a transfer byte array.
428 byte[] transferByteArray = new byte[1024];
430 // Create an integer to track the number of bytes read.
433 // Copy the temporary MHT file input stream to the MHT output stream.
434 while ((bytesRead = temporaryMhtFileInputStream.read(transferByteArray)) > 0) {
435 mhtOutputStream.write(transferByteArray, 0, bytesRead);
438 // Close the streams.
439 mhtOutputStream.close();
440 temporaryMhtFileInputStream.close();
442 // Display a snackbar.
443 Snackbar.make(currentWebView, getString(R.string.saved, finalFileNameString), Snackbar.LENGTH_SHORT).show();
444 } catch (Exception exception) {
445 // Display a snackbar with the exception.
446 Snackbar.make(currentWebView, getString(R.string.error_saving_file, finalFileNameString, exception), Snackbar.LENGTH_INDEFINITE).show();
448 // Delete the temporary MHT file.
449 //noinspection ResultOfMethodCallIgnored
450 temporaryMhtFile.delete();
452 } else { // There was an unspecified error while saving the temporary MHT file.
453 // Display an error snackbar.
454 Snackbar.make(currentWebView, getString(R.string.error_saving_file, finalFileNameString, getString(R.string.unknown_error)), Snackbar.LENGTH_INDEFINITE).show();
457 } catch (IOException ioException) {
458 // Display a snackbar with the IO exception.
459 Snackbar.make(currentWebView, getString(R.string.error_saving_file, finalFileNameString, ioException), Snackbar.LENGTH_INDEFINITE).show();
465 // Define the save webpage image activity result launcher. It must be defined before `onCreate()` is run or the app will crash.
466 private final ActivityResultLauncher<String> saveWebpageImageActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.CreateDocument("image/png"),
467 new ActivityResultCallback<Uri>() {
469 public void onActivityResult(Uri fileUri) {
470 // Only save the webpage image if the file URI is not null, which happens if the user exited the file picker by pressing back.
471 if (fileUri != null) {
472 // Save the webpage image.
473 new SaveWebpageImage(resultLauncherActivityHandle, fileUri, currentWebView).execute();
478 // Remove the warning about needing to override `performClick()` when using an `OnTouchListener` with WebView.
479 @SuppressLint("ClickableViewAccessibility")
481 protected void onCreate(Bundle savedInstanceState) {
482 // Run the default commands.
483 super.onCreate(savedInstanceState);
485 // Populate the result launcher activity. This will no longer be needed once the activity has transitioned to Kotlin.
486 resultLauncherActivityHandle = this;
488 // Check to see if the activity has been restarted.
489 if (savedInstanceState != null) {
490 // Store the saved instance state variables.
491 savedStateArrayList = savedInstanceState.getParcelableArrayList(SAVED_STATE_ARRAY_LIST);
492 savedNestedScrollWebViewStateArrayList = savedInstanceState.getParcelableArrayList(SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST);
493 savedTabPosition = savedInstanceState.getInt(SAVED_TAB_POSITION);
494 savedProxyMode = savedInstanceState.getString(PROXY_MODE);
497 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
498 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
500 // Get a handle for the shared preferences.
501 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
503 // Get the preferences.
504 String appTheme = sharedPreferences.getString(getString(R.string.app_theme_key), getString(R.string.app_theme_default_value));
505 boolean allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false);
506 bottomAppBar = sharedPreferences.getBoolean(getString(R.string.bottom_app_bar_key), false);
507 displayAdditionalAppBarIcons = sharedPreferences.getBoolean(getString(R.string.display_additional_app_bar_icons_key), false);
509 // Get the theme entry values string array.
510 String[] appThemeEntryValuesStringArray = getResources().getStringArray(R.array.app_theme_entry_values);
512 // 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.
513 if (appTheme.equals(appThemeEntryValuesStringArray[1])) { // The light theme is selected.
514 // Apply the light theme.
515 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
516 } else if (appTheme.equals(appThemeEntryValuesStringArray[2])) { // The dark theme is selected.
517 // Apply the dark theme.
518 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
519 } else { // The system default theme is selected.
520 if (Build.VERSION.SDK_INT >= 28) { // The system default theme is supported.
521 // Follow the system default theme.
522 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
523 } else { // The system default theme is not supported.
524 // Follow the battery saver mode.
525 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY);
529 // Disable screenshots if not allowed.
530 if (!allowScreenshots) {
531 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
534 // 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.
535 WebView.enableSlowWholeDocumentDraw();
537 // Set the content view according to the position of the app bar.
538 if (bottomAppBar) setContentView(R.layout.main_framelayout_bottom_appbar);
539 else setContentView(R.layout.main_framelayout_top_appbar);
541 // Get handles for the views.
542 rootFrameLayout = findViewById(R.id.root_framelayout);
543 drawerLayout = findViewById(R.id.drawerlayout);
544 coordinatorLayout = findViewById(R.id.coordinatorlayout);
545 appBarLayout = findViewById(R.id.appbar_layout);
546 toolbar = findViewById(R.id.toolbar);
547 findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
548 tabsLinearLayout = findViewById(R.id.tabs_linearlayout);
549 tabLayout = findViewById(R.id.tablayout);
550 swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
551 webViewPager = findViewById(R.id.webviewpager);
552 NavigationView navigationView = findViewById(R.id.navigationview);
553 fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
555 // Get a handle for the navigation menu.
556 Menu navigationMenu = navigationView.getMenu();
558 // Get handles for the navigation menu items.
559 navigationBackMenuItem = navigationMenu.findItem(R.id.back);
560 navigationForwardMenuItem = navigationMenu.findItem(R.id.forward);
561 navigationHistoryMenuItem = navigationMenu.findItem(R.id.history);
562 navigationRequestsMenuItem = navigationMenu.findItem(R.id.requests);
564 // Listen for touches on the navigation menu.
565 navigationView.setNavigationItemSelectedListener(this);
567 // Get a handle for the app compat delegate.
568 AppCompatDelegate appCompatDelegate = getDelegate();
570 // Set the support action bar.
571 appCompatDelegate.setSupportActionBar(toolbar);
573 // Get a handle for the action bar.
574 actionBar = appCompatDelegate.getSupportActionBar();
576 // Remove the incorrect lint warning below that the action bar might be null.
577 assert actionBar != null;
579 // Add the custom layout, which shows the URL text bar.
580 actionBar.setCustomView(R.layout.url_app_bar);
581 actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
583 // Get handles for the views in the URL app bar.
584 urlRelativeLayout = findViewById(R.id.url_relativelayout);
585 urlEditText = findViewById(R.id.url_edittext);
587 // Create the hamburger icon at the start of the AppBar.
588 actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
590 // Initially disable the sliding drawers. They will be enabled once the blocklists are loaded.
591 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
593 // Initially hide the user interface so that only the blocklist loading screen is shown (if reloading).
594 drawerLayout.setVisibility(View.GONE);
596 // Initialize the web view pager adapter.
597 webViewPagerAdapter = new WebViewPagerAdapter(getSupportFragmentManager());
599 // Set the pager adapter on the web view pager.
600 webViewPager.setAdapter(webViewPagerAdapter);
602 // Store up to 100 tabs in memory.
603 webViewPager.setOffscreenPageLimit(100);
605 // Instantiate the helpers.
606 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this);
607 domainsDatabaseHelper = new DomainsDatabaseHelper(this);
608 proxyHelper = new ProxyHelper();
609 sanitizeUrlHelper = new SanitizeUrlHelper();
611 // Initialize the app.
614 // Apply the app settings from the shared preferences.
617 // Control what the system back command does.
618 OnBackPressedCallback onBackPressedCallback = new OnBackPressedCallback(true) {
620 public void handleOnBackPressed() {
621 // Process the different back options.
622 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
623 // Close the navigation drawer.
624 drawerLayout.closeDrawer(GravityCompat.START);
625 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
626 // close the bookmarks drawer.
627 drawerLayout.closeDrawer(GravityCompat.END);
628 } else if (displayingFullScreenVideo) { // A full screen video is shown.
629 // Exit the full screen video.
630 exitFullScreenVideo();
631 } else if (currentWebView.canGoBack()) { // There is at least one item in the current WebView history.
632 // Get the current web back forward list.
633 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
635 // Get the previous entry URL.
636 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
638 // Apply the domain settings.
639 applyDomainSettings(currentWebView, previousUrl, false, false, false);
642 currentWebView.goBack();
643 } else if (tabLayout.getTabCount() > 1) { // There are at least two tabs.
644 // Close the current tab.
646 } else { // There isn't anything to do in Privacy Browser.
647 // Run clear and exit.
653 // Register the on back pressed callback.
654 getOnBackPressedDispatcher().addCallback(this, onBackPressedCallback);
656 // Populate the blocklists.
657 populateBlocklists = new PopulateBlocklists(this, this).execute();
661 protected void onNewIntent(Intent intent) {
662 // Run the default commands.
663 super.onNewIntent(intent);
665 // Check to see if the app is being restarted from a saved state.
666 if (savedStateArrayList == null || savedStateArrayList.size() == 0) { // The activity is not being restarted from a saved state.
667 // Get the information from the intent.
668 String intentAction = intent.getAction();
669 Uri intentUriData = intent.getData();
670 String intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT);
672 // Determine if this is a web search.
673 boolean isWebSearch = ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH));
675 // 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.
676 if (intentUriData != null || intentStringExtra != null || isWebSearch) {
677 // Exit the full screen video if it is displayed.
678 if (displayingFullScreenVideo) {
679 // Exit full screen video mode.
680 exitFullScreenVideo();
682 // Reload the current WebView. Otherwise, it can display entirely black.
683 currentWebView.reload();
686 // Get the shared preferences.
687 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
689 // Create a URL string.
692 // If the intent action is a web search, perform the search.
693 if (isWebSearch) { // The intent is a web search.
694 // Create an encoded URL string.
695 String encodedUrlString;
697 // Sanitize the search input and convert it to a search.
699 encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
700 } catch (UnsupportedEncodingException exception) {
701 encodedUrlString = "";
704 // Add the base search URL.
705 url = searchURL + encodedUrlString;
706 } else if (intentUriData != null) { // The intent contains a URL formatted as a URI.
707 // Set the intent data as the URL.
708 url = intentUriData.toString();
709 } else { // The intent contains a string, which might be a URL.
710 // Set the intent string as the URL.
711 url = intentStringExtra;
714 // Add a new tab if specified in the preferences.
715 if (sharedPreferences.getBoolean(getString(R.string.open_intents_in_new_tab_key), true)) { // Load the URL in a new tab.
716 // Set the loading new intent flag.
717 loadingNewIntent = true;
720 addNewTab(url, true);
721 } else { // Load the URL in the current tab.
723 loadUrl(currentWebView, url);
726 // Close the navigation drawer if it is open.
727 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
728 drawerLayout.closeDrawer(GravityCompat.START);
731 // Close the bookmarks drawer if it is open.
732 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
733 drawerLayout.closeDrawer(GravityCompat.END);
736 } else { // The app has been restarted.
737 // Replace the intent that started the app with this one. This will load the tab after the others have been restored.
743 public void onRestart() {
744 // Run the default commands.
747 // Apply the app settings if returning from the Settings activity.
748 if (reapplyAppSettingsOnRestart) {
749 // Reset the reapply app settings on restart tracker.
750 reapplyAppSettingsOnRestart = false;
752 // Apply the app settings.
756 // Apply the domain settings if returning from the settings or domains activity.
757 if (reapplyDomainSettingsOnRestart) {
758 // Reset the reapply domain settings on restart tracker.
759 reapplyDomainSettingsOnRestart = false;
761 // Reapply the domain settings for each tab.
762 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
763 // Get the WebView tab fragment.
764 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
766 // Get the fragment view.
767 View fragmentView = webViewTabFragment.getView();
769 // Only reload the WebViews if they exist.
770 if (fragmentView != null) {
771 // Get the nested scroll WebView from the tab fragment.
772 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
774 // Reset the current domain name so the domain settings will be reapplied.
775 nestedScrollWebView.setCurrentDomainName("");
777 // Reapply the domain settings if the URL is not null, which can happen if an empty tab is active when returning from settings.
778 if (nestedScrollWebView.getUrl() != null) {
779 applyDomainSettings(nestedScrollWebView, nestedScrollWebView.getUrl(), false, true, false);
785 // Update the bookmarks drawer if returning from the Bookmarks activity.
786 if (restartFromBookmarksActivity) {
787 // Close the bookmarks drawer.
788 drawerLayout.closeDrawer(GravityCompat.END);
790 // Reload the bookmarks drawer.
791 loadBookmarksFolder();
793 // Reset `restartFromBookmarksActivity`.
794 restartFromBookmarksActivity = false;
797 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
798 updatePrivacyIcons(true);
801 // `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.
803 public void onStart() {
804 // Run the default commands.
807 // Resume any WebViews.
808 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
809 // Get the WebView tab fragment.
810 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
812 // Get the fragment view.
813 View fragmentView = webViewTabFragment.getView();
815 // Only resume the WebViews if they exist (they won't when the app is first created).
816 if (fragmentView != null) {
817 // Get the nested scroll WebView from the tab fragment.
818 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
820 // Resume the nested scroll WebView.
821 nestedScrollWebView.onResume();
825 // Resume the nested scroll WebView JavaScript timers. This is a global command that resumes JavaScript timers on all WebViews.
826 if (currentWebView != null) {
827 currentWebView.resumeTimers();
830 // Reapply the proxy settings if the system is using a proxy. This redisplays the appropriate alert dialog.
831 if (!proxyMode.equals(ProxyHelper.NONE)) {
835 // Reapply any system UI flags.
836 if (displayingFullScreenVideo || inFullScreenBrowsingMode) { // The system is displaying a website or a video in full screen mode.
837 /* Hide the system bars.
838 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
839 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
840 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
841 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
843 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
844 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
847 // Show any pending dialogs.
848 for (int i = 0; i < pendingDialogsArrayList.size(); i++) {
849 // Get the pending dialog from the array list.
850 PendingDialog pendingDialog = pendingDialogsArrayList.get(i);
852 // Show the pending dialog.
853 pendingDialog.dialogFragment.show(getSupportFragmentManager(), pendingDialog.tag);
856 // Clear the pending dialogs array list.
857 pendingDialogsArrayList.clear();
860 // `onStop()` runs after `onPause()`. It is used instead of `onPause()` so the commands are not called every time the screen is partially hidden.
862 public void onStop() {
863 // Run the default commands.
866 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
867 // Get the WebView tab fragment.
868 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
870 // Get the fragment view.
871 View fragmentView = webViewTabFragment.getView();
873 // Only pause the WebViews if they exist (they won't when the app is first created).
874 if (fragmentView != null) {
875 // Get the nested scroll WebView from the tab fragment.
876 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
878 // Pause the nested scroll WebView.
879 nestedScrollWebView.onPause();
883 // Pause the WebView JavaScript timers. This is a global command that pauses JavaScript on all WebViews.
884 if (currentWebView != null) {
885 currentWebView.pauseTimers();
890 public void onSaveInstanceState(@NonNull Bundle savedInstanceState) {
891 // Run the default commands.
892 super.onSaveInstanceState(savedInstanceState);
894 // Create the saved state array lists.
895 ArrayList<Bundle> savedStateArrayList = new ArrayList<>();
896 ArrayList<Bundle> savedNestedScrollWebViewStateArrayList = new ArrayList<>();
898 // Get the URLs from each tab.
899 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
900 // Get the WebView tab fragment.
901 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
903 // Get the fragment view.
904 View fragmentView = webViewTabFragment.getView();
906 if (fragmentView != null) {
907 // Get the nested scroll WebView from the tab fragment.
908 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
910 // Create saved state bundle.
911 Bundle savedStateBundle = new Bundle();
913 // Get the current states.
914 nestedScrollWebView.saveState(savedStateBundle);
915 Bundle savedNestedScrollWebViewStateBundle = nestedScrollWebView.saveNestedScrollWebViewState();
917 // Store the saved states in the array lists.
918 savedStateArrayList.add(savedStateBundle);
919 savedNestedScrollWebViewStateArrayList.add(savedNestedScrollWebViewStateBundle);
923 // Get the current tab position.
924 int currentTabPosition = tabLayout.getSelectedTabPosition();
926 // Store the saved states in the bundle.
927 savedInstanceState.putParcelableArrayList(SAVED_STATE_ARRAY_LIST, savedStateArrayList);
928 savedInstanceState.putParcelableArrayList(SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST, savedNestedScrollWebViewStateArrayList);
929 savedInstanceState.putInt(SAVED_TAB_POSITION, currentTabPosition);
930 savedInstanceState.putString(PROXY_MODE, proxyMode);
934 public void onDestroy() {
935 // Unregister the orbot status broadcast receiver if it exists.
936 if (orbotStatusBroadcastReceiver != null) {
937 this.unregisterReceiver(orbotStatusBroadcastReceiver);
940 // Close the bookmarks cursor if it exists.
941 if (bookmarksCursor != null) {
942 bookmarksCursor.close();
945 // Close the bookmarks database if it exists.
946 if (bookmarksDatabaseHelper != null) {
947 bookmarksDatabaseHelper.close();
950 // Stop populating the blocklists if the AsyncTask is running in the background.
951 if (populateBlocklists != null) {
952 populateBlocklists.cancel(true);
955 // Run the default commands.
960 public boolean onCreateOptionsMenu(Menu menu) {
961 // Inflate the menu. This adds items to the action bar if it is present.
962 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
964 // Store a handle for the options menu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons()`.
967 // Get handles for the menu items.
968 optionsPrivacyMenuItem = menu.findItem(R.id.javascript);
969 optionsRefreshMenuItem = menu.findItem(R.id.refresh);
970 MenuItem bookmarksMenuItem = menu.findItem(R.id.bookmarks);
971 optionsCookiesMenuItem = menu.findItem(R.id.cookies);
972 optionsDomStorageMenuItem = menu.findItem(R.id.dom_storage);
973 optionsSaveFormDataMenuItem = menu.findItem(R.id.save_form_data); // Form data can be removed once the minimum API >= 26.
974 optionsClearDataMenuItem = menu.findItem(R.id.clear_data);
975 optionsClearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
976 optionsClearDomStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
977 optionsClearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
978 optionsBlocklistsMenuItem = menu.findItem(R.id.blocklists);
979 optionsEasyListMenuItem = menu.findItem(R.id.easylist);
980 optionsEasyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
981 optionsFanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
982 optionsFanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
983 optionsUltraListMenuItem = menu.findItem(R.id.ultralist);
984 optionsUltraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
985 optionsBlockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
986 optionsProxyMenuItem = menu.findItem(R.id.proxy);
987 optionsProxyNoneMenuItem = menu.findItem(R.id.proxy_none);
988 optionsProxyTorMenuItem = menu.findItem(R.id.proxy_tor);
989 optionsProxyI2pMenuItem = menu.findItem(R.id.proxy_i2p);
990 optionsProxyCustomMenuItem = menu.findItem(R.id.proxy_custom);
991 optionsUserAgentMenuItem = menu.findItem(R.id.user_agent);
992 optionsUserAgentPrivacyBrowserMenuItem = menu.findItem(R.id.user_agent_privacy_browser);
993 optionsUserAgentWebViewDefaultMenuItem = menu.findItem(R.id.user_agent_webview_default);
994 optionsUserAgentFirefoxOnAndroidMenuItem = menu.findItem(R.id.user_agent_firefox_on_android);
995 optionsUserAgentChromeOnAndroidMenuItem = menu.findItem(R.id.user_agent_chrome_on_android);
996 optionsUserAgentSafariOnIosMenuItem = menu.findItem(R.id.user_agent_safari_on_ios);
997 optionsUserAgentFirefoxOnLinuxMenuItem = menu.findItem(R.id.user_agent_firefox_on_linux);
998 optionsUserAgentChromiumOnLinuxMenuItem = menu.findItem(R.id.user_agent_chromium_on_linux);
999 optionsUserAgentFirefoxOnWindowsMenuItem = menu.findItem(R.id.user_agent_firefox_on_windows);
1000 optionsUserAgentChromeOnWindowsMenuItem = menu.findItem(R.id.user_agent_chrome_on_windows);
1001 optionsUserAgentEdgeOnWindowsMenuItem = menu.findItem(R.id.user_agent_edge_on_windows);
1002 optionsUserAgentInternetExplorerOnWindowsMenuItem = menu.findItem(R.id.user_agent_internet_explorer_on_windows);
1003 optionsUserAgentSafariOnMacosMenuItem = menu.findItem(R.id.user_agent_safari_on_macos);
1004 optionsUserAgentCustomMenuItem = menu.findItem(R.id.user_agent_custom);
1005 optionsSwipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
1006 optionsWideViewportMenuItem = menu.findItem(R.id.wide_viewport);
1007 optionsDisplayImagesMenuItem = menu.findItem(R.id.display_images);
1008 optionsDarkWebViewMenuItem = menu.findItem(R.id.dark_webview);
1009 optionsFontSizeMenuItem = menu.findItem(R.id.font_size);
1010 optionsAddOrEditDomainMenuItem = menu.findItem(R.id.add_or_edit_domain);
1012 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1013 updatePrivacyIcons(false);
1015 // Only display the form data menu items if the API < 26.
1016 optionsSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1017 optionsClearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1019 // Disable the clear form data menu item if the API >= 26 so that the status of the main Clear Data is calculated correctly.
1020 optionsClearFormDataMenuItem.setEnabled(Build.VERSION.SDK_INT < 26);
1022 // Only display the dark WebView menu item if the API >= 29.
1023 optionsDarkWebViewMenuItem.setVisible(Build.VERSION.SDK_INT >= 29);
1025 // 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.
1026 if (displayAdditionalAppBarIcons) {
1027 optionsRefreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
1028 bookmarksMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1029 optionsCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1030 } else { //Do not display the additional icons.
1031 optionsRefreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1032 bookmarksMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1033 optionsCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1036 // Replace Refresh with Stop if a URL is already loading.
1037 if (currentWebView != null && currentWebView.getProgress() != 100) {
1039 optionsRefreshMenuItem.setTitle(R.string.stop);
1041 // 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.
1042 if (displayAdditionalAppBarIcons) {
1043 optionsRefreshMenuItem.setIcon(R.drawable.close_blue);
1052 public boolean onPrepareOptionsMenu(Menu menu) {
1053 // Get a handle for the cookie manager.
1054 CookieManager cookieManager = CookieManager.getInstance();
1056 // Initialize the current user agent string and the font size.
1057 String currentUserAgent = getString(R.string.user_agent_privacy_browser);
1060 // 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.
1061 if (currentWebView != null) {
1062 // Set the add or edit domain text.
1063 if (currentWebView.getDomainSettingsApplied()) {
1064 optionsAddOrEditDomainMenuItem.setTitle(R.string.edit_domain_settings);
1066 optionsAddOrEditDomainMenuItem.setTitle(R.string.add_domain_settings);
1069 // Get the current user agent from the WebView.
1070 currentUserAgent = currentWebView.getSettings().getUserAgentString();
1072 // Get the current font size from the
1073 fontSize = currentWebView.getSettings().getTextZoom();
1075 // Set the status of the menu item checkboxes.
1076 optionsDomStorageMenuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1077 optionsSaveFormDataMenuItem.setChecked(currentWebView.getSettings().getSaveFormData()); // Form data can be removed once the minimum API >= 26.
1078 optionsEasyListMenuItem.setChecked(currentWebView.getEasyListEnabled());
1079 optionsEasyPrivacyMenuItem.setChecked(currentWebView.getEasyPrivacyEnabled());
1080 optionsFanboysAnnoyanceListMenuItem.setChecked(currentWebView.getFanboysAnnoyanceListEnabled());
1081 optionsFanboysSocialBlockingListMenuItem.setChecked(currentWebView.getFanboysSocialBlockingListEnabled());
1082 optionsUltraListMenuItem.setChecked(currentWebView.getUltraListEnabled());
1083 optionsUltraPrivacyMenuItem.setChecked(currentWebView.getUltraPrivacyEnabled());
1084 optionsBlockAllThirdPartyRequestsMenuItem.setChecked(currentWebView.getBlockAllThirdPartyRequests());
1085 optionsSwipeToRefreshMenuItem.setChecked(currentWebView.getSwipeToRefresh());
1086 optionsWideViewportMenuItem.setChecked(currentWebView.getSettings().getUseWideViewPort());
1087 optionsDisplayImagesMenuItem.setChecked(currentWebView.getSettings().getLoadsImagesAutomatically());
1089 // Initialize the display names for the blocklists with the number of blocked requests.
1090 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
1091 optionsEasyListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASYLIST) + " - " + getString(R.string.easylist));
1092 optionsEasyPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASYPRIVACY) + " - " + getString(R.string.easyprivacy));
1093 optionsFanboysAnnoyanceListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " + getString(R.string.fanboys_annoyance_list));
1094 optionsFanboysSocialBlockingListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " + getString(R.string.fanboys_social_blocking_list));
1095 optionsUltraListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRALIST) + " - " + getString(R.string.ultralist));
1096 optionsUltraPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRAPRIVACY) + " - " + getString(R.string.ultraprivacy));
1097 optionsBlockAllThirdPartyRequestsMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " + getString(R.string.block_all_third_party_requests));
1099 // Enable DOM Storage if JavaScript is enabled.
1100 optionsDomStorageMenuItem.setEnabled(currentWebView.getSettings().getJavaScriptEnabled());
1102 // Get the current theme status.
1103 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
1105 // Enable dark WebView if night mode is enabled.
1106 optionsDarkWebViewMenuItem.setEnabled(currentThemeStatus == Configuration.UI_MODE_NIGHT_YES);
1108 // Set the checkbox status for dark WebView if the device is running API >= 29 and algorithmic darkening is supported.
1109 if ((Build.VERSION.SDK_INT >= 29) && WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING))
1110 optionsDarkWebViewMenuItem.setChecked(WebSettingsCompat.isAlgorithmicDarkeningAllowed(currentWebView.getSettings()));
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 // Toggle dark WebView if supported.
1788 if ((Build.VERSION.SDK_INT >= 29) && WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING))
1789 WebSettingsCompat.setAlgorithmicDarkeningAllowed(currentWebView.getSettings(), !WebSettingsCompat.isAlgorithmicDarkeningAllowed(currentWebView.getSettings()));
1791 // Consume the event.
1793 } else if (menuItemId == R.id.find_on_page) { // Find on page.
1794 // Get a handle for the views.
1795 Toolbar toolbar = findViewById(R.id.toolbar);
1796 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
1797 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
1799 // Set the minimum height of the find on page linear layout to match the toolbar.
1800 findOnPageLinearLayout.setMinimumHeight(toolbar.getHeight());
1802 // Hide the toolbar.
1803 toolbar.setVisibility(View.GONE);
1805 // Show the find on page linear layout.
1806 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1808 // Display the keyboard. The app must wait 200 ms before running the command to work around a bug in Android.
1809 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1810 findOnPageEditText.postDelayed(() -> {
1811 // Set the focus on the find on page edit text.
1812 findOnPageEditText.requestFocus();
1814 // Get a handle for the input method manager.
1815 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1817 // Remove the lint warning below that the input method manager might be null.
1818 assert inputMethodManager != null;
1820 // Display the keyboard. `0` sets no input flags.
1821 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1824 // Consume the event.
1826 } else if (menuItemId == R.id.print) { // Print.
1827 // Get a print manager instance.
1828 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1830 // Remove the lint error below that print manager might be null.
1831 assert printManager != null;
1833 // Create a print document adapter from the current WebView.
1834 PrintDocumentAdapter printDocumentAdapter = currentWebView.createPrintDocumentAdapter(getString(R.string.print));
1836 // Print the document.
1837 printManager.print(getString(R.string.privacy_browser_webpage), printDocumentAdapter, null);
1839 // Consume the event.
1841 } else if (menuItemId == R.id.save_url) { // Save URL.
1842 // Check the download preference.
1843 if (downloadWithExternalApp) { // Download with an external app.
1844 downloadUrlWithExternalApp(currentWebView.getCurrentUrl());
1845 } else { // Handle the download inside of Privacy Browser.
1846 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
1847 new PrepareSaveDialog(this, this, getSupportFragmentManager(), currentWebView.getSettings().getUserAgentString(),
1848 currentWebView.getAcceptCookies()).execute(currentWebView.getCurrentUrl());
1851 // Consume the event.
1853 } else if (menuItemId == R.id.save_archive) {
1854 // Open the file picker with a default file name built from the current domain name.
1855 saveWebpageArchiveActivityResultLauncher.launch(currentWebView.getCurrentDomainName() + ".mht");
1857 // Consume the event.
1859 } else if (menuItemId == R.id.save_image) { // Save image.
1860 // Open the file picker with a default file name built from the current domain name.
1861 saveWebpageImageActivityResultLauncher.launch(currentWebView.getCurrentDomainName() + ".png");
1863 // Consume the event.
1865 } else if (menuItemId == R.id.add_to_homescreen) { // Add to homescreen.
1866 // Instantiate the create home screen shortcut dialog.
1867 DialogFragment createHomeScreenShortcutDialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView.getTitle(), currentWebView.getUrl(),
1868 currentWebView.getFavoriteOrDefaultIcon());
1870 // Show the create home screen shortcut dialog.
1871 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
1873 // Consume the event.
1875 } else if (menuItemId == R.id.view_source) { // View source.
1876 // Create an intent to launch the view source activity.
1877 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
1879 // Add the variables to the intent.
1880 viewSourceIntent.putExtra(ViewSourceActivityKt.CURRENT_URL, currentWebView.getUrl());
1881 viewSourceIntent.putExtra(ViewSourceActivityKt.USER_AGENT, currentWebView.getSettings().getUserAgentString());
1884 startActivity(viewSourceIntent);
1886 // Consume the event.
1888 } else if (menuItemId == R.id.share_message) { // Share a message.
1889 // Prepare the share string.
1890 String shareString = currentWebView.getTitle() + " – " + currentWebView.getUrl();
1892 // Create the share intent.
1893 Intent shareMessageIntent = new Intent(Intent.ACTION_SEND);
1895 // Add the share string to the intent.
1896 shareMessageIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1898 // Set the MIME type.
1899 shareMessageIntent.setType("text/plain");
1901 // Set the intent to open in a new task.
1902 shareMessageIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1905 startActivity(Intent.createChooser(shareMessageIntent, getString(R.string.share_message)));
1907 // Consume the event.
1909 } else if (menuItemId == R.id.share_url) { // Share URL.
1910 // Create the share intent.
1911 Intent shareUrlIntent = new Intent(Intent.ACTION_SEND);
1913 // Add the URL to the intent.
1914 shareUrlIntent.putExtra(Intent.EXTRA_TEXT, currentWebView.getUrl());
1916 // Add the title to the intent.
1917 shareUrlIntent.putExtra(Intent.EXTRA_SUBJECT, currentWebView.getTitle());
1919 // Set the MIME type.
1920 shareUrlIntent.setType("text/plain");
1922 // Set the intent to open in a new task.
1923 shareUrlIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1926 startActivity(Intent.createChooser(shareUrlIntent, getString(R.string.share_url)));
1928 // Consume the event.
1930 } else if (menuItemId == R.id.open_with_app) { // Open with app.
1931 // Open the URL with an outside app.
1932 openWithApp(currentWebView.getUrl());
1934 // Consume the event.
1936 } else if (menuItemId == R.id.open_with_browser) { // Open with browser.
1937 // Open the URL with an outside browser.
1938 openWithBrowser(currentWebView.getUrl());
1940 // Consume the event.
1942 } else if (menuItemId == R.id.add_or_edit_domain) { // Add or edit domain.
1943 // Reapply the domain settings on returning to `MainWebViewActivity`.
1944 reapplyDomainSettingsOnRestart = true;
1946 // Check if domain settings currently exist.
1947 if (currentWebView.getDomainSettingsApplied()) { // Edit the current domain settings.
1948 // Create an intent to launch the domains activity.
1949 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1951 // Add the extra information to the intent.
1952 domainsIntent.putExtra(DomainsActivity.LOAD_DOMAIN, currentWebView.getDomainSettingsDatabaseId());
1953 domainsIntent.putExtra(DomainsActivity.CLOSE_ON_BACK, true);
1954 domainsIntent.putExtra(DomainsActivity.CURRENT_URL, currentWebView.getUrl());
1955 domainsIntent.putExtra(DomainsActivity.CURRENT_IP_ADDRESSES, currentWebView.getCurrentIpAddresses());
1957 // Get the current certificate.
1958 SslCertificate sslCertificate = currentWebView.getCertificate();
1960 // Check to see if the SSL certificate is populated.
1961 if (sslCertificate != null) {
1962 // Extract the certificate to strings.
1963 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1964 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1965 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1966 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1967 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1968 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1969 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1970 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1972 // Add the certificate to the intent.
1973 domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_TO_CNAME, issuedToCName);
1974 domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_TO_ONAME, issuedToOName);
1975 domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_TO_UNAME, issuedToUName);
1976 domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_BY_CNAME, issuedByCName);
1977 domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_BY_ONAME, issuedByOName);
1978 domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_BY_UNAME, issuedByUName);
1979 domainsIntent.putExtra(DomainsActivity.SSL_START_DATE, startDateLong);
1980 domainsIntent.putExtra(DomainsActivity.SSL_END_DATE, endDateLong);
1984 startActivity(domainsIntent);
1985 } else { // Add a new domain.
1986 // Get the current URI.
1987 Uri currentUri = Uri.parse(currentWebView.getUrl());
1989 // Get the current domain from the URI.
1990 String currentDomain = currentUri.getHost();
1992 // Set an empty domain if it is null.
1993 if (currentDomain == null)
1996 // Create the domain and store the database ID.
1997 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1999 // Create an intent to launch the domains activity.
2000 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2002 // Add the extra information to the intent.
2003 domainsIntent.putExtra(DomainsActivity.LOAD_DOMAIN, newDomainDatabaseId);
2004 domainsIntent.putExtra(DomainsActivity.CLOSE_ON_BACK, true);
2005 domainsIntent.putExtra(DomainsActivity.CURRENT_URL, currentWebView.getUrl());
2006 domainsIntent.putExtra(DomainsActivity.CURRENT_IP_ADDRESSES, currentWebView.getCurrentIpAddresses());
2008 // Get the current certificate.
2009 SslCertificate sslCertificate = currentWebView.getCertificate();
2011 // Check to see if the SSL certificate is populated.
2012 if (sslCertificate != null) {
2013 // Extract the certificate to strings.
2014 String issuedToCName = sslCertificate.getIssuedTo().getCName();
2015 String issuedToOName = sslCertificate.getIssuedTo().getOName();
2016 String issuedToUName = sslCertificate.getIssuedTo().getUName();
2017 String issuedByCName = sslCertificate.getIssuedBy().getCName();
2018 String issuedByOName = sslCertificate.getIssuedBy().getOName();
2019 String issuedByUName = sslCertificate.getIssuedBy().getUName();
2020 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
2021 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
2023 // Add the certificate to the intent.
2024 domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_TO_CNAME, issuedToCName);
2025 domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_TO_ONAME, issuedToOName);
2026 domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_TO_UNAME, issuedToUName);
2027 domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_BY_CNAME, issuedByCName);
2028 domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_BY_ONAME, issuedByOName);
2029 domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_BY_UNAME, issuedByUName);
2030 domainsIntent.putExtra(DomainsActivity.SSL_START_DATE, startDateLong);
2031 domainsIntent.putExtra(DomainsActivity.SSL_END_DATE, endDateLong);
2035 startActivity(domainsIntent);
2038 // Consume the event.
2040 } else { // There is no match with the options menu. Pass the event up to the parent method.
2041 // Don't consume the event.
2042 return super.onOptionsItemSelected(menuItem);
2046 // removeAllCookies is deprecated, but it is required for API < 21.
2048 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2049 // Get a handle for the shared preferences.
2050 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2052 // Get the menu item ID.
2053 int menuItemId = menuItem.getItemId();
2055 // Run the commands that correspond to the selected menu item.
2056 if (menuItemId == R.id.clear_and_exit) { // Clear and exit.
2057 // Clear and exit Privacy Browser.
2059 } else if (menuItemId == R.id.home) { // Home.
2060 // Load the homepage.
2061 loadUrl(currentWebView, sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
2062 } else if (menuItemId == R.id.back) { // Back.
2063 // Check if the WebView can go back.
2064 if (currentWebView.canGoBack()) {
2065 // Get the current web back forward list.
2066 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
2068 // Get the previous entry URL.
2069 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
2071 // Apply the domain settings.
2072 applyDomainSettings(currentWebView, previousUrl, false, false, false);
2074 // Load the previous website in the history.
2075 currentWebView.goBack();
2077 } else if (menuItemId == R.id.forward) { // Forward.
2078 // Check if the WebView can go forward.
2079 if (currentWebView.canGoForward()) {
2080 // Get the current web back forward list.
2081 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
2083 // Get the next entry URL.
2084 String nextUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() + 1).getUrl();
2086 // Apply the domain settings.
2087 applyDomainSettings(currentWebView, nextUrl, false, false, false);
2089 // Load the next website in the history.
2090 currentWebView.goForward();
2092 } else if (menuItemId == R.id.history) { // History.
2093 // Instantiate the URL history dialog.
2094 DialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(currentWebView.getWebViewFragmentId());
2096 // Show the URL history dialog.
2097 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2098 } else if (menuItemId == R.id.open) { // Open.
2099 // Instantiate the open file dialog.
2100 DialogFragment openDialogFragment = new OpenDialog();
2102 // Show the open file dialog.
2103 openDialogFragment.show(getSupportFragmentManager(), getString(R.string.open));
2104 } else if (menuItemId == R.id.requests) { // Requests.
2105 // Populate the resource requests.
2106 RequestsActivity.resourceRequests = currentWebView.getResourceRequests();
2108 // Create an intent to launch the Requests activity.
2109 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2111 // Add the block third-party requests status to the intent.
2112 requestsIntent.putExtra("block_all_third_party_requests", currentWebView.getBlockAllThirdPartyRequests());
2115 startActivity(requestsIntent);
2116 } else if (menuItemId == R.id.downloads) { // Downloads.
2117 // Try the default system download manager.
2119 // Launch the default system Download Manager.
2120 Intent defaultDownloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2122 // Launch as a new task so that the download manager and Privacy Browser show as separate windows in the recent tasks list.
2123 defaultDownloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2126 startActivity(defaultDownloadManagerIntent);
2127 } catch (Exception defaultDownloadManagerException) {
2128 // Try a generic file manager.
2130 // Create a generic file manager intent.
2131 Intent genericFileManagerIntent = new Intent(Intent.ACTION_VIEW);
2133 // Open the download directory.
2134 genericFileManagerIntent.setDataAndType(Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()), DocumentsContract.Document.MIME_TYPE_DIR);
2136 // Launch as a new task so that the file manager and Privacy Browser show as separate windows in the recent tasks list.
2137 genericFileManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2140 startActivity(genericFileManagerIntent);
2141 } catch (Exception genericFileManagerException) {
2142 // Try an alternate file manager.
2144 // Create an alternate file manager intent.
2145 Intent alternateFileManagerIntent = new Intent(Intent.ACTION_VIEW);
2147 // Open the download directory.
2148 alternateFileManagerIntent.setDataAndType(Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()), "resource/folder");
2150 // Launch as a new task so that the file manager and Privacy Browser show as separate windows in the recent tasks list.
2151 alternateFileManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2153 // Open the alternate file manager.
2154 startActivity(alternateFileManagerIntent);
2155 } catch (Exception alternateFileManagerException) {
2156 // Display a snackbar.
2157 Snackbar.make(currentWebView, R.string.no_file_manager_detected, Snackbar.LENGTH_INDEFINITE).show();
2161 } else if (menuItemId == R.id.domains) { // Domains.
2162 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2163 reapplyDomainSettingsOnRestart = true;
2165 // Launch the domains activity.
2166 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2168 // Add the extra information to the intent.
2169 domainsIntent.putExtra(DomainsActivity.CURRENT_URL, currentWebView.getUrl());
2170 domainsIntent.putExtra(DomainsActivity.CURRENT_IP_ADDRESSES, currentWebView.getCurrentIpAddresses());
2172 // Get the current certificate.
2173 SslCertificate sslCertificate = currentWebView.getCertificate();
2175 // Check to see if the SSL certificate is populated.
2176 if (sslCertificate != null) {
2177 // Extract the certificate to strings.
2178 String issuedToCName = sslCertificate.getIssuedTo().getCName();
2179 String issuedToOName = sslCertificate.getIssuedTo().getOName();
2180 String issuedToUName = sslCertificate.getIssuedTo().getUName();
2181 String issuedByCName = sslCertificate.getIssuedBy().getCName();
2182 String issuedByOName = sslCertificate.getIssuedBy().getOName();
2183 String issuedByUName = sslCertificate.getIssuedBy().getUName();
2184 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
2185 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
2187 // Add the certificate to the intent.
2188 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
2189 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
2190 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
2191 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
2192 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
2193 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
2194 domainsIntent.putExtra("ssl_start_date", startDateLong);
2195 domainsIntent.putExtra("ssl_end_date", endDateLong);
2199 startActivity(domainsIntent);
2200 } else if (menuItemId == R.id.settings) { // Settings.
2201 // Set the flag to reapply app settings on restart when returning from Settings.
2202 reapplyAppSettingsOnRestart = true;
2204 // Set the flag to reapply the domain settings on restart when returning from Settings.
2205 reapplyDomainSettingsOnRestart = true;
2207 // Launch the settings activity.
2208 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2209 startActivity(settingsIntent);
2210 } else if (menuItemId == R.id.import_export) { // Import/Export.
2211 // Create an intent to launch the import/export activity.
2212 Intent importExportIntent = new Intent(this, ImportExportActivity.class);
2215 startActivity(importExportIntent);
2216 } else if (menuItemId == R.id.logcat) { // Logcat.
2217 // Create an intent to launch the logcat activity.
2218 Intent logcatIntent = new Intent(this, LogcatActivity.class);
2221 startActivity(logcatIntent);
2222 } else if (menuItemId == R.id.webview_devtools) { // WebView Dev.
2223 // Create a WebView DevTools intent.
2224 Intent webViewDevToolsIntent = new Intent("com.android.webview.SHOW_DEV_UI");
2226 // Launch as a new task so that the WebView DevTools and Privacy Browser show as a separate windows in the recent tasks list.
2227 webViewDevToolsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2230 startActivity(webViewDevToolsIntent);
2231 } else if (menuItemId == R.id.guide) { // Guide.
2232 // Create an intent to launch the guide activity.
2233 Intent guideIntent = new Intent(this, GuideActivity.class);
2236 startActivity(guideIntent);
2237 } else if (menuItemId == R.id.about) { // About
2238 // Create an intent to launch the about activity.
2239 Intent aboutIntent = new Intent(this, AboutActivity.class);
2241 // Create a string array for the blocklist versions.
2242 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],
2243 ultraList.get(0).get(0)[0], ultraPrivacy.get(0).get(0)[0]};
2245 // Add the blocklist versions to the intent.
2246 aboutIntent.putExtra(AboutActivity.BLOCKLIST_VERSIONS, blocklistVersions);
2249 startActivity(aboutIntent);
2252 // Close the navigation drawer.
2253 drawerLayout.closeDrawer(GravityCompat.START);
2258 public void onPostCreate(Bundle savedInstanceState) {
2259 // Run the default commands.
2260 super.onPostCreate(savedInstanceState);
2262 // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished. This creates the navigation drawer icon.
2263 actionBarDrawerToggle.syncState();
2267 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2268 // Get the hit test result.
2269 final WebView.HitTestResult hitTestResult = currentWebView.getHitTestResult();
2271 // Define the URL strings.
2272 final String imageUrl;
2273 final String linkUrl;
2275 // Get handles for the system managers.
2276 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2278 // Remove the lint errors below that the clipboard manager might be null.
2279 assert clipboardManager != null;
2281 // Process the link according to the type.
2282 switch (hitTestResult.getType()) {
2283 // `SRC_ANCHOR_TYPE` is a link.
2284 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2285 // Get the target URL.
2286 linkUrl = hitTestResult.getExtra();
2288 // Set the target URL as the title of the `ContextMenu`.
2289 menu.setHeaderTitle(linkUrl);
2291 // Add an Open in New Tab entry.
2292 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2293 // Load the link URL in a new tab and move to it.
2294 addNewTab(linkUrl, true);
2296 // Consume the event.
2300 // Add an Open in Background entry.
2301 menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
2302 // Load the link URL in a new tab but do not move to it.
2303 addNewTab(linkUrl, false);
2305 // Consume the event.
2309 // Add an Open with App entry.
2310 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2311 openWithApp(linkUrl);
2313 // Consume the event.
2317 // Add an Open with Browser entry.
2318 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2319 openWithBrowser(linkUrl);
2321 // Consume the event.
2325 // Add a Copy URL entry.
2326 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2327 // Save the link URL in a `ClipData`.
2328 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2330 // Set the `ClipData` as the clipboard's primary clip.
2331 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2333 // Consume the event.
2337 // Add a Save URL entry.
2338 menu.add(R.string.save_url).setOnMenuItemClickListener((MenuItem item) -> {
2339 // Check the download preference.
2340 if (downloadWithExternalApp) { // Download with an external app.
2341 downloadUrlWithExternalApp(linkUrl);
2342 } else { // Handle the download inside of Privacy Browser.
2343 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2344 new PrepareSaveDialog(this, this, getSupportFragmentManager(), currentWebView.getSettings().getUserAgentString(),
2345 currentWebView.getAcceptCookies()).execute(linkUrl);
2348 // Consume the event.
2352 // Add an empty Cancel entry, which by default closes the context menu.
2353 menu.add(R.string.cancel);
2356 // `IMAGE_TYPE` is an image.
2357 case WebView.HitTestResult.IMAGE_TYPE:
2358 // Get the image URL.
2359 imageUrl = hitTestResult.getExtra();
2361 // Remove the incorrect lint warning below that the image URL might be null.
2362 assert imageUrl != null;
2364 // Set the context menu title.
2365 if (imageUrl.startsWith("data:")) { // The image data is contained in within the URL, making it exceedingly long.
2366 // Truncate the image URL before making it the title.
2367 menu.setHeaderTitle(imageUrl.substring(0, 100));
2368 } else { // The image URL does not contain the full image data.
2369 // Set the image URL as the title of the context menu.
2370 menu.setHeaderTitle(imageUrl);
2373 // Add an Open in New Tab entry.
2374 menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2375 // Load the image in a new tab.
2376 addNewTab(imageUrl, true);
2378 // Consume the event.
2382 // Add an Open with App entry.
2383 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2384 // Open the image URL with an external app.
2385 openWithApp(imageUrl);
2387 // Consume the event.
2391 // Add an Open with Browser entry.
2392 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2393 // Open the image URL with an external browser.
2394 openWithBrowser(imageUrl);
2396 // Consume the event.
2400 // Add a View Image entry.
2401 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2402 // Load the image in the current tab.
2403 loadUrl(currentWebView, imageUrl);
2405 // Consume the event.
2409 // Add a Save Image entry.
2410 menu.add(R.string.save_image).setOnMenuItemClickListener((MenuItem item) -> {
2411 // Check the download preference.
2412 if (downloadWithExternalApp) { // Download with an external app.
2413 downloadUrlWithExternalApp(imageUrl);
2414 } else { // Handle the download inside of Privacy Browser.
2415 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2416 new PrepareSaveDialog(this, this, getSupportFragmentManager(), currentWebView.getSettings().getUserAgentString(),
2417 currentWebView.getAcceptCookies()).execute(imageUrl);
2420 // Consume the event.
2424 // Add a Copy URL entry.
2425 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2426 // Save the image URL in a clip data.
2427 ClipData imageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2429 // Set the clip data as the clipboard's primary clip.
2430 clipboardManager.setPrimaryClip(imageTypeClipData);
2432 // Consume the event.
2436 // Add an empty Cancel entry, which by default closes the context menu.
2437 menu.add(R.string.cancel);
2440 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2441 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2442 // Get the image URL.
2443 imageUrl = hitTestResult.getExtra();
2445 // Instantiate a handler.
2446 Handler handler = new Handler();
2448 // Get a message from the handler.
2449 Message message = handler.obtainMessage();
2451 // Request the image details from the last touched node be returned in the message.
2452 currentWebView.requestFocusNodeHref(message);
2454 // Get the link URL from the message data.
2455 linkUrl = message.getData().getString("url");
2457 // Set the link URL as the title of the context menu.
2458 menu.setHeaderTitle(linkUrl);
2460 // Add an Open in New Tab entry.
2461 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2462 // Load the link URL in a new tab and move to it.
2463 addNewTab(linkUrl, true);
2465 // Consume the event.
2469 // Add an Open in Background entry.
2470 menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
2471 // Lod the link URL in a new tab but do not move to it.
2472 addNewTab(linkUrl, false);
2474 // Consume the event.
2478 // Add an Open Image in New Tab entry.
2479 menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2480 // Load the image in a new tab and move to it.
2481 addNewTab(imageUrl, true);
2483 // Consume the event.
2487 // Add an Open with App entry.
2488 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2489 // Open the link URL with an external app.
2490 openWithApp(linkUrl);
2492 // Consume the event.
2496 // Add an Open with Browser entry.
2497 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2498 // Open the link URL with an external browser.
2499 openWithBrowser(linkUrl);
2501 // Consume the event.
2505 // Add a View Image entry.
2506 menu.add(R.string.view_image).setOnMenuItemClickListener((MenuItem item) -> {
2507 // View the image in the current tab.
2508 loadUrl(currentWebView, imageUrl);
2510 // Consume the event.
2514 // Add a Save Image entry.
2515 menu.add(R.string.save_image).setOnMenuItemClickListener((MenuItem item) -> {
2516 // Check the download preference.
2517 if (downloadWithExternalApp) { // Download with an external app.
2518 downloadUrlWithExternalApp(imageUrl);
2519 } else { // Handle the download inside of Privacy Browser.
2520 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2521 new PrepareSaveDialog(this, this, getSupportFragmentManager(), currentWebView.getSettings().getUserAgentString(),
2522 currentWebView.getAcceptCookies()).execute(imageUrl);
2525 // Consume the event.
2529 // Add a Copy URL entry.
2530 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2531 // Save the link URL in a clip data.
2532 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2534 // Set the clip data as the clipboard's primary clip.
2535 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2537 // Consume the event.
2541 // Add a Save URL entry.
2542 menu.add(R.string.save_url).setOnMenuItemClickListener((MenuItem item) -> {
2543 // Check the download preference.
2544 if (downloadWithExternalApp) { // Download with an external app.
2545 downloadUrlWithExternalApp(linkUrl);
2546 } else { // Handle the download inside of Privacy Browser.
2547 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2548 new PrepareSaveDialog(this, this, getSupportFragmentManager(), currentWebView.getSettings().getUserAgentString(),
2549 currentWebView.getAcceptCookies()).execute(linkUrl);
2552 // Consume the event.
2556 // Add an empty Cancel entry, which by default closes the context menu.
2557 menu.add(R.string.cancel);
2560 case WebView.HitTestResult.EMAIL_TYPE:
2561 // Get the target URL.
2562 linkUrl = hitTestResult.getExtra();
2564 // Set the target URL as the title of the `ContextMenu`.
2565 menu.setHeaderTitle(linkUrl);
2567 // Add a Write Email entry.
2568 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2569 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2570 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2572 // Parse the url and set it as the data for the `Intent`.
2573 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2575 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2576 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2580 startActivity(emailIntent);
2581 } catch (ActivityNotFoundException exception) {
2582 // Display a snackbar.
2583 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
2586 // Consume the event.
2590 // Add a Copy Email Address entry.
2591 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2592 // Save the email address in a `ClipData`.
2593 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2595 // Set the `ClipData` as the clipboard's primary clip.
2596 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2598 // Consume the event.
2602 // Add an empty Cancel entry, which by default closes the context menu.
2603 menu.add(R.string.cancel);
2609 public void onCreateBookmark(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2610 // Get a handle for the bookmarks list view.
2611 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2614 Dialog dialog = dialogFragment.getDialog();
2616 // Remove the incorrect lint warning below that the dialog might be null.
2617 assert dialog != null;
2619 // Get the views from the dialog fragment.
2620 EditText createBookmarkNameEditText = dialog.findViewById(R.id.create_bookmark_name_edittext);
2621 EditText createBookmarkUrlEditText = dialog.findViewById(R.id.create_bookmark_url_edittext);
2623 // Extract the strings from the edit texts.
2624 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2625 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2627 // Create a favorite icon byte array output stream.
2628 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2630 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2631 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2633 // Convert the favorite icon byte array stream to a byte array.
2634 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2636 // Display the new bookmark below the current items in the (0 indexed) list.
2637 int newBookmarkDisplayOrder = bookmarksListView.getCount();
2639 // Create the bookmark.
2640 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2642 // Update the bookmarks cursor with the current contents of this folder.
2643 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2645 // Update the list view.
2646 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2648 // Scroll to the new bookmark.
2649 bookmarksListView.setSelection(newBookmarkDisplayOrder);
2653 public void onCreateBookmarkFolder(DialogFragment dialogFragment, @NonNull Bitmap favoriteIconBitmap) {
2654 // Get a handle for the bookmarks list view.
2655 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2658 Dialog dialog = dialogFragment.getDialog();
2660 // Remove the incorrect lint warning below that the dialog might be null.
2661 assert dialog != null;
2663 // Get handles for the views in the dialog fragment.
2664 EditText folderNameEditText = dialog.findViewById(R.id.folder_name_edittext);
2665 RadioButton defaultIconRadioButton = dialog.findViewById(R.id.default_icon_radiobutton);
2666 ImageView defaultIconImageView = dialog.findViewById(R.id.default_icon_imageview);
2668 // Get new folder name string.
2669 String folderNameString = folderNameEditText.getText().toString();
2671 // Create a folder icon bitmap.
2672 Bitmap folderIconBitmap;
2674 // Set the folder icon bitmap according to the dialog.
2675 if (defaultIconRadioButton.isChecked()) { // Use the default folder icon.
2676 // Get the default folder icon drawable.
2677 Drawable folderIconDrawable = defaultIconImageView.getDrawable();
2679 // Convert the folder icon drawable to a bitmap drawable.
2680 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2682 // Convert the folder icon bitmap drawable to a bitmap.
2683 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2684 } else { // Use the WebView favorite icon.
2685 // Copy the favorite icon bitmap to the folder icon bitmap.
2686 folderIconBitmap = favoriteIconBitmap;
2689 // Create a folder icon byte array output stream.
2690 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2692 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2693 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2695 // Convert the folder icon byte array stream to a byte array.
2696 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2698 // Move all the bookmarks down one in the display order.
2699 for (int i = 0; i < bookmarksListView.getCount(); i++) {
2700 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2701 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2704 // Create the folder, which will be placed at the top of the `ListView`.
2705 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2707 // Update the bookmarks cursor with the current contents of this folder.
2708 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2710 // Update the list view.
2711 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2713 // Scroll to the new folder.
2714 bookmarksListView.setSelection(0);
2718 public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId, @NonNull Bitmap favoriteIconBitmap) {
2719 // Remove the incorrect lint warning below that the dialog fragment might be null.
2720 assert dialogFragment != null;
2723 Dialog dialog = dialogFragment.getDialog();
2725 // Remove the incorrect lint warning below that the dialog might be null.
2726 assert dialog != null;
2728 // Get handles for the views from the dialog.
2729 RadioButton currentFolderIconRadioButton = dialog.findViewById(R.id.current_icon_radiobutton);
2730 RadioButton defaultFolderIconRadioButton = dialog.findViewById(R.id.default_icon_radiobutton);
2731 ImageView defaultFolderIconImageView = dialog.findViewById(R.id.default_icon_imageview);
2732 EditText editFolderNameEditText = dialog.findViewById(R.id.folder_name_edittext);
2734 // Get the new folder name.
2735 String newFolderNameString = editFolderNameEditText.getText().toString();
2737 // Check if the favorite icon has changed.
2738 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
2739 // Update the name in the database.
2740 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2741 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
2742 // Create the new folder icon Bitmap.
2743 Bitmap folderIconBitmap;
2745 // Populate the new folder icon bitmap.
2746 if (defaultFolderIconRadioButton.isChecked()) {
2747 // Get the default folder icon drawable.
2748 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2750 // Convert the folder icon drawable to a bitmap drawable.
2751 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2753 // Convert the folder icon bitmap drawable to a bitmap.
2754 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2755 } else { // Use the `WebView` favorite icon.
2756 // Copy the favorite icon bitmap to the folder icon bitmap.
2757 folderIconBitmap = favoriteIconBitmap;
2760 // Create a folder icon byte array output stream.
2761 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2763 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2764 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2766 // Convert the folder icon byte array stream to a byte array.
2767 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2769 // Update the folder icon in the database.
2770 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, newFolderIconByteArray);
2771 } else { // The folder icon and the name have changed.
2772 // Get the new folder icon bitmap.
2773 Bitmap folderIconBitmap;
2774 if (defaultFolderIconRadioButton.isChecked()) {
2775 // Get the default folder icon drawable.
2776 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2778 // Convert the folder icon drawable to a bitmap drawable.
2779 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2781 // Convert the folder icon bitmap drawable to a bitmap.
2782 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2783 } else { // Use the `WebView` favorite icon.
2784 // Copy the favorite icon bitmap to the folder icon bitmap.
2785 folderIconBitmap = favoriteIconBitmap;
2788 // Create a folder icon byte array output stream.
2789 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2791 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2792 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2794 // Convert the folder icon byte array stream to a byte array.
2795 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2797 // Update the folder name and icon in the database.
2798 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, newFolderIconByteArray);
2801 // Update the bookmarks cursor with the current contents of this folder.
2802 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2804 // Update the list view.
2805 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2808 // Process the results of a file browse.
2810 public void onActivityResult(int requestCode, int resultCode, Intent returnedIntent) {
2811 // Run the default commands.
2812 super.onActivityResult(requestCode, resultCode, returnedIntent);
2814 // Run the commands that correlate to the specified request code.
2815 switch (requestCode) {
2816 case BROWSE_FILE_UPLOAD_REQUEST_CODE:
2817 // Pass the file to the WebView.
2818 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, returnedIntent));
2821 case BROWSE_OPEN_REQUEST_CODE:
2822 // Don't do anything if the user pressed back from the file picker.
2823 if (resultCode == Activity.RESULT_OK) {
2824 // Get a handle for the open dialog fragment.
2825 DialogFragment openDialogFragment = (DialogFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.open));
2827 // Only update the file name if the dialog still exists.
2828 if (openDialogFragment != null) {
2829 // Get a handle for the open dialog.
2830 Dialog openDialog = openDialogFragment.getDialog();
2832 // Remove the incorrect lint warning below that the dialog might be null.
2833 assert openDialog != null;
2835 // Get a handle for the file name edit text.
2836 EditText fileNameEditText = openDialog.findViewById(R.id.file_name_edittext);
2838 // Get the file name URI from the intent.
2839 Uri fileNameUri = returnedIntent.getData();
2841 // Get the file name string from the URI.
2842 String fileNameString = fileNameUri.toString();
2844 // Set the file name text.
2845 fileNameEditText.setText(fileNameString);
2847 // Move the cursor to the end of the file name edit text.
2848 fileNameEditText.setSelection(fileNameString.length());
2855 private void loadUrlFromTextBox() {
2856 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
2857 String unformattedUrlString = urlEditText.getText().toString().trim();
2859 // Initialize the formatted URL string.
2862 // Check to see if the unformatted URL string is a valid URL. Otherwise, convert it into a search.
2863 if (unformattedUrlString.startsWith("content://")) { // This is a Content URL.
2864 // Load the entire content URL.
2865 url = unformattedUrlString;
2866 } else if (Patterns.WEB_URL.matcher(unformattedUrlString).matches() || unformattedUrlString.startsWith("http://") || unformattedUrlString.startsWith("https://") ||
2867 unformattedUrlString.startsWith("file://")) { // This is a standard URL.
2868 // Add `https://` at the beginning if there is no protocol. Otherwise the app will segfault.
2869 if (!unformattedUrlString.startsWith("http") && !unformattedUrlString.startsWith("file://")) {
2870 unformattedUrlString = "https://" + unformattedUrlString;
2873 // Initialize the unformatted URL.
2874 URL unformattedUrl = null;
2876 // 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.
2878 unformattedUrl = new URL(unformattedUrlString);
2879 } catch (MalformedURLException e) {
2880 e.printStackTrace();
2883 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2884 String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2885 String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2886 String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2887 String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2888 String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2891 Uri.Builder uri = new Uri.Builder();
2892 uri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2894 // Decode the URI as a UTF-8 string in.
2896 url = URLDecoder.decode(uri.build().toString(), "UTF-8");
2897 } catch (UnsupportedEncodingException exception) {
2898 // Do nothing. The formatted URL string will remain blank.
2900 } else if (!unformattedUrlString.isEmpty()){ // This is not a URL, but rather a search string.
2901 // Create an encoded URL String.
2902 String encodedUrlString;
2904 // Sanitize the search input.
2906 encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2907 } catch (UnsupportedEncodingException exception) {
2908 encodedUrlString = "";
2911 // Add the base search URL.
2912 url = searchURL + encodedUrlString;
2915 // 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.
2916 urlEditText.clearFocus();
2919 loadUrl(currentWebView, url);
2922 private void loadUrl(NestedScrollWebView nestedScrollWebView, String url) {
2923 // Sanitize the URL.
2924 url = sanitizeUrl(url);
2926 // Apply the domain settings and load the URL.
2927 applyDomainSettings(nestedScrollWebView, url, true, false, true);
2930 public void findPreviousOnPage(View view) {
2931 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
2932 currentWebView.findNext(false);
2935 public void findNextOnPage(View view) {
2936 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2937 currentWebView.findNext(true);
2940 public void closeFindOnPage(View view) {
2941 // Get a handle for the views.
2942 Toolbar toolbar = findViewById(R.id.toolbar);
2943 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
2944 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
2946 // Delete the contents of `find_on_page_edittext`.
2947 findOnPageEditText.setText(null);
2949 // Clear the highlighted phrases if the WebView is not null.
2950 if (currentWebView != null) {
2951 currentWebView.clearMatches();
2954 // Hide the find on page linear layout.
2955 findOnPageLinearLayout.setVisibility(View.GONE);
2957 // Show the toolbar.
2958 toolbar.setVisibility(View.VISIBLE);
2960 // Get a handle for the input method manager.
2961 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
2963 // Remove the lint warning below that the input method manager might be null.
2964 assert inputMethodManager != null;
2966 // Hide the keyboard.
2967 inputMethodManager.hideSoftInputFromWindow(toolbar.getWindowToken(), 0);
2971 public void onApplyNewFontSize(DialogFragment dialogFragment) {
2972 // Remove the incorrect lint warning below that the dialog fragment might be null.
2973 assert dialogFragment != null;
2976 Dialog dialog = dialogFragment.getDialog();
2978 // Remove the incorrect lint warning below tha the dialog might be null.
2979 assert dialog != null;
2981 // Get a handle for the font size edit text.
2982 EditText fontSizeEditText = dialog.findViewById(R.id.font_size_edittext);
2984 // Initialize the new font size variable with the current font size.
2985 int newFontSize = currentWebView.getSettings().getTextZoom();
2987 // Get the font size from the edit text.
2989 newFontSize = Integer.parseInt(fontSizeEditText.getText().toString());
2990 } catch (Exception exception) {
2991 // If the edit text does not contain a valid font size do nothing.
2994 // Apply the new font size.
2995 currentWebView.getSettings().setTextZoom(newFontSize);
2999 public void onOpen(DialogFragment dialogFragment) {
3001 Dialog dialog = dialogFragment.getDialog();
3003 // Remove the incorrect lint warning below that the dialog might be null.
3004 assert dialog != null;
3006 // Get handles for the views.
3007 EditText fileNameEditText = dialog.findViewById(R.id.file_name_edittext);
3008 CheckBox mhtCheckBox = dialog.findViewById(R.id.mht_checkbox);
3010 // Get the file path string.
3011 String openFilePath = fileNameEditText.getText().toString();
3013 // Apply the domain settings. This resets the favorite icon and removes any domain settings.
3014 applyDomainSettings(currentWebView, openFilePath, true, false, false);
3016 // Open the file according to the type.
3017 if (mhtCheckBox.isChecked()) { // Force opening of an MHT file.
3019 // Get the MHT file input stream.
3020 InputStream mhtFileInputStream = getContentResolver().openInputStream(Uri.parse(openFilePath));
3022 // Create a temporary MHT file.
3023 File temporaryMhtFile = File.createTempFile("temporary_mht_file", ".mht", getCacheDir());
3025 // Get a file output stream for the temporary MHT file.
3026 FileOutputStream temporaryMhtFileOutputStream = new FileOutputStream(temporaryMhtFile);
3028 // Create a transfer byte array.
3029 byte[] transferByteArray = new byte[1024];
3031 // Create an integer to track the number of bytes read.
3034 // Copy the temporary MHT file input stream to the MHT output stream.
3035 while ((bytesRead = mhtFileInputStream.read(transferByteArray)) > 0) {
3036 temporaryMhtFileOutputStream.write(transferByteArray, 0, bytesRead);
3039 // Flush the temporary MHT file output stream.
3040 temporaryMhtFileOutputStream.flush();
3042 // Close the streams.
3043 temporaryMhtFileOutputStream.close();
3044 mhtFileInputStream.close();
3046 // Load the temporary MHT file.
3047 currentWebView.loadUrl(temporaryMhtFile.toString());
3048 } catch (Exception exception) {
3049 // Display a snackbar.
3050 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
3052 } else { // Let the WebView handle opening of the file.
3054 currentWebView.loadUrl(openFilePath);
3058 private void downloadUrlWithExternalApp(String url) {
3059 // Create a download intent. Not specifying the action type will display the maximum number of options.
3060 Intent downloadIntent = new Intent();
3062 // Set the URI and the mime type.
3063 downloadIntent.setDataAndType(Uri.parse(url), "text/html");
3065 // Flag the intent to open in a new task.
3066 downloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3068 // Show the chooser.
3069 startActivity(Intent.createChooser(downloadIntent, getString(R.string.download_with_external_app)));
3072 public void onSaveUrl(@NonNull String originalUrlString, @NonNull String fileNameString, @NonNull DialogFragment dialogFragment) {
3073 // Store the URL. This will be used in the save URL activity result launcher.
3074 if (originalUrlString.startsWith("data:")) {
3075 // Save the original URL.
3076 saveUrlString = originalUrlString;
3079 Dialog dialog = dialogFragment.getDialog();
3081 // Remove the incorrect lint warning below that the dialog might be null.
3082 assert dialog != null;
3084 // Get a handle for the dialog URL edit text.
3085 EditText dialogUrlEditText = dialog.findViewById(R.id.url_edittext);
3087 // Get the URL from the edit text, which may have been modified.
3088 saveUrlString = dialogUrlEditText.getText().toString();
3091 // Open the file picker.
3092 saveUrlActivityResultLauncher.launch(fileNameString);
3095 // Remove the warning that `OnTouchListener()` needs to override `performClick()`, as the only purpose of setting the `OnTouchListener()` is to make it do nothing.
3096 @SuppressLint("ClickableViewAccessibility")
3097 private void initializeApp() {
3098 // Get a handle for the input method.
3099 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
3101 // Remove the lint warning below that the input method manager might be null.
3102 assert inputMethodManager != null;
3104 // Initialize the color spans for highlighting the URLs.
3105 initialGrayColorSpan = new ForegroundColorSpan(getColor(R.color.gray_500));
3106 finalGrayColorSpan = new ForegroundColorSpan(getColor(R.color.gray_500));
3107 redColorSpan = new ForegroundColorSpan(getColor(R.color.red_text));
3109 // Remove the formatting from the URL edit text when the user is editing the text.
3110 urlEditText.setOnFocusChangeListener((View v, boolean hasFocus) -> {
3111 if (hasFocus) { // The user is editing the URL text box.
3112 // Remove the highlighting.
3113 urlEditText.getText().removeSpan(redColorSpan);
3114 urlEditText.getText().removeSpan(initialGrayColorSpan);
3115 urlEditText.getText().removeSpan(finalGrayColorSpan);
3116 } else { // The user has stopped editing the URL text box.
3117 // Move to the beginning of the string.
3118 urlEditText.setSelection(0);
3120 // Reapply the highlighting.
3125 // Set the go button on the keyboard to load the URL in `urlTextBox`.
3126 urlEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
3127 // If the event is a key-down event on the `enter` button, load the URL.
3128 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
3129 // Load the URL into the mainWebView and consume the event.
3130 loadUrlFromTextBox();
3132 // If the enter key was pressed, consume the event.
3135 // If any other key was pressed, do not consume the event.
3140 // Create an Orbot status broadcast receiver.
3141 orbotStatusBroadcastReceiver = new BroadcastReceiver() {
3143 public void onReceive(Context context, Intent intent) {
3144 // Store the content of the status message in `orbotStatus`.
3145 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
3147 // If Privacy Browser is waiting on the proxy, load the website now that Orbot is connected.
3148 if ((orbotStatus != null) && orbotStatus.equals(ProxyHelper.ORBOT_STATUS_ON) && waitingForProxy) {
3149 // Reset the waiting for proxy status.
3150 waitingForProxy = false;
3152 // Get a list of the current fragments.
3153 List<Fragment> fragmentList = getSupportFragmentManager().getFragments();
3155 // Check each fragment to see if it is a waiting for proxy dialog. Sometimes more than one is displayed.
3156 for (int i = 0; i < fragmentList.size(); i++) {
3157 // Get the fragment tag.
3158 String fragmentTag = fragmentList.get(i).getTag();
3160 // Check to see if it is the waiting for proxy dialog.
3161 if ((fragmentTag!= null) && fragmentTag.equals(getString(R.string.waiting_for_proxy_dialog))) {
3162 // Dismiss the waiting for proxy dialog.
3163 ((DialogFragment) fragmentList.get(i)).dismiss();
3167 // Reload existing URLs and load any URLs that are waiting for the proxy.
3168 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3169 // Get the WebView tab fragment.
3170 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3172 // Get the fragment view.
3173 View fragmentView = webViewTabFragment.getView();
3175 // Only process the WebViews if they exist.
3176 if (fragmentView != null) {
3177 // Get the nested scroll WebView from the tab fragment.
3178 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3180 // Get the waiting for proxy URL string.
3181 String waitingForProxyUrlString = nestedScrollWebView.getWaitingForProxyUrlString();
3183 // Load the pending URL if it exists.
3184 if (!waitingForProxyUrlString.isEmpty()) { // A URL is waiting to be loaded.
3186 loadUrl(nestedScrollWebView, waitingForProxyUrlString);
3188 // Reset the waiting for proxy URL string.
3189 nestedScrollWebView.setWaitingForProxyUrlString("");
3190 } else { // No URL is waiting to be loaded.
3191 // Reload the existing URL.
3192 nestedScrollWebView.reload();
3200 // Register the Orbot status broadcast receiver on `this` context.
3201 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
3203 // Get handles for views that need to be modified.
3204 LinearLayout bookmarksHeaderLinearLayout = findViewById(R.id.bookmarks_header_linearlayout);
3205 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
3206 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
3207 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
3208 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
3209 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
3211 // Update the web view pager every time a tab is modified.
3212 webViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
3214 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
3219 public void onPageSelected(int position) {
3220 // Close the find on page bar if it is open.
3221 closeFindOnPage(null);
3223 // Set the current WebView.
3224 setCurrentWebView(position);
3226 // 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.
3227 if (tabLayout.getSelectedTabPosition() != position) {
3228 // Wait until the new tab has been created.
3229 tabLayout.post(() -> {
3230 // Get a handle for the tab.
3231 TabLayout.Tab tab = tabLayout.getTabAt(position);
3233 // Assert that the tab is not null.
3243 public void onPageScrollStateChanged(int state) {
3248 // Display the View SSL Certificate dialog when the currently selected tab is reselected.
3249 tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
3251 public void onTabSelected(TabLayout.Tab tab) {
3252 // Select the same page in the view pager.
3253 webViewPager.setCurrentItem(tab.getPosition());
3257 public void onTabUnselected(TabLayout.Tab tab) {
3262 public void onTabReselected(TabLayout.Tab tab) {
3263 // Instantiate the View SSL Certificate dialog.
3264 DialogFragment viewSslCertificateDialogFragment = ViewSslCertificateDialog.displayDialog(currentWebView.getWebViewFragmentId(), currentWebView.getFavoriteOrDefaultIcon());
3266 // Display the View SSL Certificate dialog.
3267 viewSslCertificateDialogFragment.show(getSupportFragmentManager(), getString(R.string.view_ssl_certificate));
3271 // Set a touch listener on the bookmarks header linear layout so that touches don't pass through to the button underneath.
3272 bookmarksHeaderLinearLayout.setOnTouchListener((view, motionEvent) -> {
3273 // Consume the touch.
3277 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
3278 launchBookmarksActivityFab.setOnClickListener(v -> {
3279 // Get a copy of the favorite icon bitmap.
3280 Bitmap favoriteIconBitmap = currentWebView.getFavoriteOrDefaultIcon();
3282 // Create a favorite icon byte array output stream.
3283 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3285 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
3286 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
3288 // Convert the favorite icon byte array stream to a byte array.
3289 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
3291 // Create an intent to launch the bookmarks activity.
3292 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
3294 // Add the extra information to the intent.
3295 bookmarksIntent.putExtra("current_url", currentWebView.getUrl());
3296 bookmarksIntent.putExtra("current_title", currentWebView.getTitle());
3297 bookmarksIntent.putExtra("current_folder", currentBookmarksFolder);
3298 bookmarksIntent.putExtra("favorite_icon_byte_array", favoriteIconByteArray);
3301 startActivity(bookmarksIntent);
3304 // Set the create new bookmark folder FAB to display an alert dialog.
3305 createBookmarkFolderFab.setOnClickListener(v -> {
3306 // Create a create bookmark folder dialog.
3307 DialogFragment createBookmarkFolderDialog = CreateBookmarkFolderDialog.createBookmarkFolder(currentWebView.getFavoriteOrDefaultIcon());
3309 // Show the create bookmark folder dialog.
3310 createBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.create_folder));
3313 // Set the create new bookmark FAB to display an alert dialog.
3314 createBookmarkFab.setOnClickListener(view -> {
3315 // Instantiate the create bookmark dialog.
3316 DialogFragment createBookmarkDialog = CreateBookmarkDialog.createBookmark(currentWebView.getUrl(), currentWebView.getTitle(), currentWebView.getFavoriteOrDefaultIcon());
3318 // Display the create bookmark dialog.
3319 createBookmarkDialog.show(getSupportFragmentManager(), getString(R.string.create_bookmark));
3322 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
3323 findOnPageEditText.addTextChangedListener(new TextWatcher() {
3325 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
3330 public void onTextChanged(CharSequence s, int start, int before, int count) {
3335 public void afterTextChanged(Editable s) {
3336 // 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.
3337 if (currentWebView != null) {
3338 currentWebView.findAllAsync(findOnPageEditText.getText().toString());
3343 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
3344 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
3345 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
3346 // Hide the soft keyboard.
3347 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
3349 // Consume the event.
3351 } else { // A different key was pressed.
3352 // Do not consume the event.
3357 // Implement swipe to refresh.
3358 swipeRefreshLayout.setOnRefreshListener(() -> {
3359 // Reload the website.
3360 currentWebView.reload();
3363 // Store the default progress view offsets for use later in `initializeWebView()`.
3364 defaultProgressViewStartOffset = swipeRefreshLayout.getProgressViewStartOffset();
3365 defaultProgressViewEndOffset = swipeRefreshLayout.getProgressViewEndOffset();
3367 // Set the refresh color scheme according to the theme.
3368 swipeRefreshLayout.setColorSchemeResources(R.color.blue_text);
3370 // Initialize a color background typed value.
3371 TypedValue colorBackgroundTypedValue = new TypedValue();
3373 // Get the color background from the theme.
3374 getTheme().resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true);
3376 // Get the color background int from the typed value.
3377 int colorBackgroundInt = colorBackgroundTypedValue.data;
3379 // Set the swipe refresh background color.
3380 swipeRefreshLayout.setProgressBackgroundColorSchemeColor(colorBackgroundInt);
3382 // The drawer titles identify the drawer layouts in accessibility mode.
3383 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
3384 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
3386 // Load the bookmarks folder.
3387 loadBookmarksFolder();
3389 // Handle clicks on bookmarks.
3390 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
3391 // Convert the id from long to int to match the format of the bookmarks database.
3392 int databaseId = (int) id;
3394 // Get the bookmark cursor for this ID.
3395 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseId);
3397 // Move the bookmark cursor to the first row.
3398 bookmarkCursor.moveToFirst();
3400 // Act upon the bookmark according to the type.
3401 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
3402 // Store the new folder name in `currentBookmarksFolder`.
3403 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME));
3405 // Load the new folder.
3406 loadBookmarksFolder();
3407 } else { // The selected bookmark is not a folder.
3408 // Load the bookmark URL.
3409 loadUrl(currentWebView, bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_URL)));
3411 // Close the bookmarks drawer.
3412 drawerLayout.closeDrawer(GravityCompat.END);
3415 // Close the `Cursor`.
3416 bookmarkCursor.close();
3419 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
3420 // Convert the database ID from `long` to `int`.
3421 int databaseId = (int) id;
3423 // Find out if the selected bookmark is a folder.
3424 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
3426 // Check to see if the bookmark is a folder.
3427 if (isFolder) { // The bookmark is a folder.
3428 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
3429 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME));
3431 // Instantiate the edit folder bookmark dialog.
3432 DialogFragment editBookmarkFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId, currentWebView.getFavoriteOrDefaultIcon());
3434 // Show the edit folder bookmark dialog.
3435 editBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.edit_folder));
3436 } else { // The bookmark is not a folder.
3437 // Get the bookmark cursor for this ID.
3438 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseId);
3440 // Move the bookmark cursor to the first row.
3441 bookmarkCursor.moveToFirst();
3443 // Load the bookmark in a new tab.
3444 addNewTab(bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_URL)), true);
3446 // Close the bookmarks drawer.
3447 drawerLayout.closeDrawer(GravityCompat.END);
3450 // Consume the event.
3454 // The drawer listener is used to update the navigation menu.
3455 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
3457 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
3461 public void onDrawerOpened(@NonNull View drawerView) {
3465 public void onDrawerClosed(@NonNull View drawerView) {
3466 // Reset the drawer icon when the drawer is closed. Otherwise, it is an arrow if the drawer is open when the app is restarted.
3467 actionBarDrawerToggle.syncState();
3471 public void onDrawerStateChanged(int newState) {
3472 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // A drawer is opening or closing.
3473 // Update the navigation menu items if the WebView is not null.
3474 if (currentWebView != null) {
3475 navigationBackMenuItem.setEnabled(currentWebView.canGoBack());
3476 navigationForwardMenuItem.setEnabled(currentWebView.canGoForward());
3477 navigationHistoryMenuItem.setEnabled((currentWebView.canGoBack() || currentWebView.canGoForward()));
3478 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
3480 // Hide the keyboard (if displayed).
3481 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
3484 // 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.
3485 urlEditText.clearFocus();
3487 // 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.
3488 if (currentWebView != null) {
3489 // Clearing the focus from the WebView removes any text selection markers and context menus, which otherwise draw above the open drawers.
3490 currentWebView.clearFocus();
3496 // Inflate a bare WebView to get the default user agent. It is not used to render content on the screen.
3497 @SuppressLint("InflateParams") View webViewLayout = getLayoutInflater().inflate(R.layout.bare_webview, null, false);
3499 // Get a handle for the WebView.
3500 WebView bareWebView = webViewLayout.findViewById(R.id.bare_webview);
3502 // Store the default user agent.
3503 webViewDefaultUserAgent = bareWebView.getSettings().getUserAgentString();
3505 // Destroy the bare WebView.
3506 bareWebView.destroy();
3509 private void applyAppSettings() {
3510 // Get a handle for the shared preferences.
3511 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3513 // Store the values from the shared preferences in variables.
3514 incognitoModeEnabled = sharedPreferences.getBoolean(getString(R.string.incognito_mode_key), false);
3515 sanitizeTrackingQueries = sharedPreferences.getBoolean(getString(R.string.tracking_queries_key), true);
3516 sanitizeAmpRedirects = sharedPreferences.getBoolean(getString(R.string.amp_redirects_key), true);
3517 proxyMode = sharedPreferences.getString(getString(R.string.proxy_key), getString(R.string.proxy_default_value));
3518 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean(getString(R.string.full_screen_browsing_mode_key), false);
3519 hideAppBar = sharedPreferences.getBoolean(getString(R.string.hide_app_bar_key), true);
3520 downloadWithExternalApp = sharedPreferences.getBoolean(getString(R.string.download_with_external_app_key), false);
3521 scrollAppBar = sharedPreferences.getBoolean(getString(R.string.scroll_app_bar_key), true);
3523 // Apply the saved proxy mode if the app has been restarted.
3524 if (savedProxyMode != null) {
3525 // Apply the saved proxy mode.
3526 proxyMode = savedProxyMode;
3528 // Reset the saved proxy mode.
3529 savedProxyMode = null;
3532 // Get the search string.
3533 String searchString = sharedPreferences.getString(getString(R.string.search_key), getString(R.string.search_default_value));
3535 // Set the search string.
3536 if (searchString.equals(getString(R.string.custom_url_item)))
3537 searchURL = sharedPreferences.getString(getString(R.string.search_custom_url_key), getString(R.string.search_custom_url_default_value));
3539 searchURL = searchString;
3544 // Adjust the layout and scrolling parameters according to the position of the app bar.
3545 if (bottomAppBar) { // The app bar is on the bottom.
3547 if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) { // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
3548 // Reset the WebView padding to fill the available space.
3549 swipeRefreshLayout.setPadding(0, 0, 0, 0);
3550 } else { // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
3551 // Move the WebView above the app bar layout.
3552 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight);
3554 // Show the app bar if it is scrolled off the screen.
3555 if (appBarLayout.getTranslationY() != 0) {
3556 // Animate the bottom app bar onto the screen.
3557 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0);
3560 objectAnimator.start();
3563 } else { // The app bar is on the top.
3564 // Get the current layout parameters. Using coordinator layout parameters allows the `setBehavior()` command and using app bar layout parameters allows the `setScrollFlags()` command.
3565 CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
3566 AppBarLayout.LayoutParams toolbarLayoutParams = (AppBarLayout.LayoutParams) toolbar.getLayoutParams();
3567 AppBarLayout.LayoutParams findOnPageLayoutParams = (AppBarLayout.LayoutParams) findOnPageLinearLayout.getLayoutParams();
3568 AppBarLayout.LayoutParams tabsLayoutParams = (AppBarLayout.LayoutParams) tabsLinearLayout.getLayoutParams();
3570 // Add the scrolling behavior to the layout parameters.
3572 // Enable scrolling of the app bar.
3573 swipeRefreshLayoutParams.setBehavior(new AppBarLayout.ScrollingViewBehavior());
3574 toolbarLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3575 findOnPageLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3576 tabsLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3578 // Disable scrolling of the app bar.
3579 swipeRefreshLayoutParams.setBehavior(null);
3580 toolbarLayoutParams.setScrollFlags(0);
3581 findOnPageLayoutParams.setScrollFlags(0);
3582 tabsLayoutParams.setScrollFlags(0);
3584 // Expand the app bar if it is currently collapsed.
3585 appBarLayout.setExpanded(true);
3588 // Set the app bar scrolling for each WebView.
3589 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3590 // Get the WebView tab fragment.
3591 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3593 // Get the fragment view.
3594 View fragmentView = webViewTabFragment.getView();
3596 // Only modify the WebViews if they exist.
3597 if (fragmentView != null) {
3598 // Get the nested scroll WebView from the tab fragment.
3599 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3601 // Set the app bar scrolling.
3602 nestedScrollWebView.setNestedScrollingEnabled(scrollAppBar);
3607 // Update the full screen browsing mode settings.
3608 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
3609 // Update the visibility of the app bar, which might have changed in the settings.
3611 // Hide the tab linear layout.
3612 tabsLinearLayout.setVisibility(View.GONE);
3614 // Hide the action bar.
3617 // Show the tab linear layout.
3618 tabsLinearLayout.setVisibility(View.VISIBLE);
3620 // Show the action bar.
3624 /* Hide the system bars.
3625 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3626 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
3627 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3628 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3630 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
3631 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3632 } else { // Privacy Browser is not in full screen browsing mode.
3633 // 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.
3634 inFullScreenBrowsingMode = false;
3636 // Show the tab linear layout.
3637 tabsLinearLayout.setVisibility(View.VISIBLE);
3639 // Show the action bar.
3642 // Remove the `SYSTEM_UI` flags from the root frame layout.
3643 rootFrameLayout.setSystemUiVisibility(0);
3648 public void navigateHistory(@NonNull String url, int steps) {
3649 // Apply the domain settings.
3650 applyDomainSettings(currentWebView, url, false, false, false);
3652 // Load the history entry.
3653 currentWebView.goBackOrForward(steps);
3657 public void pinnedErrorGoBack() {
3658 // Get the current web back forward list.
3659 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
3661 // Get the previous entry URL.
3662 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
3664 // Apply the domain settings.
3665 applyDomainSettings(currentWebView, previousUrl, false, false, false);
3668 currentWebView.goBack();
3671 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
3672 @SuppressLint("SetJavaScriptEnabled")
3673 private void applyDomainSettings(NestedScrollWebView nestedScrollWebView, String url, boolean resetTab, boolean reloadWebsite, boolean loadUrl) {
3674 // Store the current URL.
3675 nestedScrollWebView.setCurrentUrl(url);
3677 // Parse the URL into a URI.
3678 Uri uri = Uri.parse(url);
3680 // Extract the domain from `uri`.
3681 String newHostName = uri.getHost();
3683 // Strings don't like to be null.
3684 if (newHostName == null) {
3688 // 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.
3689 if (!nestedScrollWebView.getCurrentDomainName().equals(newHostName) || newHostName.equals("")) {
3690 // Set the new host name as the current domain name.
3691 nestedScrollWebView.setCurrentDomainName(newHostName);
3693 // Reset the ignoring of pinned domain information.
3694 nestedScrollWebView.setIgnorePinnedDomainInformation(false);
3696 // Clear any pinned SSL certificate or IP addresses.
3697 nestedScrollWebView.clearPinnedSslCertificate();
3698 nestedScrollWebView.setPinnedIpAddresses("");
3700 // Reset the favorite icon if specified.
3702 // Initialize the favorite icon.
3703 nestedScrollWebView.initializeFavoriteIcon();
3705 // Get the current page position.
3706 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
3708 // Get the corresponding tab.
3709 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
3711 // Update the tab if it isn't null, which sometimes happens when restarting from the background.
3713 // Get the tab custom view.
3714 View tabCustomView = tab.getCustomView();
3716 // Remove the warning below that the tab custom view might be null.
3717 assert tabCustomView != null;
3719 // Get the tab views.
3720 ImageView tabFavoriteIconImageView = tabCustomView.findViewById(R.id.favorite_icon_imageview);
3721 TextView tabTitleTextView = tabCustomView.findViewById(R.id.title_textview);
3723 // Set the default favorite icon as the favorite icon for this tab.
3724 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(nestedScrollWebView.getFavoriteOrDefaultIcon(), 64, 64, true));
3726 // Set the loading title text.
3727 tabTitleTextView.setText(R.string.loading);
3731 // Get a full domain name cursor.
3732 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3734 // Initialize `domainSettingsSet`.
3735 Set<String> domainSettingsSet = new HashSet<>();
3737 // Get the domain name column index.
3738 int domainNameColumnIndex = domainNameCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.DOMAIN_NAME);
3740 // Populate the domain settings set.
3741 for (int i = 0; i < domainNameCursor.getCount(); i++) {
3742 // Move the domains cursor to the current row.
3743 domainNameCursor.moveToPosition(i);
3745 // Store the domain name in the domain settings set.
3746 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3749 // Close the domain name cursor.
3750 domainNameCursor.close();
3752 // Initialize the domain name in database variable.
3753 String domainNameInDatabase = null;
3755 // Check the hostname against the domain settings set.
3756 if (domainSettingsSet.contains(newHostName)) { // The hostname is contained in the domain settings set.
3757 // Record the domain name in the database.
3758 domainNameInDatabase = newHostName;
3760 // Set the domain settings applied tracker to true.
3761 nestedScrollWebView.setDomainSettingsApplied(true);
3762 } else { // The hostname is not contained in the domain settings set.
3763 // Set the domain settings applied tracker to false.
3764 nestedScrollWebView.setDomainSettingsApplied(false);
3767 // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3768 while (!nestedScrollWebView.getDomainSettingsApplied() && newHostName.contains(".")) { // Stop checking if domain settings are already applied or there are no more `.` in the hostname.
3769 if (domainSettingsSet.contains("*." + newHostName)) { // Check the host name prepended by `*.`.
3770 // Set the domain settings applied tracker to true.
3771 nestedScrollWebView.setDomainSettingsApplied(true);
3773 // Store the applied domain names as it appears in the database.
3774 domainNameInDatabase = "*." + newHostName;
3777 // Strip out the lowest subdomain of of the host name.
3778 newHostName = newHostName.substring(newHostName.indexOf(".") + 1);
3782 // Get a handle for the shared preferences.
3783 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3785 // Store the general preference information.
3786 String defaultFontSizeString = sharedPreferences.getString(getString(R.string.font_size_key), getString(R.string.font_size_default_value));
3787 String defaultUserAgentName = sharedPreferences.getString(getString(R.string.user_agent_key), getString(R.string.user_agent_default_value));
3788 boolean defaultSwipeToRefresh = sharedPreferences.getBoolean(getString(R.string.swipe_to_refresh_key), true);
3789 String webViewTheme = sharedPreferences.getString(getString(R.string.webview_theme_key), getString(R.string.webview_theme_default_value));
3790 boolean wideViewport = sharedPreferences.getBoolean(getString(R.string.wide_viewport_key), true);
3791 boolean displayWebpageImages = sharedPreferences.getBoolean(getString(R.string.display_webpage_images_key), true);
3793 // Get the WebView theme entry values string array.
3794 String[] webViewThemeEntryValuesStringArray = getResources().getStringArray(R.array.webview_theme_entry_values);
3796 // Get a handle for the cookie manager.
3797 CookieManager cookieManager = CookieManager.getInstance();
3799 // Initialize the user agent array adapter and string array.
3800 ArrayAdapter<CharSequence> userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item);
3801 String[] userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
3803 if (nestedScrollWebView.getDomainSettingsApplied()) { // The url has custom domain settings.
3804 // Remove the incorrect lint warning below that the domain name in database might be null.
3805 assert domainNameInDatabase != null;
3807 // Get a cursor for the current host.
3808 Cursor currentDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3810 // Move to the first position.
3811 currentDomainSettingsCursor.moveToFirst();
3813 // Get the settings from the cursor.
3814 nestedScrollWebView.setDomainSettingsDatabaseId(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ID)));
3815 nestedScrollWebView.getSettings().setJavaScriptEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3816 nestedScrollWebView.setAcceptCookies(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.COOKIES)) == 1);
3817 nestedScrollWebView.getSettings().setDomStorageEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3818 // Form data can be removed once the minimum API >= 26.
3819 boolean saveFormData = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3820 nestedScrollWebView.setEasyListEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3821 nestedScrollWebView.setEasyPrivacyEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3822 nestedScrollWebView.setFanboysAnnoyanceListEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(
3823 DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3824 nestedScrollWebView.setFanboysSocialBlockingListEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(
3825 DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3826 nestedScrollWebView.setUltraListEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ULTRALIST)) == 1);
3827 nestedScrollWebView.setUltraPrivacyEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_ULTRAPRIVACY)) == 1);
3828 nestedScrollWebView.setBlockAllThirdPartyRequests(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(
3829 DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
3830 String userAgentName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.USER_AGENT));
3831 int fontSize = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.FONT_SIZE));
3832 int swipeToRefreshInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
3833 int webViewThemeInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.WEBVIEW_THEME));
3834 int wideViewportInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.WIDE_VIEWPORT));
3835 int displayWebpageImagesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.DISPLAY_IMAGES));
3836 boolean pinnedSslCertificate = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3837 String pinnedSslIssuedToCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3838 String pinnedSslIssuedToOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3839 String pinnedSslIssuedToUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3840 String pinnedSslIssuedByCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3841 String pinnedSslIssuedByOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3842 String pinnedSslIssuedByUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3843 Date pinnedSslStartDate = new Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_START_DATE)));
3844 Date pinnedSslEndDate = new Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_END_DATE)));
3845 boolean pinnedIpAddresses = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.PINNED_IP_ADDRESSES)) == 1);
3846 String pinnedHostIpAddresses = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.IP_ADDRESSES));
3848 // Close the current host domain settings cursor.
3849 currentDomainSettingsCursor.close();
3851 // If there is a pinned SSL certificate, store it in the WebView.
3852 if (pinnedSslCertificate) {
3853 nestedScrollWebView.setPinnedSslCertificate(pinnedSslIssuedToCName, pinnedSslIssuedToOName, pinnedSslIssuedToUName, pinnedSslIssuedByCName, pinnedSslIssuedByOName, pinnedSslIssuedByUName,
3854 pinnedSslStartDate, pinnedSslEndDate);
3857 // If there is a pinned IP address, store it in the WebView.
3858 if (pinnedIpAddresses) {
3859 nestedScrollWebView.setPinnedIpAddresses(pinnedHostIpAddresses);
3862 // Apply the cookie domain settings.
3863 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptCookies());
3865 // Apply the form data setting if the API < 26.
3866 if (Build.VERSION.SDK_INT < 26) {
3867 nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
3870 // Apply the font size.
3871 try { // Try the specified font size to see if it is valid.
3872 if (fontSize == 0) { // Apply the default font size.
3873 // Try to set the font size from the value in the app settings.
3874 nestedScrollWebView.getSettings().setTextZoom(Integer.parseInt(defaultFontSizeString));
3875 } else { // Apply the font size from domain settings.
3876 nestedScrollWebView.getSettings().setTextZoom(fontSize);
3878 } catch (Exception exception) { // The specified font size is invalid
3879 // Set the font size to be 100%
3880 nestedScrollWebView.getSettings().setTextZoom(100);
3883 // Set the user agent.
3884 if (userAgentName.equals(getString(R.string.system_default_user_agent))) { // Use the system default user agent.
3885 // Get the array position of the default user agent name.
3886 int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3888 // Set the user agent according to the system default.
3889 switch (defaultUserAgentArrayPosition) {
3890 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
3891 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3892 nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
3895 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3896 // Set the user agent to `""`, which uses the default value.
3897 nestedScrollWebView.getSettings().setUserAgentString("");
3900 case SETTINGS_CUSTOM_USER_AGENT:
3901 // Set the default custom user agent.
3902 nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString(getString(R.string.custom_user_agent_key), getString(R.string.custom_user_agent_default_value)));
3906 // Get the user agent string from the user agent data array
3907 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
3909 } else { // Set the user agent according to the stored name.
3910 // Get the array position of the user agent name.
3911 int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
3913 switch (userAgentArrayPosition) {
3914 case UNRECOGNIZED_USER_AGENT: // The user agent name contains a custom user agent.
3915 nestedScrollWebView.getSettings().setUserAgentString(userAgentName);
3918 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3919 // Set the user agent to `""`, which uses the default value.
3920 nestedScrollWebView.getSettings().setUserAgentString("");
3924 // Get the user agent string from the user agent data array.
3925 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3929 // Set swipe to refresh.
3930 switch (swipeToRefreshInt) {
3931 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
3932 // Store the swipe to refresh status in the nested scroll WebView.
3933 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
3935 // Update the swipe refresh layout.
3936 if (defaultSwipeToRefresh) { // Swipe to refresh is enabled.
3937 // Update the status of the swipe refresh layout if the current WebView is not null (crash reports indicate that in some unexpected way it sometimes is null).
3938 if (currentWebView != null) {
3939 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
3940 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
3942 } else { // Swipe to refresh is disabled.
3943 // Disable the swipe refresh layout.
3944 swipeRefreshLayout.setEnabled(false);
3948 case DomainsDatabaseHelper.ENABLED:
3949 // Store the swipe to refresh status in the nested scroll WebView.
3950 nestedScrollWebView.setSwipeToRefresh(true);
3953 // Update the status of the swipe refresh layout if the current WebView is not null (crash reports indicate that in some unexpected way it sometimes is null).
3954 if (currentWebView != null) {
3955 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
3956 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
3960 case DomainsDatabaseHelper.DISABLED:
3961 // Store the swipe to refresh status in the nested scroll WebView.
3962 nestedScrollWebView.setSwipeToRefresh(false);
3964 // Disable swipe to refresh.
3965 swipeRefreshLayout.setEnabled(false);
3969 // Set the WebView theme if device is running API >= 29 and algorithmic darkening is supported.
3970 if ((Build.VERSION.SDK_INT >= 29) && WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {
3971 // Set the WebView theme.
3972 switch (webViewThemeInt) {
3973 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
3974 // Set the WebView theme. A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
3975 if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) { // The light theme is selected.
3976 // Turn off algorithmic darkening.
3977 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), false);
3978 } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) { // The dark theme is selected.
3979 // Turn on algorithmic darkening.
3980 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), true);
3981 } else { // The system default theme is selected.
3982 // Get the current system theme status.
3983 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
3985 // Set the algorithmic darkening according to the current system theme status.
3986 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES));
3990 case DomainsDatabaseHelper.LIGHT_THEME:
3991 // Turn off algorithmic darkening.
3992 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), false);
3995 case DomainsDatabaseHelper.DARK_THEME:
3996 // Turn on algorithmic darkening.
3997 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), true);
4002 // Set the viewport.
4003 switch (wideViewportInt) {
4004 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4005 nestedScrollWebView.getSettings().setUseWideViewPort(wideViewport);
4008 case DomainsDatabaseHelper.ENABLED:
4009 nestedScrollWebView.getSettings().setUseWideViewPort(true);
4012 case DomainsDatabaseHelper.DISABLED:
4013 nestedScrollWebView.getSettings().setUseWideViewPort(false);
4017 // Set the loading of webpage images.
4018 switch (displayWebpageImagesInt) {
4019 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4020 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
4023 case DomainsDatabaseHelper.ENABLED:
4024 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(true);
4027 case DomainsDatabaseHelper.DISABLED:
4028 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(false);
4032 // Set a background on the URL relative layout to indicate that custom domain settings are being used.
4033 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.domain_settings_url_background, null));
4034 } else { // The new URL does not have custom domain settings. Load the defaults.
4035 // Store the values from the shared preferences.
4036 nestedScrollWebView.getSettings().setJavaScriptEnabled(sharedPreferences.getBoolean(getString(R.string.javascript_key), false));
4037 nestedScrollWebView.setAcceptCookies(sharedPreferences.getBoolean(getString(R.string.cookies_key), false));
4038 nestedScrollWebView.getSettings().setDomStorageEnabled(sharedPreferences.getBoolean(getString(R.string.dom_storage_key), false));
4039 boolean saveFormData = sharedPreferences.getBoolean(getString(R.string.save_form_data_key), false); // Form data can be removed once the minimum API >= 26.
4040 nestedScrollWebView.setEasyListEnabled(sharedPreferences.getBoolean(getString(R.string.easylist_key), true));
4041 nestedScrollWebView.setEasyPrivacyEnabled(sharedPreferences.getBoolean(getString(R.string.easyprivacy_key), true));
4042 nestedScrollWebView.setFanboysAnnoyanceListEnabled(sharedPreferences.getBoolean(getString(R.string.fanboys_annoyance_list_key), true));
4043 nestedScrollWebView.setFanboysSocialBlockingListEnabled(sharedPreferences.getBoolean(getString(R.string.fanboys_social_blocking_list_key), true));
4044 nestedScrollWebView.setUltraListEnabled(sharedPreferences.getBoolean(getString(R.string.ultralist_key), true));
4045 nestedScrollWebView.setUltraPrivacyEnabled(sharedPreferences.getBoolean(getString(R.string.ultraprivacy_key), true));
4046 nestedScrollWebView.setBlockAllThirdPartyRequests(sharedPreferences.getBoolean(getString(R.string.block_all_third_party_requests_key), false));
4048 // Apply the default cookie setting.
4049 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptCookies());
4051 // Apply the default font size setting.
4053 // Try to set the font size from the value in the app settings.
4054 nestedScrollWebView.getSettings().setTextZoom(Integer.parseInt(defaultFontSizeString));
4055 } catch (Exception exception) {
4056 // If the app settings value is invalid, set the font size to 100%.
4057 nestedScrollWebView.getSettings().setTextZoom(100);
4060 // Apply the form data setting if the API < 26.
4061 if (Build.VERSION.SDK_INT < 26) {
4062 nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
4065 // Store the swipe to refresh status in the nested scroll WebView.
4066 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
4068 // Update the swipe refresh layout.
4069 if (defaultSwipeToRefresh) { // Swipe to refresh is enabled.
4070 // Update the status of the swipe refresh layout if the current WebView is not null (crash reports indicate that in some unexpected way it sometimes is null).
4071 if (currentWebView != null) {
4072 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
4073 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
4075 } else { // Swipe to refresh is disabled.
4076 // Disable the swipe refresh layout.
4077 swipeRefreshLayout.setEnabled(false);
4080 // Reset the pinned variables.
4081 nestedScrollWebView.setDomainSettingsDatabaseId(-1);
4083 // Get the array position of the user agent name.
4084 int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
4086 // Set the user agent.
4087 switch (userAgentArrayPosition) {
4088 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
4089 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
4090 nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
4093 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4094 // Set the user agent to `""`, which uses the default value.
4095 nestedScrollWebView.getSettings().setUserAgentString("");
4098 case SETTINGS_CUSTOM_USER_AGENT:
4099 // Set the default custom user agent.
4100 nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString(getString(R.string.custom_user_agent_key), getString(R.string.custom_user_agent_default_value)));
4104 // Get the user agent string from the user agent data array
4105 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4108 // Set the WebView theme if device is running API >= 29 and algorithmic darkening is supported.
4109 if ((Build.VERSION.SDK_INT >= 29) && WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {
4110 // Set the WebView theme. A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
4111 if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) { // the light theme is selected.
4112 // Turn off algorithmic darkening.
4113 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), false);
4114 } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) { // The dark theme is selected.
4115 // Turn on algorithmic darkening.
4116 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), true);
4117 } else { // The system default theme is selected.
4118 // Get the current system theme status.
4119 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4121 // Set the algorithmic darkening according to the current system theme status.
4122 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), currentThemeStatus == Configuration.UI_MODE_NIGHT_YES);
4126 // Set the viewport.
4127 nestedScrollWebView.getSettings().setUseWideViewPort(wideViewport);
4129 // Set the loading of webpage images.
4130 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
4132 // Set a transparent background on the URL relative layout.
4133 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.color.transparent, null));
4136 // Close the domains database helper.
4137 domainsDatabaseHelper.close();
4139 // Update the privacy icons.
4140 updatePrivacyIcons(true);
4143 // Reload the website if returning from the Domains activity.
4144 if (reloadWebsite) {
4145 nestedScrollWebView.reload();
4148 // 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.
4150 nestedScrollWebView.loadUrl(url);
4154 private void applyProxy(boolean reloadWebViews) {
4155 // Set the proxy according to the mode.
4156 proxyHelper.setProxy(getApplicationContext(), appBarLayout, proxyMode);
4158 // Reset the waiting for proxy tracker.
4159 waitingForProxy = false;
4161 // Get the current theme status.
4162 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4164 // Update the user interface and reload the WebViews if requested.
4165 switch (proxyMode) {
4166 case ProxyHelper.NONE:
4167 // Initialize a color background typed value.
4168 TypedValue colorBackgroundTypedValue = new TypedValue();
4170 // Get the color background from the theme.
4171 getTheme().resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true);
4173 // Get the color background int from the typed value.
4174 int colorBackgroundInt = colorBackgroundTypedValue.data;
4176 // Set the default app bar layout background.
4177 appBarLayout.setBackgroundColor(colorBackgroundInt);
4180 case ProxyHelper.TOR:
4181 // Set the app bar background to indicate proxying through Orbot is enabled.
4182 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4183 appBarLayout.setBackgroundResource(R.color.blue_50);
4185 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4188 // Check to see if Orbot is installed.
4190 // Get the package manager.
4191 PackageManager packageManager = getPackageManager();
4193 // 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.
4194 packageManager.getPackageInfo("org.torproject.android", 0);
4196 // Check to see if the proxy is ready.
4197 if (!orbotStatus.equals(ProxyHelper.ORBOT_STATUS_ON)) { // Orbot is not ready.
4198 // Set the waiting for proxy status.
4199 waitingForProxy = true;
4201 // Show the waiting for proxy dialog if it isn't already displayed.
4202 if (getSupportFragmentManager().findFragmentByTag(getString(R.string.waiting_for_proxy_dialog)) == null) {
4203 // Get a handle for the waiting for proxy alert dialog.
4204 DialogFragment waitingForProxyDialogFragment = new WaitingForProxyDialog();
4206 // Try to show the dialog. Sometimes the window is not yet active if returning from Settings.
4208 // Show the waiting for proxy alert dialog.
4209 waitingForProxyDialogFragment.show(getSupportFragmentManager(), getString(R.string.waiting_for_proxy_dialog));
4210 } catch (Exception waitingForTorException) {
4211 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
4212 pendingDialogsArrayList.add(new PendingDialog(waitingForProxyDialogFragment, getString(R.string.waiting_for_proxy_dialog)));
4216 } catch (PackageManager.NameNotFoundException exception) { // Orbot is not installed.
4217 // Show the Orbot not installed dialog if it is not already displayed.
4218 if (getSupportFragmentManager().findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
4219 // Get a handle for the Orbot not installed alert dialog.
4220 DialogFragment orbotNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode);
4222 // Try to show the dialog. Sometimes the window is not yet active if returning from Settings.
4224 // Display the Orbot not installed alert dialog.
4225 orbotNotInstalledDialogFragment.show(getSupportFragmentManager(), getString(R.string.proxy_not_installed_dialog));
4226 } catch (Exception orbotNotInstalledException) {
4227 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
4228 pendingDialogsArrayList.add(new PendingDialog(orbotNotInstalledDialogFragment, getString(R.string.proxy_not_installed_dialog)));
4234 case ProxyHelper.I2P:
4235 // Set the app bar background to indicate proxying through Orbot is enabled.
4236 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4237 appBarLayout.setBackgroundResource(R.color.blue_50);
4239 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4241 // Get the package manager.
4242 PackageManager packageManager = getPackageManager();
4244 // Check to see if I2P is installed.
4246 // 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.
4247 packageManager.getPackageInfo("net.i2p.android.router", 0);
4248 } catch (PackageManager.NameNotFoundException fdroidException) { // The F-Droid flavor is not installed.
4250 // 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.
4251 packageManager.getPackageInfo("net.i2p.android", 0);
4252 } catch (PackageManager.NameNotFoundException googlePlayException) { // The Google Play flavor is not installed.
4253 // Sow the I2P not installed dialog if it is not already displayed.
4254 if (getSupportFragmentManager().findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
4255 // Get a handle for the waiting for proxy alert dialog.
4256 DialogFragment i2pNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode);
4258 // Try to show the dialog. Sometimes the window is not yet active if returning from Settings.
4260 // Display the I2P not installed alert dialog.
4261 i2pNotInstalledDialogFragment.show(getSupportFragmentManager(), getString(R.string.proxy_not_installed_dialog));
4262 } catch (Exception i2pNotInstalledException) {
4263 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
4264 pendingDialogsArrayList.add(new PendingDialog(i2pNotInstalledDialogFragment, getString(R.string.proxy_not_installed_dialog)));
4271 case ProxyHelper.CUSTOM:
4272 // Set the app bar background to indicate proxying through Orbot is enabled.
4273 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4274 appBarLayout.setBackgroundResource(R.color.blue_50);
4276 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4281 // Reload the WebViews if requested and not waiting for the proxy.
4282 if (reloadWebViews && !waitingForProxy) {
4283 // Reload the WebViews.
4284 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4285 // Get the WebView tab fragment.
4286 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4288 // Get the fragment view.
4289 View fragmentView = webViewTabFragment.getView();
4291 // Only reload the WebViews if they exist.
4292 if (fragmentView != null) {
4293 // Get the nested scroll WebView from the tab fragment.
4294 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4296 // Reload the WebView.
4297 nestedScrollWebView.reload();
4303 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
4304 // Only update the privacy icons if the options menu and the current WebView have already been populated.
4305 if ((optionsMenu != null) && (currentWebView != null)) {
4306 // Update the privacy icon.
4307 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is enabled.
4308 optionsPrivacyMenuItem.setIcon(R.drawable.javascript_enabled);
4309 } else if (currentWebView.getAcceptCookies()) { // JavaScript is disabled but cookies are enabled.
4310 optionsPrivacyMenuItem.setIcon(R.drawable.warning);
4311 } else { // All the dangerous features are disabled.
4312 optionsPrivacyMenuItem.setIcon(R.drawable.privacy_mode);
4315 // Update the cookies icon.
4316 if (currentWebView.getAcceptCookies()) {
4317 optionsCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
4319 optionsCookiesMenuItem.setIcon(R.drawable.cookies_disabled);
4322 // Update the refresh icon.
4323 if (optionsRefreshMenuItem.getTitle() == getString(R.string.refresh)) { // The refresh icon is displayed.
4324 // Set the icon. Once the minimum API is >= 26, the blue and black icons can be combined with a tint list.
4325 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled);
4326 } else { // The stop icon is displayed.
4327 // Set the icon. Once the minimum API is >= 26, the blue and black icons can be combined with a tint list.
4328 optionsRefreshMenuItem.setIcon(R.drawable.close_blue);
4331 // `invalidateOptionsMenu()` calls `onPrepareOptionsMenu()` and redraws the icons in the app bar.
4332 if (runInvalidateOptionsMenu) {
4333 invalidateOptionsMenu();
4338 private void highlightUrlText() {
4339 // Only highlight the URL text if the box is not currently selected.
4340 if (!urlEditText.hasFocus()) {
4341 // Get the URL string.
4342 String urlString = urlEditText.getText().toString();
4344 // Highlight the URL according to the protocol.
4345 if (urlString.startsWith("file://") || urlString.startsWith("content://")) { // This is a file or content URL.
4346 // De-emphasize everything before the file name.
4347 urlEditText.getText().setSpan(initialGrayColorSpan, 0, urlString.lastIndexOf("/") + 1,Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4348 } else { // This is a web URL.
4349 // Get the index of the `/` immediately after the domain name.
4350 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
4352 // Create a base URL string.
4355 // Get the base URL.
4356 if (endOfDomainName > 0) { // There is at least one character after the base URL.
4357 // Get the base URL.
4358 baseUrl = urlString.substring(0, endOfDomainName);
4359 } else { // There are no characters after the base URL.
4360 // Set the base URL to be the entire URL string.
4361 baseUrl = urlString;
4364 // Get the index of the last `.` in the domain.
4365 int lastDotIndex = baseUrl.lastIndexOf(".");
4367 // Get the index of the penultimate `.` in the domain.
4368 int penultimateDotIndex = baseUrl.lastIndexOf(".", lastDotIndex - 1);
4370 // Markup the beginning of the URL.
4371 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
4372 urlEditText.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4374 // De-emphasize subdomains.
4375 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
4376 urlEditText.getText().setSpan(initialGrayColorSpan, 7, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4378 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
4379 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
4380 // De-emphasize the protocol and the additional subdomains.
4381 urlEditText.getText().setSpan(initialGrayColorSpan, 0, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4382 } else { // There is only one subdomain in the domain name.
4383 // De-emphasize only the protocol.
4384 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4388 // De-emphasize the text after the domain name.
4389 if (endOfDomainName > 0) {
4390 urlEditText.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4396 private void loadBookmarksFolder() {
4397 // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
4398 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
4400 // Populate the bookmarks cursor adapter.
4401 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
4403 public View newView(Context context, Cursor cursor, ViewGroup parent) {
4404 // Inflate the individual item layout.
4405 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
4409 public void bindView(View view, Context context, Cursor cursor) {
4410 // Get handles for the views.
4411 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
4412 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
4414 // Get the favorite icon byte array from the cursor.
4415 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.FAVORITE_ICON));
4417 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
4418 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
4420 // Display the bitmap in `bookmarkFavoriteIcon`.
4421 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
4423 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
4424 String bookmarkNameString = cursor.getString(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME));
4425 bookmarkNameTextView.setText(bookmarkNameString);
4427 // Make the font bold for folders.
4428 if (cursor.getInt(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
4429 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
4430 } else { // Reset the font to default for normal bookmarks.
4431 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
4436 // Get a handle for the bookmarks list view.
4437 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
4439 // Populate the list view with the adapter.
4440 bookmarksListView.setAdapter(bookmarksCursorAdapter);
4442 // Get a handle for the bookmarks title text view.
4443 TextView bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
4445 // Set the bookmarks drawer title.
4446 if (currentBookmarksFolder.isEmpty()) {
4447 bookmarksTitleTextView.setText(R.string.bookmarks);
4449 bookmarksTitleTextView.setText(currentBookmarksFolder);
4453 private void openWithApp(String url) {
4454 // Create an open with app intent with `ACTION_VIEW`.
4455 Intent openWithAppIntent = new Intent(Intent.ACTION_VIEW);
4457 // Set the URI but not the MIME type. This should open all available apps.
4458 openWithAppIntent.setData(Uri.parse(url));
4460 // Flag the intent to open in a new task.
4461 openWithAppIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4465 // Show the chooser.
4466 startActivity(openWithAppIntent);
4467 } catch (ActivityNotFoundException exception) { // There are no apps available to open the URL.
4468 // Show a snackbar with the error.
4469 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
4473 private void openWithBrowser(String url) {
4474 // Create an open with browser intent with `ACTION_VIEW`.
4475 Intent openWithBrowserIntent = new Intent(Intent.ACTION_VIEW);
4477 // Set the URI and the MIME type. `"text/html"` should load browser options.
4478 openWithBrowserIntent.setDataAndType(Uri.parse(url), "text/html");
4480 // Flag the intent to open in a new task.
4481 openWithBrowserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4485 // Show the chooser.
4486 startActivity(openWithBrowserIntent);
4487 } catch (ActivityNotFoundException exception) { // There are no browsers available to open the URL.
4488 // Show a snackbar with the error.
4489 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
4493 private String sanitizeUrl(String url) {
4494 // Sanitize tracking queries.
4495 if (sanitizeTrackingQueries)
4496 url = sanitizeUrlHelper.sanitizeTrackingQueries(url);
4498 // Sanitize AMP redirects.
4499 if (sanitizeAmpRedirects)
4500 url = sanitizeUrlHelper.sanitizeAmpRedirects(url);
4502 // Return the sanitized URL.
4506 public void finishedPopulatingBlocklists(ArrayList<ArrayList<List<String[]>>> combinedBlocklists) {
4507 // Store the blocklists.
4508 easyList = combinedBlocklists.get(0);
4509 easyPrivacy = combinedBlocklists.get(1);
4510 fanboysAnnoyanceList = combinedBlocklists.get(2);
4511 fanboysSocialList = combinedBlocklists.get(3);
4512 ultraList = combinedBlocklists.get(4);
4513 ultraPrivacy = combinedBlocklists.get(5);
4515 // Check to see if the activity has been restarted with a saved state.
4516 if ((savedStateArrayList == null) || (savedStateArrayList.size() == 0)) { // The activity has not been restarted or it was restarted on start to force the night theme.
4517 // Add the first tab.
4518 addNewTab("", true);
4519 } else { // The activity has been restarted.
4520 // Restore each tab. Once the minimum API >= 24, a `forEach()` command can be used.
4521 for (int i = 0; i < savedStateArrayList.size(); i++) {
4523 tabLayout.addTab(tabLayout.newTab());
4526 TabLayout.Tab newTab = tabLayout.getTabAt(i);
4528 // Remove the lint warning below that the current tab might be null.
4529 assert newTab != null;
4531 // Set a custom view on the new tab.
4532 newTab.setCustomView(R.layout.tab_custom_view);
4534 // Add the new page.
4535 webViewPagerAdapter.restorePage(savedStateArrayList.get(i), savedNestedScrollWebViewStateArrayList.get(i));
4538 // Reset the saved state variables.
4539 savedStateArrayList = null;
4540 savedNestedScrollWebViewStateArrayList = null;
4542 // Restore the selected tab position.
4543 if (savedTabPosition == 0) { // The first tab is selected.
4544 // Set the first page as the current WebView.
4545 setCurrentWebView(0);
4546 } else { // the first tab is not selected.
4547 // Move to the selected tab.
4548 webViewPager.setCurrentItem(savedTabPosition);
4551 // Get the intent that started the app.
4552 Intent intent = getIntent();
4554 // Reset the intent. This prevents a duplicate tab from being created on restart.
4555 setIntent(new Intent());
4557 // Get the information from the intent.
4558 String intentAction = intent.getAction();
4559 Uri intentUriData = intent.getData();
4560 String intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT);
4562 // Determine if this is a web search.
4563 boolean isWebSearch = ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH));
4565 // 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.
4566 if (intentUriData != null || intentStringExtra != null || isWebSearch) {
4567 // Get the shared preferences.
4568 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4570 // Create a URL string.
4573 // If the intent action is a web search, perform the search.
4574 if (isWebSearch) { // The intent is a web search.
4575 // Create an encoded URL string.
4576 String encodedUrlString;
4578 // Sanitize the search input and convert it to a search.
4580 encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
4581 } catch (UnsupportedEncodingException exception) {
4582 encodedUrlString = "";
4585 // Add the base search URL.
4586 url = searchURL + encodedUrlString;
4587 } else if (intentUriData != null) { // The intent contains a URL formatted as a URI.
4588 // Set the intent data as the URL.
4589 url = intentUriData.toString();
4590 } else { // The intent contains a string, which might be a URL.
4591 // Set the intent string as the URL.
4592 url = intentStringExtra;
4595 // Add a new tab if specified in the preferences.
4596 if (sharedPreferences.getBoolean(getString(R.string.open_intents_in_new_tab_key), true)) { // Load the URL in a new tab.
4597 // Set the loading new intent flag.
4598 loadingNewIntent = true;
4601 addNewTab(url, true);
4602 } else { // Load the URL in the current tab.
4604 loadUrl(currentWebView, url);
4610 public void addTab(View view) {
4611 // Add a new tab with a blank URL.
4612 addNewTab("", true);
4615 private void addNewTab(String url, boolean moveToTab) {
4616 // Clear the focus from the URL edit text, so that it will be populated with the information from the new tab.
4617 urlEditText.clearFocus();
4619 // Get the new page number. The page numbers are 0 indexed, so the new page number will match the current count.
4620 int newTabNumber = tabLayout.getTabCount();
4623 tabLayout.addTab(tabLayout.newTab());
4626 TabLayout.Tab newTab = tabLayout.getTabAt(newTabNumber);
4628 // Remove the lint warning below that the current tab might be null.
4629 assert newTab != null;
4631 // Set a custom view on the new tab.
4632 newTab.setCustomView(R.layout.tab_custom_view);
4634 // Add the new WebView page.
4635 webViewPagerAdapter.addPage(newTabNumber, webViewPager, url, moveToTab);
4637 // Show the app bar if it is at the bottom of the screen and the new tab is taking focus.
4638 if (bottomAppBar && moveToTab && (appBarLayout.getTranslationY() != 0)) {
4639 // Animate the bottom app bar onto the screen.
4640 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0);
4643 objectAnimator.start();
4647 public void closeTab(View view) {
4648 // Run the command according to the number of tabs.
4649 if (tabLayout.getTabCount() > 1) { // There is more than one tab open.
4650 // Close the current tab.
4652 } else { // There is only one tab open.
4657 private void closeCurrentTab() {
4658 // Get the current tab number.
4659 int currentTabNumber = tabLayout.getSelectedTabPosition();
4661 // Delete the current tab.
4662 tabLayout.removeTabAt(currentTabNumber);
4664 // 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,
4665 // meaning that the current WebView must be reset. Otherwise it will happen automatically as the selected tab number changes.
4666 if (webViewPagerAdapter.deletePage(currentTabNumber, webViewPager)) {
4667 setCurrentWebView(currentTabNumber);
4671 private void exitFullScreenVideo() {
4672 // Re-enable the screen timeout.
4673 fullScreenVideoFrameLayout.setKeepScreenOn(false);
4675 // Unset the full screen video flag.
4676 displayingFullScreenVideo = false;
4678 // Remove all the views from the full screen video frame layout.
4679 fullScreenVideoFrameLayout.removeAllViews();
4681 // Hide the full screen video frame layout.
4682 fullScreenVideoFrameLayout.setVisibility(View.GONE);
4684 // Enable the sliding drawers.
4685 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
4687 // Show the coordinator layout.
4688 coordinatorLayout.setVisibility(View.VISIBLE);
4690 // Apply the appropriate full screen mode flags.
4691 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
4692 // Hide the app bar if specified.
4694 // Hide the tab linear layout.
4695 tabsLinearLayout.setVisibility(View.GONE);
4697 // Hide the action bar.
4701 /* Hide the system bars.
4702 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4703 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4704 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4705 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4707 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
4708 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
4709 } else { // Switch to normal viewing mode.
4710 // Remove the `SYSTEM_UI` flags from the root frame layout.
4711 rootFrameLayout.setSystemUiVisibility(0);
4715 private void clearAndExit() {
4716 // Get a handle for the shared preferences.
4717 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4719 // Close the bookmarks cursor and database.
4720 bookmarksCursor.close();
4721 bookmarksDatabaseHelper.close();
4723 // Get the status of the clear everything preference.
4724 boolean clearEverything = sharedPreferences.getBoolean(getString(R.string.clear_everything_key), true);
4726 // Get a handle for the runtime.
4727 Runtime runtime = Runtime.getRuntime();
4729 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
4730 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
4731 String privateDataDirectoryString = getApplicationInfo().dataDir;
4734 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_cookies_key), true)) {
4735 // Request the cookies be deleted.
4736 CookieManager.getInstance().removeAllCookies(null);
4738 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4740 // Two commands must be used because `Runtime.exec()` does not like `*`.
4741 Process deleteCookiesProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
4742 Process deleteCookiesJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
4744 // Wait until the processes have finished.
4745 deleteCookiesProcess.waitFor();
4746 deleteCookiesJournalProcess.waitFor();
4747 } catch (Exception exception) {
4748 // Do nothing if an error is thrown.
4752 // Clear DOM storage.
4753 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_dom_storage_key), true)) {
4754 // Ask `WebStorage` to clear the DOM storage.
4755 WebStorage webStorage = WebStorage.getInstance();
4756 webStorage.deleteAllData();
4758 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4760 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4761 Process deleteLocalStorageProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
4763 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
4764 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
4765 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
4766 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
4767 Process deleteDatabaseProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
4769 // Wait until the processes have finished.
4770 deleteLocalStorageProcess.waitFor();
4771 deleteIndexProcess.waitFor();
4772 deleteQuotaManagerProcess.waitFor();
4773 deleteQuotaManagerJournalProcess.waitFor();
4774 deleteDatabaseProcess.waitFor();
4775 } catch (Exception exception) {
4776 // Do nothing if an error is thrown.
4780 // Clear form data if the API < 26.
4781 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_form_data_key), true))) {
4782 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
4783 webViewDatabase.clearFormData();
4785 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4787 // A string array must be used because the database contains a space and `Runtime.exec` will not otherwise escape the string correctly.
4788 Process deleteWebDataProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
4789 Process deleteWebDataJournalProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
4791 // Wait until the processes have finished.
4792 deleteWebDataProcess.waitFor();
4793 deleteWebDataJournalProcess.waitFor();
4794 } catch (Exception exception) {
4795 // Do nothing if an error is thrown.
4799 // Clear the logcat.
4800 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_logcat_key), true)) {
4802 // Clear the logcat. `-c` clears the logcat. `-b all` clears all the buffers (instead of just crash, main, and system).
4803 Process process = Runtime.getRuntime().exec("logcat -b all -c");
4805 // Wait for the process to finish.
4807 } catch (IOException|InterruptedException exception) {
4813 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_cache_key), true)) {
4814 // Clear the cache from each WebView.
4815 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4816 // Get the WebView tab fragment.
4817 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4819 // Get the WebView fragment view.
4820 View webViewFragmentView = webViewTabFragment.getView();
4822 // Only clear the cache if the WebView exists.
4823 if (webViewFragmentView != null) {
4824 // Get the nested scroll WebView from the tab fragment.
4825 NestedScrollWebView nestedScrollWebView = webViewFragmentView.findViewById(R.id.nestedscroll_webview);
4827 // Clear the cache for this WebView.
4828 nestedScrollWebView.clearCache(true);
4832 // Manually delete the cache directories.
4834 // Delete the main cache directory.
4835 Process deleteCacheProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/cache");
4837 // Delete the secondary `Service Worker` cache directory.
4838 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4839 Process deleteServiceWorkerProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Default/Service Worker/"});
4841 // Wait until the processes have finished.
4842 deleteCacheProcess.waitFor();
4843 deleteServiceWorkerProcess.waitFor();
4844 } catch (Exception exception) {
4845 // Do nothing if an error is thrown.
4849 // Wipe out each WebView.
4850 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4851 // Get the WebView tab fragment.
4852 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4854 // Get the WebView frame layout.
4855 FrameLayout webViewFrameLayout = (FrameLayout) webViewTabFragment.getView();
4857 // Only wipe out the WebView if it exists.
4858 if (webViewFrameLayout != null) {
4859 // Get the nested scroll WebView from the tab fragment.
4860 NestedScrollWebView nestedScrollWebView = webViewFrameLayout.findViewById(R.id.nestedscroll_webview);
4862 // Clear SSL certificate preferences for this WebView.
4863 nestedScrollWebView.clearSslPreferences();
4865 // Clear the back/forward history for this WebView.
4866 nestedScrollWebView.clearHistory();
4868 // Remove all the views from the frame layout.
4869 webViewFrameLayout.removeAllViews();
4871 // Destroy the internal state of the WebView.
4872 nestedScrollWebView.destroy();
4876 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
4877 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
4878 if (clearEverything) {
4880 // Delete the folder.
4881 Process deleteAppWebviewProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
4883 // Wait until the process has finished.
4884 deleteAppWebviewProcess.waitFor();
4885 } catch (Exception exception) {
4886 // Do nothing if an error is thrown.
4890 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
4891 finishAndRemoveTask();
4893 // Remove the terminated program from RAM. The status code is `0`.
4897 public void bookmarksBack(View view) {
4898 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
4899 // close the bookmarks drawer.
4900 drawerLayout.closeDrawer(GravityCompat.END);
4901 } else { // A subfolder is displayed.
4902 // Place the former parent folder in `currentFolder`.
4903 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolderName(currentBookmarksFolder);
4905 // Load the new folder.
4906 loadBookmarksFolder();
4910 private void setCurrentWebView(int pageNumber) {
4911 // Stop the swipe to refresh indicator if it is running
4912 swipeRefreshLayout.setRefreshing(false);
4914 // Get the WebView tab fragment.
4915 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(pageNumber);
4917 // Get the fragment view.
4918 View webViewFragmentView = webViewTabFragment.getView();
4920 // Set the current WebView if the fragment view is not null.
4921 if (webViewFragmentView != null) { // The fragment has been populated.
4922 // Store the current WebView.
4923 currentWebView = webViewFragmentView.findViewById(R.id.nestedscroll_webview);
4925 // Update the status of swipe to refresh.
4926 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
4927 // Enable the swipe refresh layout if the WebView is scrolled all the way to the top. It is updated every time the scroll changes.
4928 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
4929 } else { // Swipe to refresh is disabled.
4930 // Disable the swipe refresh layout.
4931 swipeRefreshLayout.setEnabled(false);
4934 // Get a handle for the cookie manager.
4935 CookieManager cookieManager = CookieManager.getInstance();
4937 // Set the cookie status.
4938 cookieManager.setAcceptCookie(currentWebView.getAcceptCookies());
4940 // Update the privacy icons. `true` redraws the icons in the app bar.
4941 updatePrivacyIcons(true);
4943 // Get a handle for the input method manager.
4944 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
4946 // Remove the lint warning below that the input method manager might be null.
4947 assert inputMethodManager != null;
4949 // Get the current URL.
4950 String url = currentWebView.getUrl();
4952 // Update the URL edit text if not loading a new intent. Otherwise, this will be handled by `onPageStarted()` (if called) and `onPageFinished()`.
4953 if (!loadingNewIntent) { // A new intent is not being loaded.
4954 if ((url == null) || url.equals("about:blank")) { // The WebView is blank.
4955 // Display the hint in the URL edit text.
4956 urlEditText.setText("");
4958 // Request focus for the URL text box.
4959 urlEditText.requestFocus();
4961 // Display the keyboard.
4962 inputMethodManager.showSoftInput(urlEditText, 0);
4963 } else { // The WebView has a loaded URL.
4964 // Clear the focus from the URL text box.
4965 urlEditText.clearFocus();
4967 // Hide the soft keyboard.
4968 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
4970 // Display the current URL in the URL text box.
4971 urlEditText.setText(url);
4973 // Highlight the URL text.
4976 } else { // A new intent is being loaded.
4977 // Reset the loading new intent tracker.
4978 loadingNewIntent = false;
4981 // Set the background to indicate the domain settings status.
4982 if (currentWebView.getDomainSettingsApplied()) {
4983 // Set a background on the URL relative layout to indicate that custom domain settings are being used.
4984 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.domain_settings_url_background, null));
4986 // Remove any background on the URL relative layout.
4987 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.color.transparent, null));
4989 } else { // The fragment has not been populated. Try again in 100 milliseconds.
4990 // Create a handler to set the current WebView.
4991 Handler setCurrentWebViewHandler = new Handler();
4993 // Create a runnable to set the current WebView.
4994 Runnable setCurrentWebWebRunnable = () -> {
4995 // Set the current WebView.
4996 setCurrentWebView(pageNumber);
4999 // Try setting the current WebView again after 100 milliseconds.
5000 setCurrentWebViewHandler.postDelayed(setCurrentWebWebRunnable, 100);
5004 @SuppressLint("ClickableViewAccessibility")
5006 public void initializeWebView(@NonNull NestedScrollWebView nestedScrollWebView, int pageNumber, @NonNull ProgressBar progressBar, @NonNull String url, boolean restoringState) {
5007 // Get a handle for the shared preferences.
5008 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
5010 // Get the WebView theme.
5011 String webViewTheme = sharedPreferences.getString(getString(R.string.webview_theme_key), getString(R.string.webview_theme_default_value));
5013 // Get the WebView theme entry values string array.
5014 String[] webViewThemeEntryValuesStringArray = getResources().getStringArray(R.array.webview_theme_entry_values);
5016 // Set the WebView theme if device is running API >= 29 and algorithmic darkening is supported.
5017 if ((Build.VERSION.SDK_INT >= 29) && WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {
5018 // Set the WebView them. A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
5019 if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) { // The light theme is selected.
5020 // Turn off algorithmic darkening.
5021 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), false);
5023 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
5024 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
5025 nestedScrollWebView.setVisibility(View.VISIBLE);
5026 } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) { // The dark theme is selected.
5027 // Turn on algorithmic darkening.
5028 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), true);
5030 // The system default theme is selected.
5031 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
5033 // Set the algorithmic darkening according to the current system theme status.
5034 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) { // The system is in day mode.
5035 // Turn off algorithmic darkening.
5036 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), false);
5038 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
5039 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
5040 nestedScrollWebView.setVisibility(View.VISIBLE);
5041 } else { // The system is in night mode.
5042 // Turn on algorithmic darkening.
5043 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), true);
5048 // Get a handle for the activity
5049 Activity activity = this;
5051 // Get a handle for the input method manager.
5052 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
5054 // Instantiate the blocklist helper.
5055 BlocklistHelper blocklistHelper = new BlocklistHelper();
5057 // Remove the lint warning below that the input method manager might be null.
5058 assert inputMethodManager != null;
5060 // Set the app bar scrolling.
5061 nestedScrollWebView.setNestedScrollingEnabled(scrollAppBar);
5063 // Allow pinch to zoom.
5064 nestedScrollWebView.getSettings().setBuiltInZoomControls(true);
5066 // Hide zoom controls.
5067 nestedScrollWebView.getSettings().setDisplayZoomControls(false);
5069 // Don't allow mixed content (HTTP and HTTPS) on the same website.
5070 nestedScrollWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW);
5072 // Set the WebView to load in overview mode (zoomed out to the maximum width).
5073 nestedScrollWebView.getSettings().setLoadWithOverviewMode(true);
5075 // Explicitly disable geolocation.
5076 nestedScrollWebView.getSettings().setGeolocationEnabled(false);
5078 // Allow loading of file:// URLs. This is necessary for opening MHT web archives, which are copies into a temporary cache location.
5079 nestedScrollWebView.getSettings().setAllowFileAccess(true);
5081 // Create a double-tap gesture detector to toggle full-screen mode.
5082 GestureDetector doubleTapGestureDetector = new GestureDetector(getApplicationContext(), new GestureDetector.SimpleOnGestureListener() {
5083 // Override `onDoubleTap()`. All other events are handled using the default settings.
5085 public boolean onDoubleTap(MotionEvent event) {
5086 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
5087 // Toggle the full screen browsing mode tracker.
5088 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
5090 // Toggle the full screen browsing mode.
5091 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
5092 // Hide the app bar if specified.
5093 if (hideAppBar) { // The app bar is hidden.
5094 // Close the find on page bar if it is visible.
5095 closeFindOnPage(null);
5097 // Hide the tab linear layout.
5098 tabsLinearLayout.setVisibility(View.GONE);
5100 // Hide the action bar.
5103 // Set layout and scrolling parameters according to the position of the app bar.
5104 if (bottomAppBar) { // The app bar is at the bottom.
5105 // Reset the WebView padding to fill the available space.
5106 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5107 } else { // The app bar is at the top.
5108 // Check to see if the app bar is normally scrolled.
5109 if (scrollAppBar) { // The app bar is scrolled when it is displayed.
5110 // Get the swipe refresh layout parameters.
5111 CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
5113 // Remove the off-screen scrolling layout.
5114 swipeRefreshLayoutParams.setBehavior(null);
5115 } else { // The app bar is not scrolled when it is displayed.
5116 // Remove the padding from the top of the swipe refresh layout.
5117 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5119 // The swipe refresh circle must be moved above the now removed status bar location.
5120 swipeRefreshLayout.setProgressViewOffset(false, -200, defaultProgressViewEndOffset);
5123 } else { // The app bar is not hidden.
5124 // Adjust the UI for the bottom app bar.
5126 // Adjust the UI according to the scrolling of the app bar.
5128 // Reset the WebView padding to fill the available space.
5129 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5131 // Move the WebView above the app bar layout.
5132 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight);
5137 /* Hide the system bars.
5138 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5139 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5140 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5141 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5143 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5144 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5145 } else { // Switch to normal viewing mode.
5146 // Show the app bar if it was hidden.
5148 // Show the tab linear layout.
5149 tabsLinearLayout.setVisibility(View.VISIBLE);
5151 // Show the action bar.
5155 // Set layout and scrolling parameters according to the position of the app bar.
5156 if (bottomAppBar) { // The app bar is at the bottom.
5159 // Reset the WebView padding to fill the available space.
5160 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5162 // Move the WebView above the app bar layout.
5163 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight);
5165 } else { // The app bar is at the top.
5166 // Check to see if the app bar is normally scrolled.
5167 if (scrollAppBar) { // The app bar is scrolled when it is displayed.
5168 // Get the swipe refresh layout parameters.
5169 CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
5171 // Add the off-screen scrolling layout.
5172 swipeRefreshLayoutParams.setBehavior(new AppBarLayout.ScrollingViewBehavior());
5173 } else { // The app bar is not scrolled when it is displayed.
5174 // The swipe refresh layout must be manually moved below the app bar layout.
5175 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0);
5177 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5178 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight);
5182 // Remove the `SYSTEM_UI` flags from the root frame layout.
5183 rootFrameLayout.setSystemUiVisibility(0);
5186 // Consume the double-tap.
5188 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
5194 public boolean onFling(MotionEvent motionEvent1, MotionEvent motionEvent2, float velocityX, float velocityY) {
5195 // Scroll the bottom app bar if enabled.
5196 if (bottomAppBar && scrollAppBar && !objectAnimator.isRunning()) {
5197 // Calculate the Y change.
5198 float motionY = motionEvent2.getY() - motionEvent1.getY();
5200 // Scroll the app bar if the change is greater than 50 pixels.
5202 // Animate the bottom app bar onto the screen.
5203 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0);
5204 } else if (motionY < -50) {
5205 // Animate the bottom app bar off the screen.
5206 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", appBarLayout.getHeight());
5210 objectAnimator.start();
5213 // Do not consume the event.
5218 // Pass all touch events on the WebView through the double-tap gesture detector.
5219 nestedScrollWebView.setOnTouchListener((View view, MotionEvent event) -> {
5220 // Call `performClick()` on the view, which is required for accessibility.
5221 view.performClick();
5223 // Send the event to the gesture detector.
5224 return doubleTapGestureDetector.onTouchEvent(event);
5227 // Register the WebView for a context menu. This is used to see link targets and download images.
5228 registerForContextMenu(nestedScrollWebView);
5230 // Allow the downloading of files.
5231 nestedScrollWebView.setDownloadListener((String downloadUrl, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
5232 // Check the download preference.
5233 if (downloadWithExternalApp) { // Download with an external app.
5234 downloadUrlWithExternalApp(downloadUrl);
5235 } else { // Handle the download inside of Privacy Browser.
5236 // Define a formatted file size string.
5237 String formattedFileSizeString;
5239 // Process the content length if it contains data.
5240 if (contentLength > 0) { // The content length is greater than 0.
5241 // Format the content length as a string.
5242 formattedFileSizeString = NumberFormat.getInstance().format(contentLength) + " " + getString(R.string.bytes);
5243 } else { // The content length is not greater than 0.
5244 // Set the formatted file size string to be `unknown size`.
5245 formattedFileSizeString = getString(R.string.unknown_size);
5248 // Get the file name from the content disposition.
5249 String fileNameString = PrepareSaveDialog.getFileNameFromHeaders(this, contentDisposition, mimetype, downloadUrl);
5251 // Instantiate the save dialog.
5252 DialogFragment saveDialogFragment = SaveDialog.saveUrl(downloadUrl, formattedFileSizeString, fileNameString, userAgent,
5253 nestedScrollWebView.getAcceptCookies());
5255 // 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.
5257 // Show the save dialog. It must be named `save_dialog` so that the file picker can update the file name.
5258 saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
5259 } catch (Exception exception) { // The dialog could not be shown.
5260 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
5261 pendingDialogsArrayList.add(new PendingDialog(saveDialogFragment, getString(R.string.save_dialog)));
5266 // Update the find on page count.
5267 nestedScrollWebView.setFindListener(new WebView.FindListener() {
5268 // Get a handle for `findOnPageCountTextView`.
5269 final TextView findOnPageCountTextView = findViewById(R.id.find_on_page_count_textview);
5272 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
5273 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
5274 // Set `findOnPageCountTextView` to `0/0`.
5275 findOnPageCountTextView.setText(R.string.zero_of_zero);
5276 } else if (isDoneCounting) { // There are matches.
5277 // `activeMatchOrdinal` is zero-based.
5278 int activeMatch = activeMatchOrdinal + 1;
5280 // Build the match string.
5281 String matchString = activeMatch + "/" + numberOfMatches;
5283 // Set `findOnPageCountTextView`.
5284 findOnPageCountTextView.setText(matchString);
5289 // Process scroll changes.
5290 nestedScrollWebView.setOnScrollChangeListener((view, scrollX, scrollY, oldScrollX, oldScrollY) -> {
5291 // Set the swipe to refresh status.
5292 if (nestedScrollWebView.getSwipeToRefresh()) {
5293 // Only enable swipe to refresh if the WebView is scrolled to the top.
5294 swipeRefreshLayout.setEnabled(nestedScrollWebView.getScrollY() == 0);
5296 // Disable swipe to refresh.
5297 swipeRefreshLayout.setEnabled(false);
5300 // Reinforce the system UI visibility flags if in full screen browsing mode.
5301 // This hides the status and navigation bars, which are displayed if other elements are shown, like dialog boxes, the options menu, or the keyboard.
5302 if (inFullScreenBrowsingMode) {
5303 /* Hide the system bars.
5304 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5305 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5306 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5307 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5309 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5310 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5314 // Set the web chrome client.
5315 nestedScrollWebView.setWebChromeClient(new WebChromeClient() {
5316 // Update the progress bar when a page is loading.
5318 public void onProgressChanged(WebView view, int progress) {
5319 // Update the progress bar.
5320 progressBar.setProgress(progress);
5322 // Set the visibility of the progress bar.
5323 if (progress < 100) {
5324 // Show the progress bar.
5325 progressBar.setVisibility(View.VISIBLE);
5327 // Hide the progress bar.
5328 progressBar.setVisibility(View.GONE);
5330 //Stop the swipe to refresh indicator if it is running
5331 swipeRefreshLayout.setRefreshing(false);
5333 // 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.
5334 nestedScrollWebView.setVisibility(View.VISIBLE);
5338 // Set the favorite icon when it changes.
5340 public void onReceivedIcon(WebView view, Bitmap icon) {
5341 // Only update the favorite icon if the website has finished loading.
5342 if (progressBar.getVisibility() == View.GONE) {
5343 // Store the new favorite icon.
5344 nestedScrollWebView.setFavoriteOrDefaultIcon(icon);
5346 // Get the current page position.
5347 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5349 // Get the current tab.
5350 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
5352 // Check to see if the tab has been populated.
5354 // Get the custom view from the tab.
5355 View tabView = tab.getCustomView();
5357 // Check to see if the custom tab view has been populated.
5358 if (tabView != null) {
5359 // Get the favorite icon image view from the tab.
5360 ImageView tabFavoriteIconImageView = tabView.findViewById(R.id.favorite_icon_imageview);
5362 // Display the favorite icon in the tab.
5363 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
5369 // Save a copy of the title when it changes.
5371 public void onReceivedTitle(WebView view, String title) {
5372 // Get the current page position.
5373 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5375 // Get the current tab.
5376 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
5378 // Only populate the title text view if the tab has been fully created.
5380 // Get the custom view from the tab.
5381 View tabView = tab.getCustomView();
5383 // Only populate the title text view if the tab view has been fully populated.
5384 if (tabView != null) {
5385 // Get the title text view from the tab.
5386 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
5388 // Set the title according to the URL.
5389 if (title.equals("about:blank")) {
5390 // Set the title to indicate a new tab.
5391 tabTitleTextView.setText(R.string.new_tab);
5393 // Set the title as the tab text.
5394 tabTitleTextView.setText(title);
5400 // Enter full screen video.
5402 public void onShowCustomView(View video, CustomViewCallback callback) {
5403 // Set the full screen video flag.
5404 displayingFullScreenVideo = true;
5406 // Hide the keyboard.
5407 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
5409 // Hide the coordinator layout.
5410 coordinatorLayout.setVisibility(View.GONE);
5412 /* Hide the system bars.
5413 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5414 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5415 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5416 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5418 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5419 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5421 // Disable the sliding drawers.
5422 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
5424 // Add the video view to the full screen video frame layout.
5425 fullScreenVideoFrameLayout.addView(video);
5427 // Show the full screen video frame layout.
5428 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
5430 // Disable the screen timeout while the video is playing. YouTube does this automatically, but not all other videos do.
5431 fullScreenVideoFrameLayout.setKeepScreenOn(true);
5434 // Exit full screen video.
5436 public void onHideCustomView() {
5437 // Exit the full screen video.
5438 exitFullScreenVideo();
5443 public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
5444 // Store the file path callback.
5445 fileChooserCallback = filePathCallback;
5447 // Create an intent to open a chooser based on the file chooser parameters.
5448 Intent fileChooserIntent = fileChooserParams.createIntent();
5450 // Get a handle for the package manager.
5451 PackageManager packageManager = getPackageManager();
5453 // Check to see if the file chooser intent resolves to an installed package.
5454 if (fileChooserIntent.resolveActivity(packageManager) != null) { // The file chooser intent is fine.
5455 // Start the file chooser intent.
5456 startActivityForResult(fileChooserIntent, BROWSE_FILE_UPLOAD_REQUEST_CODE);
5457 } else { // The file chooser intent will cause a crash.
5458 // Create a generic intent to open a chooser.
5459 Intent genericFileChooserIntent = new Intent(Intent.ACTION_GET_CONTENT);
5461 // Request an openable file.
5462 genericFileChooserIntent.addCategory(Intent.CATEGORY_OPENABLE);
5464 // Set the file type to everything.
5465 genericFileChooserIntent.setType("*/*");
5467 // Start the generic file chooser intent.
5468 startActivityForResult(genericFileChooserIntent, BROWSE_FILE_UPLOAD_REQUEST_CODE);
5474 nestedScrollWebView.setWebViewClient(new WebViewClient() {
5475 // `shouldOverrideUrlLoading` makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
5476 // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
5478 public boolean shouldOverrideUrlLoading(WebView view, String url) {
5479 // Sanitize the url.
5480 url = sanitizeUrl(url);
5482 // Handle the URL according to the type.
5483 if (url.startsWith("http")) { // Load the URL in Privacy Browser.
5484 // Load the URL. By using `loadUrl()`, instead of `loadUrlFromBase()`, the Referer header will never be sent.
5485 loadUrl(nestedScrollWebView, url);
5487 // Returning true indicates that Privacy Browser is manually handling the loading of the URL.
5488 // Custom headers cannot be added if false is returned and the WebView handles the loading of the URL.
5490 } else if (url.startsWith("mailto:")) { // Load the email address in an external email program.
5491 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
5492 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
5494 // Parse the url and set it as the data for the intent.
5495 emailIntent.setData(Uri.parse(url));
5497 // Open the email program in a new task instead of as part of Privacy Browser.
5498 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5502 startActivity(emailIntent);
5503 } catch (ActivityNotFoundException exception) {
5504 // Display a snackbar.
5505 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
5509 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5511 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
5512 // Open the dialer and load the phone number, but wait for the user to place the call.
5513 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
5515 // Add the phone number to the intent.
5516 dialIntent.setData(Uri.parse(url));
5518 // Open the dialer in a new task instead of as part of Privacy Browser.
5519 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5523 startActivity(dialIntent);
5524 } catch (ActivityNotFoundException exception) {
5525 // Display a snackbar.
5526 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
5529 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5531 } else { // Load a system chooser to select an app that can handle the URL.
5532 // Open an app that can handle the URL.
5533 Intent genericIntent = new Intent(Intent.ACTION_VIEW);
5535 // Add the URL to the intent.
5536 genericIntent.setData(Uri.parse(url));
5538 // List all apps that can handle the URL instead of just opening the first one.
5539 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
5541 // Open the app in a new task instead of as part of Privacy Browser.
5542 genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5544 // Start the app or display a snackbar if no app is available to handle the URL.
5546 startActivity(genericIntent);
5547 } catch (ActivityNotFoundException exception) {
5548 Snackbar.make(nestedScrollWebView, getString(R.string.unrecognized_url) + " " + url, Snackbar.LENGTH_SHORT).show();
5551 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5556 // Check requests against the block lists. The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
5558 public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest webResourceRequest) {
5560 String url = webResourceRequest.getUrl().toString();
5562 // Check to see if the resource request is for the main URL.
5563 if (url.equals(nestedScrollWebView.getCurrentUrl())) {
5564 // `return null` loads the resource request, which should never be blocked if it is the main URL.
5568 // 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.
5569 while (ultraPrivacy == null) {
5570 // The wait must be synchronized, which only lets one thread run on it at a time, or `java.lang.IllegalMonitorStateException` is thrown.
5571 synchronized (this) {
5573 // Check to see if the blocklists have been populated after 100 ms.
5575 } catch (InterruptedException exception) {
5581 // Create an empty web resource response to be used if the resource request is blocked.
5582 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
5584 // Reset the whitelist results tracker.
5585 String[] whitelistResultStringArray = null;
5587 // Initialize the third party request tracker.
5588 boolean isThirdPartyRequest = false;
5590 // Get the current URL. `.getUrl()` throws an error because operations on the WebView cannot be made from this thread.
5591 String currentBaseDomain = nestedScrollWebView.getCurrentDomainName();
5593 // Store a copy of the current domain for use in later requests.
5594 String currentDomain = currentBaseDomain;
5596 // Get the request host name.
5597 String requestBaseDomain = webResourceRequest.getUrl().getHost();
5599 // Only check for third-party requests if the current base domain is not empty and the request domain is not null.
5600 if (!currentBaseDomain.isEmpty() && (requestBaseDomain != null)) {
5601 // Determine the current base domain.
5602 while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
5603 // Remove the first subdomain.
5604 currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
5607 // Determine the request base domain.
5608 while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
5609 // Remove the first subdomain.
5610 requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
5613 // Update the third party request tracker.
5614 isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
5617 // Get the current WebView page position.
5618 int webViewPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5620 // Determine if the WebView is currently displayed.
5621 boolean webViewDisplayed = (webViewPagePosition == tabLayout.getSelectedTabPosition());
5623 // Block third-party requests if enabled.
5624 if (isThirdPartyRequest && nestedScrollWebView.getBlockAllThirdPartyRequests()) {
5625 // Add the result to the resource requests.
5626 nestedScrollWebView.addResourceRequest(new String[]{BlocklistHelper.REQUEST_THIRD_PARTY, url});
5628 // Increment the blocked requests counters.
5629 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5630 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS);
5632 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5633 if (webViewDisplayed) {
5634 // Updating the UI must be run from the UI thread.
5635 activity.runOnUiThread(() -> {
5636 // Update the menu item titles.
5637 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5639 // Update the options menu if it has been populated.
5640 if (optionsMenu != null) {
5641 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5642 optionsBlockAllThirdPartyRequestsMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " +
5643 getString(R.string.block_all_third_party_requests));
5648 // Return an empty web resource response.
5649 return emptyWebResourceResponse;
5652 // Check UltraList if it is enabled.
5653 if (nestedScrollWebView.getUltraListEnabled()) {
5654 // Check the URL against UltraList.
5655 String[] ultraListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraList);
5657 // Process the UltraList results.
5658 if (ultraListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched UltraList's blacklist.
5659 // Add the result to the resource requests.
5660 nestedScrollWebView.addResourceRequest(new String[] {ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]});
5662 // Increment the blocked requests counters.
5663 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5664 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRALIST);
5666 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5667 if (webViewDisplayed) {
5668 // Updating the UI must be run from the UI thread.
5669 activity.runOnUiThread(() -> {
5670 // Update the menu item titles.
5671 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5673 // Update the options menu if it has been populated.
5674 if (optionsMenu != null) {
5675 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5676 optionsUltraListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRALIST) + " - " + getString(R.string.ultralist));
5681 // The resource request was blocked. Return an empty web resource response.
5682 return emptyWebResourceResponse;
5683 } else if (ultraListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched UltraList's whitelist.
5684 // Add a whitelist entry to the resource requests array.
5685 nestedScrollWebView.addResourceRequest(new String[] {ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]});
5687 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
5692 // Check UltraPrivacy if it is enabled.
5693 if (nestedScrollWebView.getUltraPrivacyEnabled()) {
5694 // Check the URL against UltraPrivacy.
5695 String[] ultraPrivacyResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraPrivacy);
5697 // Process the UltraPrivacy results.
5698 if (ultraPrivacyResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched UltraPrivacy's blacklist.
5699 // Add the result to the resource requests.
5700 nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5701 ultraPrivacyResults[5]});
5703 // Increment the blocked requests counters.
5704 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5705 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRAPRIVACY);
5707 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5708 if (webViewDisplayed) {
5709 // Updating the UI must be run from the UI thread.
5710 activity.runOnUiThread(() -> {
5711 // Update the menu item titles.
5712 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5714 // Update the options menu if it has been populated.
5715 if (optionsMenu != null) {
5716 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5717 optionsUltraPrivacyMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRAPRIVACY) + " - " + getString(R.string.ultraprivacy));
5722 // The resource request was blocked. Return an empty web resource response.
5723 return emptyWebResourceResponse;
5724 } else if (ultraPrivacyResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched UltraPrivacy's whitelist.
5725 // Add a whitelist entry to the resource requests array.
5726 nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5727 ultraPrivacyResults[5]});
5729 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
5734 // Check EasyList if it is enabled.
5735 if (nestedScrollWebView.getEasyListEnabled()) {
5736 // Check the URL against EasyList.
5737 String[] easyListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyList);
5739 // Process the EasyList results.
5740 if (easyListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched EasyList's blacklist.
5741 // Add the result to the resource requests.
5742 nestedScrollWebView.addResourceRequest(new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]});
5744 // Increment the blocked requests counters.
5745 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5746 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASYLIST);
5748 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5749 if (webViewDisplayed) {
5750 // Updating the UI must be run from the UI thread.
5751 activity.runOnUiThread(() -> {
5752 // Update the menu item titles.
5753 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5755 // Update the options menu if it has been populated.
5756 if (optionsMenu != null) {
5757 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5758 optionsEasyListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASYLIST) + " - " + getString(R.string.easylist));
5763 // The resource request was blocked. Return an empty web resource response.
5764 return emptyWebResourceResponse;
5765 } else if (easyListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched EasyList's whitelist.
5766 // Update the whitelist result string array tracker.
5767 whitelistResultStringArray = new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]};
5771 // Check EasyPrivacy if it is enabled.
5772 if (nestedScrollWebView.getEasyPrivacyEnabled()) {
5773 // Check the URL against EasyPrivacy.
5774 String[] easyPrivacyResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyPrivacy);
5776 // Process the EasyPrivacy results.
5777 if (easyPrivacyResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched EasyPrivacy's blacklist.
5778 // Add the result to the resource requests.
5779 nestedScrollWebView.addResourceRequest(new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4],
5780 easyPrivacyResults[5]});
5782 // Increment the blocked requests counters.
5783 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5784 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASYPRIVACY);
5786 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5787 if (webViewDisplayed) {
5788 // Updating the UI must be run from the UI thread.
5789 activity.runOnUiThread(() -> {
5790 // Update the menu item titles.
5791 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5793 // Update the options menu if it has been populated.
5794 if (optionsMenu != null) {
5795 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5796 optionsEasyPrivacyMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASYPRIVACY) + " - " + getString(R.string.easyprivacy));
5801 // The resource request was blocked. Return an empty web resource response.
5802 return emptyWebResourceResponse;
5803 } else if (easyPrivacyResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched EasyPrivacy's whitelist.
5804 // Update the whitelist result string array tracker.
5805 whitelistResultStringArray = new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5]};
5809 // Check Fanboy’s Annoyance List if it is enabled.
5810 if (nestedScrollWebView.getFanboysAnnoyanceListEnabled()) {
5811 // Check the URL against Fanboy's Annoyance List.
5812 String[] fanboysAnnoyanceListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList);
5814 // Process the Fanboy's Annoyance List results.
5815 if (fanboysAnnoyanceListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched Fanboy's Annoyance List's blacklist.
5816 // Add the result to the resource requests.
5817 nestedScrollWebView.addResourceRequest(new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5818 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]});
5820 // Increment the blocked requests counters.
5821 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5822 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST);
5824 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5825 if (webViewDisplayed) {
5826 // Updating the UI must be run from the UI thread.
5827 activity.runOnUiThread(() -> {
5828 // Update the menu item titles.
5829 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5831 // Update the options menu if it has been populated.
5832 if (optionsMenu != null) {
5833 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5834 optionsFanboysAnnoyanceListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " +
5835 getString(R.string.fanboys_annoyance_list));
5840 // The resource request was blocked. Return an empty web resource response.
5841 return emptyWebResourceResponse;
5842 } else if (fanboysAnnoyanceListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)){ // The resource request matched Fanboy's Annoyance List's whitelist.
5843 // Update the whitelist result string array tracker.
5844 whitelistResultStringArray = new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5845 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]};
5847 } else if (nestedScrollWebView.getFanboysSocialBlockingListEnabled()) { // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
5848 // Check the URL against Fanboy's Annoyance List.
5849 String[] fanboysSocialListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysSocialList);
5851 // Process the Fanboy's Social Blocking List results.
5852 if (fanboysSocialListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched Fanboy's Social Blocking List's blacklist.
5853 // Add the result to the resource requests.
5854 nestedScrollWebView.addResourceRequest(new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5855 fanboysSocialListResults[4], fanboysSocialListResults[5]});
5857 // Increment the blocked requests counters.
5858 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5859 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST);
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 optionsFanboysSocialBlockingListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " +
5872 getString(R.string.fanboys_social_blocking_list));
5877 // The resource request was blocked. Return an empty web resource response.
5878 return emptyWebResourceResponse;
5879 } else if (fanboysSocialListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched Fanboy's Social Blocking List's whitelist.
5880 // Update the whitelist result string array tracker.
5881 whitelistResultStringArray = new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5882 fanboysSocialListResults[4], fanboysSocialListResults[5]};
5886 // Add the request to the log because it hasn't been processed by any of the previous checks.
5887 if (whitelistResultStringArray != null) { // The request was processed by a whitelist.
5888 nestedScrollWebView.addResourceRequest(whitelistResultStringArray);
5889 } else { // The request didn't match any blocklist entry. Log it as a default request.
5890 nestedScrollWebView.addResourceRequest(new String[]{BlocklistHelper.REQUEST_DEFAULT, url});
5893 // The resource request has not been blocked. `return null` loads the requested resource.
5897 // Handle HTTP authentication requests.
5899 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
5900 // Store the handler.
5901 nestedScrollWebView.setHttpAuthHandler(handler);
5903 // Instantiate an HTTP authentication dialog.
5904 DialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm, nestedScrollWebView.getWebViewFragmentId());
5906 // Show the HTTP authentication dialog.
5907 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
5911 public void onPageStarted(WebView view, String url, Bitmap favicon) {
5912 // Get the app bar layout height. This can't be done in `applyAppSettings()` because the app bar is not yet populated there.
5913 // 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.
5914 if (appBarLayout.getHeight() > 0) appBarHeight = appBarLayout.getHeight();
5916 // Set the padding and layout settings according to the position of the app bar.
5917 if (bottomAppBar) { // The app bar is on the bottom.
5919 if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) { // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
5920 // Reset the WebView padding to fill the available space.
5921 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5922 } else { // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
5923 // Move the WebView above the app bar layout.
5924 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight);
5926 } else { // The app bar is on the top.
5927 // 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.
5928 if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) {
5929 // No padding is needed because it will automatically be placed below the app bar layout due to the scrolling layout behavior.
5930 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5932 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5933 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10, defaultProgressViewEndOffset);
5935 // The swipe refresh layout must be manually moved below the app bar layout.
5936 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0);
5938 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5939 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight);
5943 // Reset the list of resource requests.
5944 nestedScrollWebView.clearResourceRequests();
5946 // Reset the requests counters.
5947 nestedScrollWebView.resetRequestsCounters();
5949 // Get the current page position.
5950 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5952 // Update the URL text bar if the page is currently selected and the URL edit text is not currently being edited.
5953 if ((tabLayout.getSelectedTabPosition() == currentPagePosition) && !urlEditText.hasFocus()) {
5954 // Display the formatted URL text.
5955 urlEditText.setText(url);
5957 // Apply text highlighting to the URL text box.
5960 // Hide the keyboard.
5961 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
5964 // Reset the list of host IP addresses.
5965 nestedScrollWebView.setCurrentIpAddresses("");
5967 // Get a URI for the current URL.
5968 Uri currentUri = Uri.parse(url);
5970 // Get the IP addresses for the host.
5971 new GetHostIpAddresses(activity, getSupportFragmentManager(), nestedScrollWebView).execute(currentUri.getHost());
5973 // Replace Refresh with Stop if the options menu has been created. (The first WebView typically begins loading before the menu items are instantiated.)
5974 if (optionsMenu != null) {
5976 optionsRefreshMenuItem.setTitle(R.string.stop);
5978 // Set the icon if it is displayed in the AppBar.
5979 if (displayAdditionalAppBarIcons)
5980 optionsRefreshMenuItem.setIcon(R.drawable.close_blue);
5985 public void onPageFinished(WebView view, String url) {
5986 // Flush any cookies to persistent storage. The cookie manager has become very lazy about flushing cookies in recent versions.
5987 if (nestedScrollWebView.getAcceptCookies()) {
5988 CookieManager.getInstance().flush();
5991 // Update the Refresh menu item if the options menu has been created.
5992 if (optionsMenu != null) {
5993 // Reset the Refresh title.
5994 optionsRefreshMenuItem.setTitle(R.string.refresh);
5996 // Reset the icon if it is displayed in the app bar.
5997 if (displayAdditionalAppBarIcons)
5998 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled);
6001 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
6002 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
6003 String privateDataDirectoryString = getApplicationInfo().dataDir;
6005 // Clear the cache, history, and logcat if Incognito Mode is enabled.
6006 if (incognitoModeEnabled) {
6007 // Clear the cache. `true` includes disk files.
6008 nestedScrollWebView.clearCache(true);
6010 // Clear the back/forward history.
6011 nestedScrollWebView.clearHistory();
6013 // Manually delete cache folders.
6015 // Delete the main cache directory.
6016 Runtime.getRuntime().exec("rm -rf " + privateDataDirectoryString + "/cache");
6017 } catch (IOException exception) {
6018 // Do nothing if an error is thrown.
6021 // Clear the logcat.
6023 // Clear the logcat. `-c` clears the logcat. `-b all` clears all the buffers (instead of just crash, main, and system).
6024 Runtime.getRuntime().exec("logcat -b all -c");
6025 } catch (IOException exception) {
6030 // Clear the `Service Worker` directory.
6032 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
6033 Runtime.getRuntime().exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Default/Service Worker/"});
6034 } catch (IOException exception) {
6038 // Get the current page position.
6039 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
6041 // 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.
6042 String currentUrl = nestedScrollWebView.getUrl();
6044 // Get the current tab.
6045 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
6047 // Update the URL text bar if the page is currently selected and the user is not currently typing in the URL edit text.
6048 // Crash records show that, in some crazy way, it is possible for the current URL to be blank at this point.
6049 // Probably some sort of race condition when Privacy Browser is being resumed.
6050 if ((tabLayout.getSelectedTabPosition() == currentPagePosition) && !urlEditText.hasFocus() && (currentUrl != null)) {
6051 // Check to see if the URL is `about:blank`.
6052 if (currentUrl.equals("about:blank")) { // The WebView is blank.
6053 // Display the hint in the URL edit text.
6054 urlEditText.setText("");
6056 // Request focus for the URL text box.
6057 urlEditText.requestFocus();
6059 // Display the keyboard.
6060 inputMethodManager.showSoftInput(urlEditText, 0);
6062 // Apply the domain settings. This clears any settings from the previous domain.
6063 applyDomainSettings(nestedScrollWebView, "", true, false, false);
6065 // Only populate the title text view if the tab has been fully created.
6067 // Get the custom view from the tab.
6068 View tabView = tab.getCustomView();
6070 // Remove the incorrect warning below that the current tab view might be null.
6071 assert tabView != null;
6073 // Get the title text view from the tab.
6074 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
6076 // Set the title as the tab text.
6077 tabTitleTextView.setText(R.string.new_tab);
6079 } else { // The WebView has loaded a webpage.
6080 // Update the URL edit text if it is not currently being edited.
6081 if (!urlEditText.hasFocus()) {
6082 // 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.
6083 String sanitizedUrl = sanitizeUrl(currentUrl);
6085 // Display the final URL. Getting the URL from the WebView instead of using the one provided by `onPageFinished()` makes websites like YouTube function correctly.
6086 urlEditText.setText(sanitizedUrl);
6088 // Apply text highlighting to the URL.
6092 // Only populate the title text view if the tab has been fully created.
6094 // Get the custom view from the tab.
6095 View tabView = tab.getCustomView();
6097 // Remove the incorrect warning below that the current tab view might be null.
6098 assert tabView != null;
6100 // Get the title text view from the tab.
6101 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
6103 // Set the title as the tab text. Sometimes `onReceivedTitle()` is not called, especially when navigating history.
6104 tabTitleTextView.setText(nestedScrollWebView.getTitle());
6110 // Handle SSL Certificate errors. Suppress the lint warning that ignoring the error might be dangerous.
6111 @SuppressLint("WebViewClientOnReceivedSslError")
6113 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
6114 // Get the current website SSL certificate.
6115 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
6117 // Extract the individual pieces of information from the current website SSL certificate.
6118 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
6119 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
6120 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
6121 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
6122 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
6123 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
6124 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
6125 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
6127 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
6128 if (nestedScrollWebView.hasPinnedSslCertificate()) {
6129 // Get the pinned SSL certificate.
6130 Pair<String[], Date[]> pinnedSslCertificatePair = nestedScrollWebView.getPinnedSslCertificate();
6132 // Extract the arrays from the array list.
6133 String[] pinnedSslCertificateStringArray = pinnedSslCertificatePair.getFirst();
6134 Date[] pinnedSslCertificateDateArray = pinnedSslCertificatePair.getSecond();
6136 // Check if the current SSL certificate matches the pinned certificate.
6137 if (currentWebsiteIssuedToCName.equals(pinnedSslCertificateStringArray[0]) && currentWebsiteIssuedToOName.equals(pinnedSslCertificateStringArray[1]) &&
6138 currentWebsiteIssuedToUName.equals(pinnedSslCertificateStringArray[2]) && currentWebsiteIssuedByCName.equals(pinnedSslCertificateStringArray[3]) &&
6139 currentWebsiteIssuedByOName.equals(pinnedSslCertificateStringArray[4]) && currentWebsiteIssuedByUName.equals(pinnedSslCertificateStringArray[5]) &&
6140 currentWebsiteSslStartDate.equals(pinnedSslCertificateDateArray[0]) && currentWebsiteSslEndDate.equals(pinnedSslCertificateDateArray[1])) {
6142 // An SSL certificate is pinned and matches the current domain certificate. Proceed to the website without displaying an error.
6145 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
6146 // Store the SSL error handler.
6147 nestedScrollWebView.setSslErrorHandler(handler);
6149 // Instantiate an SSL certificate error alert dialog.
6150 DialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error, nestedScrollWebView.getWebViewFragmentId());
6152 // 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.
6154 // Show the SSL certificate error dialog.
6155 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
6156 } catch (Exception exception) {
6157 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
6158 pendingDialogsArrayList.add(new PendingDialog(sslCertificateErrorDialogFragment, getString(R.string.ssl_certificate_error)));
6164 // Check to see if the state is being restored.
6165 if (restoringState) { // The state is being restored.
6166 // Resume the nested scroll WebView JavaScript timers.
6167 nestedScrollWebView.resumeTimers();
6168 } else if (pageNumber == 0) { // The first page is being loaded.
6169 // Set this nested scroll WebView as the current WebView.
6170 currentWebView = nestedScrollWebView;
6172 // Initialize the URL to load string.
6173 String urlToLoadString;
6175 // Get the intent that started the app.
6176 Intent launchingIntent = getIntent();
6178 // Reset the intent. This prevents a duplicate tab from being created on restart.
6179 setIntent(new Intent());
6181 // Get the information from the intent.
6182 String launchingIntentAction = launchingIntent.getAction();
6183 Uri launchingIntentUriData = launchingIntent.getData();
6184 String launchingIntentStringExtra = launchingIntent.getStringExtra(Intent.EXTRA_TEXT);
6186 // Parse the launching intent URL.
6187 if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) { // The intent contains a search string.
6188 // Create an encoded URL string.
6189 String encodedUrlString;
6191 // Sanitize the search input and convert it to a search.
6193 encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
6194 } catch (UnsupportedEncodingException exception) {
6195 encodedUrlString = "";
6198 // Store the web search as the URL to load.
6199 urlToLoadString = searchURL + encodedUrlString;
6200 } else if (launchingIntentUriData != null) { // The launching intent contains a URL formatted as a URI.
6201 // Store the URI as a URL.
6202 urlToLoadString = launchingIntentUriData.toString();
6203 } else if (launchingIntentStringExtra != null) { // The launching intent contains text that might be a URL.
6205 urlToLoadString = launchingIntentStringExtra;
6206 } else if (!url.equals("")) { // The activity has been restarted.
6207 // Load the saved URL.
6208 urlToLoadString = url;
6209 } else { // The is no URL in the intent.
6210 // Store the homepage to be loaded.
6211 urlToLoadString = sharedPreferences.getString("homepage", getString(R.string.homepage_default_value));
6214 // Load the website if not waiting for the proxy.
6215 if (waitingForProxy) { // Store the URL to be loaded in the Nested Scroll WebView.
6216 nestedScrollWebView.setWaitingForProxyUrlString(urlToLoadString);
6217 } else { // Load the URL.
6218 loadUrl(nestedScrollWebView, urlToLoadString);
6221 // 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.
6222 // 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.
6223 setIntent(new Intent());
6224 } else { // This is not the first tab.
6226 loadUrl(nestedScrollWebView, url);
6228 // Set the focus and display the keyboard if the URL is blank.
6229 if (url.equals("")) {
6230 // Request focus for the URL text box.
6231 urlEditText.requestFocus();
6233 // Create a display keyboard handler.
6234 Handler displayKeyboardHandler = new Handler();
6236 // Create a display keyboard runnable.
6237 Runnable displayKeyboardRunnable = () -> {
6238 // Display the keyboard.
6239 inputMethodManager.showSoftInput(urlEditText, 0);
6242 // Display the keyboard after 100 milliseconds, which leaves enough time for the tab to transition.
6243 displayKeyboardHandler.postDelayed(displayKeyboardRunnable, 100);