2 * Copyright © 2015-2022 Soren Stoutner <soren@stoutner.com>.
4 * Download cookie code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
6 * This file is part of Privacy Browser Android <https://www.stoutner.com/privacy-browser-android>.
8 * Privacy Browser Android is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
13 * Privacy Browser Android is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with Privacy Browser Android. If not, see <http://www.gnu.org/licenses/>.
22 package com.stoutner.privacybrowser.activities;
24 import android.animation.ObjectAnimator;
25 import android.annotation.SuppressLint;
26 import android.app.Activity;
27 import android.app.Dialog;
28 import android.app.DownloadManager;
29 import android.app.SearchManager;
30 import android.content.ActivityNotFoundException;
31 import android.content.BroadcastReceiver;
32 import android.content.ClipData;
33 import android.content.ClipboardManager;
34 import android.content.Context;
35 import android.content.Intent;
36 import android.content.IntentFilter;
37 import android.content.SharedPreferences;
38 import android.content.pm.PackageManager;
39 import android.content.res.Configuration;
40 import android.database.Cursor;
41 import android.graphics.Bitmap;
42 import android.graphics.BitmapFactory;
43 import android.graphics.Typeface;
44 import android.graphics.drawable.BitmapDrawable;
45 import android.graphics.drawable.Drawable;
46 import android.net.Uri;
47 import android.net.http.SslCertificate;
48 import android.net.http.SslError;
49 import android.os.AsyncTask;
50 import android.os.Build;
51 import android.os.Bundle;
52 import android.os.Environment;
53 import android.os.Handler;
54 import android.os.Message;
55 import android.preference.PreferenceManager;
56 import android.print.PrintDocumentAdapter;
57 import android.print.PrintManager;
58 import android.provider.DocumentsContract;
59 import android.provider.OpenableColumns;
60 import android.text.Editable;
61 import android.text.Spanned;
62 import android.text.TextWatcher;
63 import android.text.style.ForegroundColorSpan;
64 import android.util.Patterns;
65 import android.util.TypedValue;
66 import android.view.ContextMenu;
67 import android.view.GestureDetector;
68 import android.view.KeyEvent;
69 import android.view.Menu;
70 import android.view.MenuItem;
71 import android.view.MotionEvent;
72 import android.view.View;
73 import android.view.ViewGroup;
74 import android.view.WindowManager;
75 import android.view.inputmethod.InputMethodManager;
76 import android.webkit.CookieManager;
77 import android.webkit.HttpAuthHandler;
78 import android.webkit.SslErrorHandler;
79 import android.webkit.ValueCallback;
80 import android.webkit.WebBackForwardList;
81 import android.webkit.WebChromeClient;
82 import android.webkit.WebResourceRequest;
83 import android.webkit.WebResourceResponse;
84 import android.webkit.WebSettings;
85 import android.webkit.WebStorage;
86 import android.webkit.WebView;
87 import android.webkit.WebViewClient;
88 import android.webkit.WebViewDatabase;
89 import android.widget.ArrayAdapter;
90 import android.widget.CheckBox;
91 import android.widget.CursorAdapter;
92 import android.widget.EditText;
93 import android.widget.FrameLayout;
94 import android.widget.ImageView;
95 import android.widget.LinearLayout;
96 import android.widget.ListView;
97 import android.widget.ProgressBar;
98 import android.widget.RadioButton;
99 import android.widget.RelativeLayout;
100 import android.widget.TextView;
102 import androidx.activity.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.swiperefreshlayout.widget.SwipeRefreshLayout;
118 import androidx.viewpager.widget.ViewPager;
119 import androidx.webkit.WebSettingsCompat;
120 import androidx.webkit.WebViewFeature;
122 import com.google.android.material.appbar.AppBarLayout;
123 import com.google.android.material.floatingactionbutton.FloatingActionButton;
124 import com.google.android.material.navigation.NavigationView;
125 import com.google.android.material.snackbar.Snackbar;
126 import com.google.android.material.tabs.TabLayout;
128 import com.stoutner.privacybrowser.R;
129 import com.stoutner.privacybrowser.adapters.WebViewPagerAdapter;
130 import com.stoutner.privacybrowser.asynctasks.GetHostIpAddresses;
131 import com.stoutner.privacybrowser.asynctasks.PopulateBlocklists;
132 import com.stoutner.privacybrowser.asynctasks.PrepareSaveDialog;
133 import com.stoutner.privacybrowser.asynctasks.SaveUrl;
134 import com.stoutner.privacybrowser.asynctasks.SaveWebpageImage;
135 import com.stoutner.privacybrowser.dataclasses.PendingDialog;
136 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
137 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
138 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
139 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
140 import com.stoutner.privacybrowser.dialogs.FontSizeDialog;
141 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
142 import com.stoutner.privacybrowser.dialogs.OpenDialog;
143 import com.stoutner.privacybrowser.dialogs.ProxyNotInstalledDialog;
144 import com.stoutner.privacybrowser.dialogs.PinnedMismatchDialog;
145 import com.stoutner.privacybrowser.dialogs.SaveDialog;
146 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
147 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
148 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
149 import com.stoutner.privacybrowser.dialogs.WaitingForProxyDialog;
150 import com.stoutner.privacybrowser.fragments.WebViewTabFragment;
151 import com.stoutner.privacybrowser.helpers.BlocklistHelper;
152 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
153 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
154 import com.stoutner.privacybrowser.helpers.ProxyHelper;
155 import com.stoutner.privacybrowser.helpers.SanitizeUrlHelper;
156 import com.stoutner.privacybrowser.views.NestedScrollWebView;
158 import java.io.ByteArrayInputStream;
159 import java.io.ByteArrayOutputStream;
161 import java.io.FileInputStream;
162 import java.io.FileOutputStream;
163 import java.io.IOException;
164 import java.io.InputStream;
165 import java.io.OutputStream;
166 import java.io.UnsupportedEncodingException;
168 import java.net.MalformedURLException;
170 import java.net.URLDecoder;
171 import java.net.URLEncoder;
173 import java.text.NumberFormat;
175 import java.util.ArrayList;
176 import java.util.Date;
177 import java.util.HashMap;
178 import java.util.HashSet;
179 import java.util.List;
180 import java.util.Map;
181 import java.util.Objects;
182 import java.util.Set;
183 import java.util.concurrent.ExecutorService;
184 import java.util.concurrent.Executors;
188 public class MainWebViewActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener,
189 EditBookmarkFolderDialog.EditBookmarkFolderListener, FontSizeDialog.UpdateFontSizeListener, NavigationView.OnNavigationItemSelectedListener, OpenDialog.OpenListener,
190 PinnedMismatchDialog.PinnedMismatchListener, PopulateBlocklists.PopulateBlocklistsListener, SaveDialog.SaveListener, UrlHistoryDialog.NavigateHistoryListener,
191 WebViewTabFragment.NewTabListener {
193 // Define the public static variables.
194 public static ExecutorService executorService = Executors.newFixedThreadPool(4);
195 public static String orbotStatus = "unknown";
196 public static ArrayList<PendingDialog> pendingDialogsArrayList = new ArrayList<>();
197 public static String proxyMode = ProxyHelper.NONE;
199 // Declare the public static variables.
200 public static String currentBookmarksFolder;
201 public static boolean restartFromBookmarksActivity;
202 public static WebViewPagerAdapter webViewPagerAdapter;
204 // Declare the public static views.
205 public static AppBarLayout appBarLayout;
207 // The user agent constants are public static so they can be accessed from `SettingsFragment`, `DomainsActivity`, and `DomainSettingsFragment`.
208 public final static int UNRECOGNIZED_USER_AGENT = -1;
209 public final static int SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1;
210 public final static int SETTINGS_CUSTOM_USER_AGENT = 11;
211 public final static int DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0;
212 public final static int DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2;
213 public final static int DOMAINS_CUSTOM_USER_AGENT = 12;
215 // Define the start activity for result request codes. The public static entry is accessed from `OpenDialog()`.
216 private final int BROWSE_FILE_UPLOAD_REQUEST_CODE = 0;
217 public final static int BROWSE_OPEN_REQUEST_CODE = 1;
219 // Define the saved instance state constants.
220 private final String SAVED_STATE_ARRAY_LIST = "saved_state_array_list";
221 private final String SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST = "saved_nested_scroll_webview_state_array_list";
222 private final String SAVED_TAB_POSITION = "saved_tab_position";
223 private final String PROXY_MODE = "proxy_mode";
225 // Define the saved instance state variables.
226 private ArrayList<Bundle> savedStateArrayList;
227 private ArrayList<Bundle> savedNestedScrollWebViewStateArrayList;
228 private int savedTabPosition;
229 private String savedProxyMode;
231 // Define the class variables.
232 @SuppressWarnings("rawtypes")
233 AsyncTask populateBlocklists;
235 // The current WebView is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
236 // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, `applyProxy()`, and `applyDomainSettings()`.
237 private NestedScrollWebView currentWebView;
239 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
240 private final Map<String, String> customHeaders = new HashMap<>();
242 // The search URL is set in `applyAppSettings()` and used in `onNewIntent()`, `loadUrlFromTextBox()`, `initializeApp()`, and `initializeWebView()`.
243 private String searchURL;
245 // The blocklists are populated in `finishedPopulatingBlocklists()` and accessed from `initializeWebView()`.
246 private ArrayList<List<String[]>> easyList;
247 private ArrayList<List<String[]>> easyPrivacy;
248 private ArrayList<List<String[]>> fanboysAnnoyanceList;
249 private ArrayList<List<String[]>> fanboysSocialList;
250 private ArrayList<List<String[]>> ultraList;
251 private ArrayList<List<String[]>> ultraPrivacy;
253 // The action bar drawer toggle is initialized in `onCreate()` and used in `onResume()`.
254 private ActionBarDrawerToggle actionBarDrawerToggle;
256 // The color spans are used in `onCreate()` and `highlightUrlText()`.
257 private ForegroundColorSpan redColorSpan;
258 private ForegroundColorSpan initialGrayColorSpan;
259 private ForegroundColorSpan finalGrayColorSpan;
261 // `bookmarksCursor` is used in `onDestroy()`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
262 private Cursor bookmarksCursor;
264 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
265 private CursorAdapter bookmarksCursorAdapter;
267 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
268 private String oldFolderNameString;
270 // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
271 private ValueCallback<Uri[]> fileChooserCallback;
273 // The default progress view offsets are set in `onCreate()` and used in `initializeWebView()`.
274 private int appBarHeight;
275 private int defaultProgressViewStartOffset;
276 private int defaultProgressViewEndOffset;
278 // Declare the helpers.
279 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
280 private DomainsDatabaseHelper domainsDatabaseHelper;
281 private ProxyHelper proxyHelper;
282 private SanitizeUrlHelper sanitizeUrlHelper;
284 // Declare the class variables
285 private boolean bottomAppBar;
286 private boolean displayingFullScreenVideo;
287 private boolean downloadWithExternalApp;
288 private boolean fullScreenBrowsingModeEnabled;
289 private boolean hideAppBar;
290 private boolean incognitoModeEnabled;
291 private boolean inFullScreenBrowsingMode;
292 private boolean loadingNewIntent;
293 private BroadcastReceiver orbotStatusBroadcastReceiver;
294 private boolean reapplyAppSettingsOnRestart;
295 private boolean reapplyDomainSettingsOnRestart;
296 private boolean sanitizeAmpRedirects;
297 private boolean sanitizeTrackingQueries;
298 private boolean scrollAppBar;
299 private boolean waitingForProxy;
300 private String webViewDefaultUserAgent;
302 // Define the class variables.
303 private ObjectAnimator objectAnimator = new ObjectAnimator();
304 private String saveUrlString = "";
306 // Declare the class views.
307 private FrameLayout rootFrameLayout;
308 private DrawerLayout drawerLayout;
309 private CoordinatorLayout coordinatorLayout;
310 private Toolbar toolbar;
311 private RelativeLayout urlRelativeLayout;
312 private EditText urlEditText;
313 private ActionBar actionBar;
314 private LinearLayout findOnPageLinearLayout;
315 private LinearLayout tabsLinearLayout;
316 private TabLayout tabLayout;
317 private SwipeRefreshLayout swipeRefreshLayout;
318 private ViewPager webViewPager;
319 private FrameLayout fullScreenVideoFrameLayout;
321 // Declare the class menus.
322 private Menu optionsMenu;
324 // Declare the class menu items.
325 private MenuItem navigationBackMenuItem;
326 private MenuItem navigationForwardMenuItem;
327 private MenuItem navigationHistoryMenuItem;
328 private MenuItem navigationRequestsMenuItem;
329 private MenuItem optionsPrivacyMenuItem;
330 private MenuItem optionsRefreshMenuItem;
331 private MenuItem optionsCookiesMenuItem;
332 private MenuItem optionsDomStorageMenuItem;
333 private MenuItem optionsSaveFormDataMenuItem;
334 private MenuItem optionsClearDataMenuItem;
335 private MenuItem optionsClearCookiesMenuItem;
336 private MenuItem optionsClearDomStorageMenuItem;
337 private MenuItem optionsClearFormDataMenuItem;
338 private MenuItem optionsBlocklistsMenuItem;
339 private MenuItem optionsEasyListMenuItem;
340 private MenuItem optionsEasyPrivacyMenuItem;
341 private MenuItem optionsFanboysAnnoyanceListMenuItem;
342 private MenuItem optionsFanboysSocialBlockingListMenuItem;
343 private MenuItem optionsUltraListMenuItem;
344 private MenuItem optionsUltraPrivacyMenuItem;
345 private MenuItem optionsBlockAllThirdPartyRequestsMenuItem;
346 private MenuItem optionsProxyMenuItem;
347 private MenuItem optionsProxyNoneMenuItem;
348 private MenuItem optionsProxyTorMenuItem;
349 private MenuItem optionsProxyI2pMenuItem;
350 private MenuItem optionsProxyCustomMenuItem;
351 private MenuItem optionsUserAgentMenuItem;
352 private MenuItem optionsUserAgentPrivacyBrowserMenuItem;
353 private MenuItem optionsUserAgentWebViewDefaultMenuItem;
354 private MenuItem optionsUserAgentFirefoxOnAndroidMenuItem;
355 private MenuItem optionsUserAgentChromeOnAndroidMenuItem;
356 private MenuItem optionsUserAgentSafariOnIosMenuItem;
357 private MenuItem optionsUserAgentFirefoxOnLinuxMenuItem;
358 private MenuItem optionsUserAgentChromiumOnLinuxMenuItem;
359 private MenuItem optionsUserAgentFirefoxOnWindowsMenuItem;
360 private MenuItem optionsUserAgentChromeOnWindowsMenuItem;
361 private MenuItem optionsUserAgentEdgeOnWindowsMenuItem;
362 private MenuItem optionsUserAgentInternetExplorerOnWindowsMenuItem;
363 private MenuItem optionsUserAgentSafariOnMacosMenuItem;
364 private MenuItem optionsUserAgentCustomMenuItem;
365 private MenuItem optionsSwipeToRefreshMenuItem;
366 private MenuItem optionsWideViewportMenuItem;
367 private MenuItem optionsDisplayImagesMenuItem;
368 private MenuItem optionsDarkWebViewMenuItem;
369 private MenuItem optionsFontSizeMenuItem;
370 private MenuItem optionsAddOrEditDomainMenuItem;
372 // This variable won't be needed once the class is migrated to Kotlin, as can be seen in LogcatActivity or AboutVersionFragment.
373 private Activity resultLauncherActivityHandle;
375 // Define the save URL activity result launcher. It must be defined before `onCreate()` is run or the app will crash.
376 private final ActivityResultLauncher<String> saveUrlActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.CreateDocument(),
377 new ActivityResultCallback<Uri>() {
379 public void onActivityResult(Uri fileUri) {
380 // Only save the URL if the file URI is not null, which happens if the user exited the file picker by pressing back.
381 if (fileUri != null) {
382 new SaveUrl(getApplicationContext(), resultLauncherActivityHandle, fileUri, currentWebView.getSettings().getUserAgentString(), currentWebView.getAcceptCookies()).execute(saveUrlString);
385 // Reset the save URL string.
390 // Define the save webpage archive activity result launcher. It must be defined before `onCreate()` is run or the app will crash.
391 private final ActivityResultLauncher<String> saveWebpageArchiveActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.CreateDocument(),
392 new ActivityResultCallback<Uri>() {
394 public void onActivityResult(Uri fileUri) {
395 // Only save the webpage archive if the file URI is not null, which happens if the user exited the file picker by pressing back.
396 if (fileUri != null) {
398 // Create a temporary MHT file.
399 File temporaryMhtFile = File.createTempFile("temporary_mht_file", ".mht", getCacheDir());
401 // Save the temporary MHT file.
402 currentWebView.saveWebArchive(temporaryMhtFile.toString(), false, callbackValue -> {
403 if (callbackValue != null) { // The temporary MHT file was saved successfully.
405 // Create a temporary MHT file input stream.
406 FileInputStream temporaryMhtFileInputStream = new FileInputStream(temporaryMhtFile);
408 // Get an output stream for the save webpage file path.
409 OutputStream mhtOutputStream = getContentResolver().openOutputStream(fileUri);
411 // Create a transfer byte array.
412 byte[] transferByteArray = new byte[1024];
414 // Create an integer to track the number of bytes read.
417 // Copy the temporary MHT file input stream to the MHT output stream.
418 while ((bytesRead = temporaryMhtFileInputStream.read(transferByteArray)) > 0) {
419 mhtOutputStream.write(transferByteArray, 0, bytesRead);
422 // Close the streams.
423 mhtOutputStream.close();
424 temporaryMhtFileInputStream.close();
426 // Initialize the file name string from the file URI last path segment.
427 String fileNameString = fileUri.getLastPathSegment();
429 // Query the exact file name if the API >= 26.
430 if (Build.VERSION.SDK_INT >= 26) {
431 // Get a cursor from the content resolver.
432 Cursor contentResolverCursor = resultLauncherActivityHandle.getContentResolver().query(fileUri, null, null, null);
434 // Move to the fist row.
435 contentResolverCursor.moveToFirst();
437 // Get the file name from the cursor.
438 fileNameString = contentResolverCursor.getString(contentResolverCursor.getColumnIndexOrThrow(OpenableColumns.DISPLAY_NAME));
441 contentResolverCursor.close();
444 // Display a snackbar.
445 Snackbar.make(currentWebView, getString(R.string.file_saved) + " " + fileNameString, Snackbar.LENGTH_SHORT).show();
446 } catch (Exception exception) {
447 // Display a snackbar with the exception.
448 Snackbar.make(currentWebView, getString(R.string.error_saving_file) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
450 // Delete the temporary MHT file.
451 //noinspection ResultOfMethodCallIgnored
452 temporaryMhtFile.delete();
454 } else { // There was an unspecified error while saving the temporary MHT file.
455 // Display an error snackbar.
456 Snackbar.make(currentWebView, getString(R.string.error_saving_file), Snackbar.LENGTH_INDEFINITE).show();
459 } catch (IOException ioException) {
460 // Display a snackbar with the IO exception.
461 Snackbar.make(currentWebView, getString(R.string.error_saving_file) + " " + ioException, Snackbar.LENGTH_INDEFINITE).show();
467 // Define the save webpage image activity result launcher. It must be defined before `onCreate()` is run or the app will crash.
468 private final ActivityResultLauncher<String> saveWebpageImageActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.CreateDocument(),
469 new ActivityResultCallback<Uri>() {
471 public void onActivityResult(Uri fileUri) {
472 // Only save the webpage image if the file URI is not null, which happens if the user exited the file picker by pressing back.
473 if (fileUri != null) {
474 // Save the webpage image.
475 new SaveWebpageImage(resultLauncherActivityHandle, fileUri, currentWebView).execute();
480 // Remove the warning about needing to override `performClick()` when using an `OnTouchListener` with WebView.
481 @SuppressLint("ClickableViewAccessibility")
483 protected void onCreate(Bundle savedInstanceState) {
484 // Run the default commands.
485 super.onCreate(savedInstanceState);
487 // Populate the result launcher activity. This will no longer be needed once the activity has transitioned to Kotlin.
488 resultLauncherActivityHandle = this;
490 // Check to see if the activity has been restarted.
491 if (savedInstanceState != null) {
492 // Store the saved instance state variables.
493 savedStateArrayList = savedInstanceState.getParcelableArrayList(SAVED_STATE_ARRAY_LIST);
494 savedNestedScrollWebViewStateArrayList = savedInstanceState.getParcelableArrayList(SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST);
495 savedTabPosition = savedInstanceState.getInt(SAVED_TAB_POSITION);
496 savedProxyMode = savedInstanceState.getString(PROXY_MODE);
499 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
500 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
502 // Get a handle for the shared preferences.
503 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
505 // Get the preferences.
506 String appTheme = sharedPreferences.getString("app_theme", getString(R.string.app_theme_default_value));
507 boolean allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false);
508 bottomAppBar = sharedPreferences.getBoolean(getString(R.string.bottom_app_bar_key), false);
510 // Get the theme entry values string array.
511 String[] appThemeEntryValuesStringArray = getResources().getStringArray(R.array.app_theme_entry_values);
513 // 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.
514 if (appTheme.equals(appThemeEntryValuesStringArray[1])) { // The light theme is selected.
515 // Apply the light theme.
516 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
517 } else if (appTheme.equals(appThemeEntryValuesStringArray[2])) { // The dark theme is selected.
518 // Apply the dark theme.
519 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
520 } else { // The system default theme is selected.
521 if (Build.VERSION.SDK_INT >= 28) { // The system default theme is supported.
522 // Follow the system default theme.
523 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
524 } else { // The system default theme is not supported.
525 // Follow the battery saver mode.
526 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY);
530 // Disable screenshots if not allowed.
531 if (!allowScreenshots) {
532 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
535 // 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.
536 WebView.enableSlowWholeDocumentDraw();
538 // Set the content view according to the position of the app bar.
539 if (bottomAppBar) setContentView(R.layout.main_framelayout_bottom_appbar);
540 else setContentView(R.layout.main_framelayout_top_appbar);
542 // Get handles for the views.
543 rootFrameLayout = findViewById(R.id.root_framelayout);
544 drawerLayout = findViewById(R.id.drawerlayout);
545 coordinatorLayout = findViewById(R.id.coordinatorlayout);
546 appBarLayout = findViewById(R.id.appbar_layout);
547 toolbar = findViewById(R.id.toolbar);
548 findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
549 tabsLinearLayout = findViewById(R.id.tabs_linearlayout);
550 tabLayout = findViewById(R.id.tablayout);
551 swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
552 webViewPager = findViewById(R.id.webviewpager);
553 NavigationView navigationView = findViewById(R.id.navigationview);
554 fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
556 // Get a handle for the navigation menu.
557 Menu navigationMenu = navigationView.getMenu();
559 // Get handles for the navigation menu items.
560 navigationBackMenuItem = navigationMenu.findItem(R.id.back);
561 navigationForwardMenuItem = navigationMenu.findItem(R.id.forward);
562 navigationHistoryMenuItem = navigationMenu.findItem(R.id.history);
563 navigationRequestsMenuItem = navigationMenu.findItem(R.id.requests);
565 // Listen for touches on the navigation menu.
566 navigationView.setNavigationItemSelectedListener(this);
568 // Get a handle for the app compat delegate.
569 AppCompatDelegate appCompatDelegate = getDelegate();
571 // Set the support action bar.
572 appCompatDelegate.setSupportActionBar(toolbar);
574 // Get a handle for the action bar.
575 actionBar = appCompatDelegate.getSupportActionBar();
577 // Remove the incorrect lint warning below that the action bar might be null.
578 assert actionBar != null;
580 // Add the custom layout, which shows the URL text bar.
581 actionBar.setCustomView(R.layout.url_app_bar);
582 actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
584 // Get handles for the views in the URL app bar.
585 urlRelativeLayout = findViewById(R.id.url_relativelayout);
586 urlEditText = findViewById(R.id.url_edittext);
588 // Create the hamburger icon at the start of the AppBar.
589 actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
591 // Initially disable the sliding drawers. They will be enabled once the blocklists are loaded.
592 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
594 // Initialize the web view pager adapter.
595 webViewPagerAdapter = new WebViewPagerAdapter(getSupportFragmentManager());
597 // Set the pager adapter on the web view pager.
598 webViewPager.setAdapter(webViewPagerAdapter);
600 // Store up to 100 tabs in memory.
601 webViewPager.setOffscreenPageLimit(100);
603 // Instantiate the helpers.
604 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this);
605 domainsDatabaseHelper = new DomainsDatabaseHelper(this);
606 proxyHelper = new ProxyHelper();
607 sanitizeUrlHelper = new SanitizeUrlHelper();
609 // Initialize the app.
612 // Apply the app settings from the shared preferences.
615 // Populate the blocklists.
616 populateBlocklists = new PopulateBlocklists(this, this).execute();
620 protected void onNewIntent(Intent intent) {
621 // Run the default commands.
622 super.onNewIntent(intent);
624 // Replace the intent that started the app with this one.
627 // Check to see if the app is being restarted from a saved state.
628 if (savedStateArrayList == null || savedStateArrayList.size() == 0) { // The activity is not being restarted from a saved state.
629 // Get the information from the intent.
630 String intentAction = intent.getAction();
631 Uri intentUriData = intent.getData();
632 String intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT);
634 // Determine if this is a web search.
635 boolean isWebSearch = ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH));
637 // 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.
638 if (intentUriData != null || intentStringExtra != null || isWebSearch) {
639 // Exit the full screen video if it is displayed.
640 if (displayingFullScreenVideo) {
641 // Exit full screen video mode.
642 exitFullScreenVideo();
644 // Reload the current WebView. Otherwise, it can display entirely black.
645 currentWebView.reload();
648 // Get the shared preferences.
649 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
651 // Create a URL string.
654 // If the intent action is a web search, perform the search.
655 if (isWebSearch) { // The intent is a web search.
656 // Create an encoded URL string.
657 String encodedUrlString;
659 // Sanitize the search input and convert it to a search.
661 encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
662 } catch (UnsupportedEncodingException exception) {
663 encodedUrlString = "";
666 // Add the base search URL.
667 url = searchURL + encodedUrlString;
668 } else if (intentUriData != null) { // The intent contains a URL formatted as a URI.
669 // Set the intent data as the URL.
670 url = intentUriData.toString();
671 } else { // The intent contains a string, which might be a URL.
672 // Set the intent string as the URL.
673 url = intentStringExtra;
676 // Add a new tab if specified in the preferences.
677 if (sharedPreferences.getBoolean("open_intents_in_new_tab", true)) { // Load the URL in a new tab.
678 // Set the loading new intent flag.
679 loadingNewIntent = true;
682 addNewTab(url, true);
683 } else { // Load the URL in the current tab.
685 loadUrl(currentWebView, url);
688 // Close the navigation drawer if it is open.
689 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
690 drawerLayout.closeDrawer(GravityCompat.START);
693 // Close the bookmarks drawer if it is open.
694 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
695 drawerLayout.closeDrawer(GravityCompat.END);
702 public void onRestart() {
703 // Run the default commands.
706 // Apply the app settings if returning from the Settings activity.
707 if (reapplyAppSettingsOnRestart) {
708 // Reset the reapply app settings on restart tracker.
709 reapplyAppSettingsOnRestart = false;
711 // Apply the app settings.
715 // Apply the domain settings if returning from the settings or domains activity.
716 if (reapplyDomainSettingsOnRestart) {
717 // Reset the reapply domain settings on restart tracker.
718 reapplyDomainSettingsOnRestart = false;
720 // Reapply the domain settings for each tab.
721 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
722 // Get the WebView tab fragment.
723 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
725 // Get the fragment view.
726 View fragmentView = webViewTabFragment.getView();
728 // Only reload the WebViews if they exist.
729 if (fragmentView != null) {
730 // Get the nested scroll WebView from the tab fragment.
731 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
733 // Reset the current domain name so the domain settings will be reapplied.
734 nestedScrollWebView.setCurrentDomainName("");
736 // Reapply the domain settings if the URL is not null, which can happen if an empty tab is active when returning from settings.
737 if (nestedScrollWebView.getUrl() != null) {
738 applyDomainSettings(nestedScrollWebView, nestedScrollWebView.getUrl(), false, true, false);
744 // Update the bookmarks drawer if returning from the Bookmarks activity.
745 if (restartFromBookmarksActivity) {
746 // Close the bookmarks drawer.
747 drawerLayout.closeDrawer(GravityCompat.END);
749 // Reload the bookmarks drawer.
750 loadBookmarksFolder();
752 // Reset `restartFromBookmarksActivity`.
753 restartFromBookmarksActivity = false;
756 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
757 updatePrivacyIcons(true);
760 // `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.
762 public void onStart() {
763 // Run the default commands.
766 // Resume any WebViews.
767 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
768 // Get the WebView tab fragment.
769 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
771 // Get the fragment view.
772 View fragmentView = webViewTabFragment.getView();
774 // Only resume the WebViews if they exist (they won't when the app is first created).
775 if (fragmentView != null) {
776 // Get the nested scroll WebView from the tab fragment.
777 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
779 // Resume the nested scroll WebView.
780 nestedScrollWebView.onResume();
784 // Resume the nested scroll WebView JavaScript timers. This is a global command that resumes JavaScript timers on all WebViews.
785 if (currentWebView != null) {
786 currentWebView.resumeTimers();
789 // Reapply the proxy settings if the system is using a proxy. This redisplays the appropriate alert dialog.
790 if (!proxyMode.equals(ProxyHelper.NONE)) {
794 // Reapply any system UI flags.
795 if (displayingFullScreenVideo || inFullScreenBrowsingMode) { // The system is displaying a website or a video in full screen mode.
796 /* Hide the system bars.
797 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
798 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
799 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
800 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
802 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
803 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
806 // Show any pending dialogs.
807 for (int i = 0; i < pendingDialogsArrayList.size(); i++) {
808 // Get the pending dialog from the array list.
809 PendingDialog pendingDialog = pendingDialogsArrayList.get(i);
811 // Show the pending dialog.
812 pendingDialog.dialogFragment.show(getSupportFragmentManager(), pendingDialog.tag);
815 // Clear the pending dialogs array list.
816 pendingDialogsArrayList.clear();
819 // `onStop()` runs after `onPause()`. It is used instead of `onPause()` so the commands are not called every time the screen is partially hidden.
821 public void onStop() {
822 // Run the default commands.
825 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
826 // Get the WebView tab fragment.
827 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
829 // Get the fragment view.
830 View fragmentView = webViewTabFragment.getView();
832 // Only pause the WebViews if they exist (they won't when the app is first created).
833 if (fragmentView != null) {
834 // Get the nested scroll WebView from the tab fragment.
835 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
837 // Pause the nested scroll WebView.
838 nestedScrollWebView.onPause();
842 // Pause the WebView JavaScript timers. This is a global command that pauses JavaScript on all WebViews.
843 if (currentWebView != null) {
844 currentWebView.pauseTimers();
849 public void onSaveInstanceState(@NonNull Bundle savedInstanceState) {
850 // Run the default commands.
851 super.onSaveInstanceState(savedInstanceState);
853 // Create the saved state array lists.
854 ArrayList<Bundle> savedStateArrayList = new ArrayList<>();
855 ArrayList<Bundle> savedNestedScrollWebViewStateArrayList = new ArrayList<>();
857 // Get the URLs from each tab.
858 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
859 // Get the WebView tab fragment.
860 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
862 // Get the fragment view.
863 View fragmentView = webViewTabFragment.getView();
865 if (fragmentView != null) {
866 // Get the nested scroll WebView from the tab fragment.
867 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
869 // Create saved state bundle.
870 Bundle savedStateBundle = new Bundle();
872 // Get the current states.
873 nestedScrollWebView.saveState(savedStateBundle);
874 Bundle savedNestedScrollWebViewStateBundle = nestedScrollWebView.saveNestedScrollWebViewState();
876 // Store the saved states in the array lists.
877 savedStateArrayList.add(savedStateBundle);
878 savedNestedScrollWebViewStateArrayList.add(savedNestedScrollWebViewStateBundle);
882 // Get the current tab position.
883 int currentTabPosition = tabLayout.getSelectedTabPosition();
885 // Store the saved states in the bundle.
886 savedInstanceState.putParcelableArrayList(SAVED_STATE_ARRAY_LIST, savedStateArrayList);
887 savedInstanceState.putParcelableArrayList(SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST, savedNestedScrollWebViewStateArrayList);
888 savedInstanceState.putInt(SAVED_TAB_POSITION, currentTabPosition);
889 savedInstanceState.putString(PROXY_MODE, proxyMode);
893 public void onDestroy() {
894 // Unregister the orbot status broadcast receiver if it exists.
895 if (orbotStatusBroadcastReceiver != null) {
896 this.unregisterReceiver(orbotStatusBroadcastReceiver);
899 // Close the bookmarks cursor if it exists.
900 if (bookmarksCursor != null) {
901 bookmarksCursor.close();
904 // Close the bookmarks database if it exists.
905 if (bookmarksDatabaseHelper != null) {
906 bookmarksDatabaseHelper.close();
909 // Stop populating the blocklists if the AsyncTask is running in the background.
910 if (populateBlocklists != null) {
911 populateBlocklists.cancel(true);
914 // Run the default commands.
919 public boolean onCreateOptionsMenu(Menu menu) {
920 // Inflate the menu. This adds items to the action bar if it is present.
921 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
923 // Store a handle for the options menu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons()`.
926 // Get handles for the menu items.
927 optionsPrivacyMenuItem = menu.findItem(R.id.javascript);
928 optionsRefreshMenuItem = menu.findItem(R.id.refresh);
929 MenuItem bookmarksMenuItem = menu.findItem(R.id.bookmarks);
930 optionsCookiesMenuItem = menu.findItem(R.id.cookies);
931 optionsDomStorageMenuItem = menu.findItem(R.id.dom_storage);
932 optionsSaveFormDataMenuItem = menu.findItem(R.id.save_form_data); // Form data can be removed once the minimum API >= 26.
933 optionsClearDataMenuItem = menu.findItem(R.id.clear_data);
934 optionsClearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
935 optionsClearDomStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
936 optionsClearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
937 optionsBlocklistsMenuItem = menu.findItem(R.id.blocklists);
938 optionsEasyListMenuItem = menu.findItem(R.id.easylist);
939 optionsEasyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
940 optionsFanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
941 optionsFanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
942 optionsUltraListMenuItem = menu.findItem(R.id.ultralist);
943 optionsUltraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
944 optionsBlockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
945 optionsProxyMenuItem = menu.findItem(R.id.proxy);
946 optionsProxyNoneMenuItem = menu.findItem(R.id.proxy_none);
947 optionsProxyTorMenuItem = menu.findItem(R.id.proxy_tor);
948 optionsProxyI2pMenuItem = menu.findItem(R.id.proxy_i2p);
949 optionsProxyCustomMenuItem = menu.findItem(R.id.proxy_custom);
950 optionsUserAgentMenuItem = menu.findItem(R.id.user_agent);
951 optionsUserAgentPrivacyBrowserMenuItem = menu.findItem(R.id.user_agent_privacy_browser);
952 optionsUserAgentWebViewDefaultMenuItem = menu.findItem(R.id.user_agent_webview_default);
953 optionsUserAgentFirefoxOnAndroidMenuItem = menu.findItem(R.id.user_agent_firefox_on_android);
954 optionsUserAgentChromeOnAndroidMenuItem = menu.findItem(R.id.user_agent_chrome_on_android);
955 optionsUserAgentSafariOnIosMenuItem = menu.findItem(R.id.user_agent_safari_on_ios);
956 optionsUserAgentFirefoxOnLinuxMenuItem = menu.findItem(R.id.user_agent_firefox_on_linux);
957 optionsUserAgentChromiumOnLinuxMenuItem = menu.findItem(R.id.user_agent_chromium_on_linux);
958 optionsUserAgentFirefoxOnWindowsMenuItem = menu.findItem(R.id.user_agent_firefox_on_windows);
959 optionsUserAgentChromeOnWindowsMenuItem = menu.findItem(R.id.user_agent_chrome_on_windows);
960 optionsUserAgentEdgeOnWindowsMenuItem = menu.findItem(R.id.user_agent_edge_on_windows);
961 optionsUserAgentInternetExplorerOnWindowsMenuItem = menu.findItem(R.id.user_agent_internet_explorer_on_windows);
962 optionsUserAgentSafariOnMacosMenuItem = menu.findItem(R.id.user_agent_safari_on_macos);
963 optionsUserAgentCustomMenuItem = menu.findItem(R.id.user_agent_custom);
964 optionsSwipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
965 optionsWideViewportMenuItem = menu.findItem(R.id.wide_viewport);
966 optionsDisplayImagesMenuItem = menu.findItem(R.id.display_images);
967 optionsDarkWebViewMenuItem = menu.findItem(R.id.dark_webview);
968 optionsFontSizeMenuItem = menu.findItem(R.id.font_size);
969 optionsAddOrEditDomainMenuItem = menu.findItem(R.id.add_or_edit_domain);
971 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
972 updatePrivacyIcons(false);
974 // Only display the form data menu items if the API < 26.
975 optionsSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
976 optionsClearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
978 // Disable the clear form data menu item if the API >= 26 so that the status of the main Clear Data is calculated correctly.
979 optionsClearFormDataMenuItem.setEnabled(Build.VERSION.SDK_INT < 26);
981 // Get the shared preferences.
982 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
984 // Get the dark theme and app bar preferences.
985 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean(getString(R.string.display_additional_app_bar_icons_key), false);
987 // 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.
988 if (displayAdditionalAppBarIcons) {
989 optionsRefreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
990 bookmarksMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
991 optionsCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
992 } else { //Do not display the additional icons.
993 optionsRefreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
994 bookmarksMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
995 optionsCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
998 // Replace Refresh with Stop if a URL is already loading.
999 if (currentWebView != null && currentWebView.getProgress() != 100) {
1001 optionsRefreshMenuItem.setTitle(R.string.stop);
1003 // 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.
1004 if (displayAdditionalAppBarIcons) {
1005 optionsRefreshMenuItem.setIcon(R.drawable.close_blue);
1014 public boolean onPrepareOptionsMenu(Menu menu) {
1015 // Get a handle for the cookie manager.
1016 CookieManager cookieManager = CookieManager.getInstance();
1018 // Initialize the current user agent string and the font size.
1019 String currentUserAgent = getString(R.string.user_agent_privacy_browser);
1022 // 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.
1023 if (currentWebView != null) {
1024 // Set the add or edit domain text.
1025 if (currentWebView.getDomainSettingsApplied()) {
1026 optionsAddOrEditDomainMenuItem.setTitle(R.string.edit_domain_settings);
1028 optionsAddOrEditDomainMenuItem.setTitle(R.string.add_domain_settings);
1031 // Get the current user agent from the WebView.
1032 currentUserAgent = currentWebView.getSettings().getUserAgentString();
1034 // Get the current font size from the
1035 fontSize = currentWebView.getSettings().getTextZoom();
1037 // Set the status of the menu item checkboxes.
1038 optionsDomStorageMenuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1039 optionsSaveFormDataMenuItem.setChecked(currentWebView.getSettings().getSaveFormData()); // Form data can be removed once the minimum API >= 26.
1040 optionsEasyListMenuItem.setChecked(currentWebView.getEasyListEnabled());
1041 optionsEasyPrivacyMenuItem.setChecked(currentWebView.getEasyPrivacyEnabled());
1042 optionsFanboysAnnoyanceListMenuItem.setChecked(currentWebView.getFanboysAnnoyanceListEnabled());
1043 optionsFanboysSocialBlockingListMenuItem.setChecked(currentWebView.getFanboysSocialBlockingListEnabled());
1044 optionsUltraListMenuItem.setChecked(currentWebView.getUltraListEnabled());
1045 optionsUltraPrivacyMenuItem.setChecked(currentWebView.getUltraPrivacyEnabled());
1046 optionsBlockAllThirdPartyRequestsMenuItem.setChecked(currentWebView.getBlockAllThirdPartyRequests());
1047 optionsSwipeToRefreshMenuItem.setChecked(currentWebView.getSwipeToRefresh());
1048 optionsWideViewportMenuItem.setChecked(currentWebView.getSettings().getUseWideViewPort());
1049 optionsDisplayImagesMenuItem.setChecked(currentWebView.getSettings().getLoadsImagesAutomatically());
1051 // Initialize the display names for the blocklists with the number of blocked requests.
1052 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
1053 optionsEasyListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASYLIST) + " - " + getString(R.string.easylist));
1054 optionsEasyPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASYPRIVACY) + " - " + getString(R.string.easyprivacy));
1055 optionsFanboysAnnoyanceListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " + getString(R.string.fanboys_annoyance_list));
1056 optionsFanboysSocialBlockingListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " + getString(R.string.fanboys_social_blocking_list));
1057 optionsUltraListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRALIST) + " - " + getString(R.string.ultralist));
1058 optionsUltraPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRAPRIVACY) + " - " + getString(R.string.ultraprivacy));
1059 optionsBlockAllThirdPartyRequestsMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " + getString(R.string.block_all_third_party_requests));
1061 // Enable DOM Storage if JavaScript is enabled.
1062 optionsDomStorageMenuItem.setEnabled(currentWebView.getSettings().getJavaScriptEnabled());
1064 // Set the checkbox status for dark WebView if the WebView supports it.
1065 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
1066 optionsDarkWebViewMenuItem.setChecked(WebSettingsCompat.getForceDark(currentWebView.getSettings()) == WebSettingsCompat.FORCE_DARK_ON);
1070 // Set the cookies menu item checked status.
1071 optionsCookiesMenuItem.setChecked(cookieManager.acceptCookie());
1073 // Enable Clear Cookies if there are any.
1074 optionsClearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1076 // 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`.
1077 String privateDataDirectoryString = getApplicationInfo().dataDir;
1079 // Get a count of the number of files in the Local Storage directory.
1080 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1081 int localStorageDirectoryNumberOfFiles = 0;
1082 if (localStorageDirectory.exists()) {
1083 // `Objects.requireNonNull` removes a lint warning that `localStorageDirectory.list` might produce a null pointed exception if it is dereferenced.
1084 localStorageDirectoryNumberOfFiles = Objects.requireNonNull(localStorageDirectory.list()).length;
1087 // Get a count of the number of files in the IndexedDB directory.
1088 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1089 int indexedDBDirectoryNumberOfFiles = 0;
1090 if (indexedDBDirectory.exists()) {
1091 // `Objects.requireNonNull` removes a lint warning that `indexedDBDirectory.list` might produce a null pointed exception if it is dereferenced.
1092 indexedDBDirectoryNumberOfFiles = Objects.requireNonNull(indexedDBDirectory.list()).length;
1095 // Enable Clear DOM Storage if there is any.
1096 optionsClearDomStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1098 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
1099 if (Build.VERSION.SDK_INT < 26) {
1100 // Get the WebView database.
1101 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1103 // Enable the clear form data menu item if there is anything to clear.
1104 optionsClearFormDataMenuItem.setEnabled(webViewDatabase.hasFormData());
1107 // Enable Clear Data if any of the submenu items are enabled.
1108 optionsClearDataMenuItem.setEnabled(optionsClearCookiesMenuItem.isEnabled() || optionsClearDomStorageMenuItem.isEnabled() || optionsClearFormDataMenuItem.isEnabled());
1110 // Disable Fanboy's Social Blocking List menu item if Fanboy's Annoyance List is checked.
1111 optionsFanboysSocialBlockingListMenuItem.setEnabled(!optionsFanboysAnnoyanceListMenuItem.isChecked());
1113 // Set the proxy title and check the applied proxy.
1114 switch (proxyMode) {
1115 case ProxyHelper.NONE:
1116 // Set the proxy title.
1117 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_none));
1119 // Check the proxy None radio button.
1120 optionsProxyNoneMenuItem.setChecked(true);
1123 case ProxyHelper.TOR:
1124 // Set the proxy title.
1125 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_tor));
1127 // Check the proxy Tor radio button.
1128 optionsProxyTorMenuItem.setChecked(true);
1131 case ProxyHelper.I2P:
1132 // Set the proxy title.
1133 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_i2p));
1135 // Check the proxy I2P radio button.
1136 optionsProxyI2pMenuItem.setChecked(true);
1139 case ProxyHelper.CUSTOM:
1140 // Set the proxy title.
1141 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_custom));
1143 // Check the proxy Custom radio button.
1144 optionsProxyCustomMenuItem.setChecked(true);
1148 // Select the current user agent menu item. A switch statement cannot be used because the user agents are not compile time constants.
1149 if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) { // Privacy Browser.
1150 // Update the user agent menu item title.
1151 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_privacy_browser));
1153 // Select the Privacy Browser radio box.
1154 optionsUserAgentPrivacyBrowserMenuItem.setChecked(true);
1155 } else if (currentUserAgent.equals(webViewDefaultUserAgent)) { // WebView Default.
1156 // Update the user agent menu item title.
1157 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_webview_default));
1159 // Select the WebView Default radio box.
1160 optionsUserAgentWebViewDefaultMenuItem.setChecked(true);
1161 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) { // Firefox on Android.
1162 // Update the user agent menu item title.
1163 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_android));
1165 // Select the Firefox on Android radio box.
1166 optionsUserAgentFirefoxOnAndroidMenuItem.setChecked(true);
1167 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) { // Chrome on Android.
1168 // Update the user agent menu item title.
1169 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_android));
1171 // Select the Chrome on Android radio box.
1172 optionsUserAgentChromeOnAndroidMenuItem.setChecked(true);
1173 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) { // Safari on iOS.
1174 // Update the user agent menu item title.
1175 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_ios));
1177 // Select the Safari on iOS radio box.
1178 optionsUserAgentSafariOnIosMenuItem.setChecked(true);
1179 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) { // Firefox on Linux.
1180 // Update the user agent menu item title.
1181 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_linux));
1183 // Select the Firefox on Linux radio box.
1184 optionsUserAgentFirefoxOnLinuxMenuItem.setChecked(true);
1185 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) { // Chromium on Linux.
1186 // Update the user agent menu item title.
1187 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chromium_on_linux));
1189 // Select the Chromium on Linux radio box.
1190 optionsUserAgentChromiumOnLinuxMenuItem.setChecked(true);
1191 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) { // Firefox on Windows.
1192 // Update the user agent menu item title.
1193 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_windows));
1195 // Select the Firefox on Windows radio box.
1196 optionsUserAgentFirefoxOnWindowsMenuItem.setChecked(true);
1197 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) { // Chrome on Windows.
1198 // Update the user agent menu item title.
1199 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_windows));
1201 // Select the Chrome on Windows radio box.
1202 optionsUserAgentChromeOnWindowsMenuItem.setChecked(true);
1203 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) { // Edge on Windows.
1204 // Update the user agent menu item title.
1205 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_edge_on_windows));
1207 // Select the Edge on Windows radio box.
1208 optionsUserAgentEdgeOnWindowsMenuItem.setChecked(true);
1209 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) { // Internet Explorer on Windows.
1210 // Update the user agent menu item title.
1211 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_internet_explorer_on_windows));
1213 // Select the Internet on Windows radio box.
1214 optionsUserAgentInternetExplorerOnWindowsMenuItem.setChecked(true);
1215 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) { // Safari on macOS.
1216 // Update the user agent menu item title.
1217 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_macos));
1219 // Select the Safari on macOS radio box.
1220 optionsUserAgentSafariOnMacosMenuItem.setChecked(true);
1221 } else { // Custom user agent.
1222 // Update the user agent menu item title.
1223 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_custom));
1225 // Select the Custom radio box.
1226 optionsUserAgentCustomMenuItem.setChecked(true);
1229 // Set the font size title.
1230 optionsFontSizeMenuItem.setTitle(getString(R.string.font_size) + " - " + fontSize + "%");
1232 // Run all the other default commands.
1233 super.onPrepareOptionsMenu(menu);
1235 // Display the menu.
1240 public boolean onOptionsItemSelected(MenuItem menuItem) {
1241 // Get a handle for the shared preferences.
1242 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1244 // Get a handle for the cookie manager.
1245 CookieManager cookieManager = CookieManager.getInstance();
1247 // Get the selected menu item ID.
1248 int menuItemId = menuItem.getItemId();
1250 // Run the commands that correlate to the selected menu item.
1251 if (menuItemId == R.id.javascript) { // JavaScript.
1252 // Toggle the JavaScript status.
1253 currentWebView.getSettings().setJavaScriptEnabled(!currentWebView.getSettings().getJavaScriptEnabled());
1255 // Update the privacy icon.
1256 updatePrivacyIcons(true);
1258 // Display a `Snackbar`.
1259 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScrip is enabled.
1260 Snackbar.make(webViewPager, R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1261 } else if (cookieManager.acceptCookie()) { // JavaScript is disabled, but first-party cookies are enabled.
1262 Snackbar.make(webViewPager, R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1263 } else { // Privacy mode.
1264 Snackbar.make(webViewPager, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1267 // Reload the current WebView.
1268 currentWebView.reload();
1270 // Consume the event.
1272 } else if (menuItemId == R.id.refresh) { // Refresh.
1273 // Run the command that correlates to the current status of the menu item.
1274 if (menuItem.getTitle().equals(getString(R.string.refresh))) { // The refresh button was pushed.
1275 // Reload the current WebView.
1276 currentWebView.reload();
1277 } else { // The stop button was pushed.
1278 // Stop the loading of the WebView.
1279 currentWebView.stopLoading();
1282 // Consume the event.
1284 } else if (menuItemId == R.id.bookmarks) { // Bookmarks.
1285 // Open the bookmarks drawer.
1286 drawerLayout.openDrawer(GravityCompat.END);
1288 // Consume the event.
1290 } else if (menuItemId == R.id.cookies) { // Cookies.
1291 // Switch the first-party cookie status.
1292 cookieManager.setAcceptCookie(!cookieManager.acceptCookie());
1294 // Store the cookie status.
1295 currentWebView.setAcceptCookies(cookieManager.acceptCookie());
1297 // Update the menu checkbox.
1298 menuItem.setChecked(cookieManager.acceptCookie());
1300 // Update the privacy icon.
1301 updatePrivacyIcons(true);
1303 // Display a snackbar.
1304 if (cookieManager.acceptCookie()) { // Cookies are enabled.
1305 Snackbar.make(webViewPager, R.string.cookies_enabled, Snackbar.LENGTH_SHORT).show();
1306 } else if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is still enabled.
1307 Snackbar.make(webViewPager, R.string.cookies_disabled, Snackbar.LENGTH_SHORT).show();
1308 } else { // Privacy mode.
1309 Snackbar.make(webViewPager, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1312 // Reload the current WebView.
1313 currentWebView.reload();
1315 // Consume the event.
1317 } else if (menuItemId == R.id.dom_storage) { // DOM storage.
1318 // Toggle the status of domStorageEnabled.
1319 currentWebView.getSettings().setDomStorageEnabled(!currentWebView.getSettings().getDomStorageEnabled());
1321 // Update the menu checkbox.
1322 menuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1324 // Update the privacy icon.
1325 updatePrivacyIcons(true);
1327 // Display a snackbar.
1328 if (currentWebView.getSettings().getDomStorageEnabled()) {
1329 Snackbar.make(webViewPager, R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1331 Snackbar.make(webViewPager, R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1334 // Reload the current WebView.
1335 currentWebView.reload();
1337 // Consume the event.
1339 } else if (menuItemId == R.id.save_form_data) { // Form data. This can be removed once the minimum API >= 26.
1340 // Switch the status of saveFormDataEnabled.
1341 currentWebView.getSettings().setSaveFormData(!currentWebView.getSettings().getSaveFormData());
1343 // Update the menu checkbox.
1344 menuItem.setChecked(currentWebView.getSettings().getSaveFormData());
1346 // Display a snackbar.
1347 if (currentWebView.getSettings().getSaveFormData()) {
1348 Snackbar.make(webViewPager, R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1350 Snackbar.make(webViewPager, R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1353 // Update the privacy icon.
1354 updatePrivacyIcons(true);
1356 // Reload the current WebView.
1357 currentWebView.reload();
1359 // Consume the event.
1361 } else if (menuItemId == R.id.clear_cookies) { // Clear cookies.
1362 // Create a snackbar.
1363 Snackbar.make(webViewPager, R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1364 .setAction(R.string.undo, v -> {
1365 // Do nothing because everything will be handled by `onDismissed()` below.
1367 .addCallback(new Snackbar.Callback() {
1369 public void onDismissed(Snackbar snackbar, int event) {
1370 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1371 // Delete the cookies.
1372 cookieManager.removeAllCookies(null);
1378 // Consume the event.
1380 } else if (menuItemId == R.id.clear_dom_storage) { // Clear DOM storage.
1381 // Create a snackbar.
1382 Snackbar.make(webViewPager, R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1383 .setAction(R.string.undo, v -> {
1384 // Do nothing because everything will be handled by `onDismissed()` below.
1386 .addCallback(new Snackbar.Callback() {
1388 public void onDismissed(Snackbar snackbar, int event) {
1389 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1390 // Delete the DOM Storage.
1391 WebStorage webStorage = WebStorage.getInstance();
1392 webStorage.deleteAllData();
1394 // Initialize a handler to manually delete the DOM storage files and directories.
1395 Handler deleteDomStorageHandler = new Handler();
1397 // Setup a runnable to manually delete the DOM storage files and directories.
1398 Runnable deleteDomStorageRunnable = () -> {
1400 // Get a handle for the runtime.
1401 Runtime runtime = Runtime.getRuntime();
1403 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
1404 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
1405 String privateDataDirectoryString = getApplicationInfo().dataDir;
1407 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1408 Process deleteLocalStorageProcess = runtime.exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1410 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1411 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1412 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1413 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1414 Process deleteDatabasesProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1416 // Wait for the processes to finish.
1417 deleteLocalStorageProcess.waitFor();
1418 deleteIndexProcess.waitFor();
1419 deleteQuotaManagerProcess.waitFor();
1420 deleteQuotaManagerJournalProcess.waitFor();
1421 deleteDatabasesProcess.waitFor();
1422 } catch (Exception exception) {
1423 // Do nothing if an error is thrown.
1427 // Manually delete the DOM storage files after 200 milliseconds.
1428 deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200);
1434 // Consume the event.
1436 } else if (menuItemId == R.id.clear_form_data) { // Clear form data. This can be remove once the minimum API >= 26.
1437 // Create a snackbar.
1438 Snackbar.make(webViewPager, R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1439 .setAction(R.string.undo, v -> {
1440 // Do nothing because everything will be handled by `onDismissed()` below.
1442 .addCallback(new Snackbar.Callback() {
1444 public void onDismissed(Snackbar snackbar, int event) {
1445 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1446 // Get a handle for the webView database.
1447 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1449 // Delete the form data.
1450 webViewDatabase.clearFormData();
1456 // Consume the event.
1458 } else if (menuItemId == R.id.easylist) { // EasyList.
1459 // Toggle the EasyList status.
1460 currentWebView.setEasyListEnabled(!currentWebView.getEasyListEnabled());
1462 // Update the menu checkbox.
1463 menuItem.setChecked(currentWebView.getEasyListEnabled());
1465 // Reload the current WebView.
1466 currentWebView.reload();
1468 // Consume the event.
1470 } else if (menuItemId == R.id.easyprivacy) { // EasyPrivacy.
1471 // Toggle the EasyPrivacy status.
1472 currentWebView.setEasyPrivacyEnabled(!currentWebView.getEasyPrivacyEnabled());
1474 // Update the menu checkbox.
1475 menuItem.setChecked(currentWebView.getEasyPrivacyEnabled());
1477 // Reload the current WebView.
1478 currentWebView.reload();
1480 // Consume the event.
1482 } else if (menuItemId == R.id.fanboys_annoyance_list) { // Fanboy's Annoyance List.
1483 // Toggle Fanboy's Annoyance List status.
1484 currentWebView.setFanboysAnnoyanceListEnabled(!currentWebView.getFanboysAnnoyanceListEnabled());
1486 // Update the menu checkbox.
1487 menuItem.setChecked(currentWebView.getFanboysAnnoyanceListEnabled());
1489 // Update the status of Fanboy's Social Blocking List.
1490 optionsFanboysSocialBlockingListMenuItem.setEnabled(!currentWebView.getFanboysAnnoyanceListEnabled());
1492 // Reload the current WebView.
1493 currentWebView.reload();
1495 // Consume the event.
1497 } else if (menuItemId == R.id.fanboys_social_blocking_list) { // Fanboy's Social Blocking List.
1498 // Toggle Fanboy's Social Blocking List status.
1499 currentWebView.setFanboysSocialBlockingListEnabled(!currentWebView.getFanboysSocialBlockingListEnabled());
1501 // Update the menu checkbox.
1502 menuItem.setChecked(currentWebView.getFanboysSocialBlockingListEnabled());
1504 // Reload the current WebView.
1505 currentWebView.reload();
1507 // Consume the event.
1509 } else if (menuItemId == R.id.ultralist) { // UltraList.
1510 // Toggle the UltraList status.
1511 currentWebView.setUltraListEnabled(!currentWebView.getUltraListEnabled());
1513 // Update the menu checkbox.
1514 menuItem.setChecked(currentWebView.getUltraListEnabled());
1516 // Reload the current WebView.
1517 currentWebView.reload();
1519 // Consume the event.
1521 } else if (menuItemId == R.id.ultraprivacy) { // UltraPrivacy.
1522 // Toggle the UltraPrivacy status.
1523 currentWebView.setUltraPrivacyEnabled(!currentWebView.getUltraPrivacyEnabled());
1525 // Update the menu checkbox.
1526 menuItem.setChecked(currentWebView.getUltraPrivacyEnabled());
1528 // Reload the current WebView.
1529 currentWebView.reload();
1531 // Consume the event.
1533 } else if (menuItemId == R.id.block_all_third_party_requests) { // Block all third-party requests.
1534 //Toggle the third-party requests blocker status.
1535 currentWebView.setBlockAllThirdPartyRequests(!currentWebView.getBlockAllThirdPartyRequests());
1537 // Update the menu checkbox.
1538 menuItem.setChecked(currentWebView.getBlockAllThirdPartyRequests());
1540 // Reload the current WebView.
1541 currentWebView.reload();
1543 // Consume the event.
1545 } else if (menuItemId == R.id.proxy_none) { // Proxy - None.
1546 // Update the proxy mode.
1547 proxyMode = ProxyHelper.NONE;
1549 // Apply the proxy mode.
1552 // Consume the event.
1554 } else if (menuItemId == R.id.proxy_tor) { // Proxy - Tor.
1555 // Update the proxy mode.
1556 proxyMode = ProxyHelper.TOR;
1558 // Apply the proxy mode.
1561 // Consume the event.
1563 } else if (menuItemId == R.id.proxy_i2p) { // Proxy - I2P.
1564 // Update the proxy mode.
1565 proxyMode = ProxyHelper.I2P;
1567 // Apply the proxy mode.
1570 // Consume the event.
1572 } else if (menuItemId == R.id.proxy_custom) { // Proxy - Custom.
1573 // Update the proxy mode.
1574 proxyMode = ProxyHelper.CUSTOM;
1576 // Apply the proxy mode.
1579 // Consume the event.
1581 } else if (menuItemId == R.id.user_agent_privacy_browser) { // User Agent - Privacy Browser.
1582 // Update the user agent.
1583 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
1585 // Reload the current WebView.
1586 currentWebView.reload();
1588 // Consume the event.
1590 } else if (menuItemId == R.id.user_agent_webview_default) { // User Agent - WebView Default.
1591 // Update the user agent.
1592 currentWebView.getSettings().setUserAgentString("");
1594 // Reload the current WebView.
1595 currentWebView.reload();
1597 // Consume the event.
1599 } else if (menuItemId == R.id.user_agent_firefox_on_android) { // User Agent - Firefox on Android.
1600 // Update the user agent.
1601 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
1603 // Reload the current WebView.
1604 currentWebView.reload();
1606 // Consume the event.
1608 } else if (menuItemId == R.id.user_agent_chrome_on_android) { // User Agent - Chrome on Android.
1609 // Update the user agent.
1610 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
1612 // Reload the current WebView.
1613 currentWebView.reload();
1615 // Consume the event.
1617 } else if (menuItemId == R.id.user_agent_safari_on_ios) { // User Agent - Safari on iOS.
1618 // Update the user agent.
1619 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
1621 // Reload the current WebView.
1622 currentWebView.reload();
1624 // Consume the event.
1626 } else if (menuItemId == R.id.user_agent_firefox_on_linux) { // User Agent - Firefox on Linux.
1627 // Update the user agent.
1628 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
1630 // Reload the current WebView.
1631 currentWebView.reload();
1633 // Consume the event.
1635 } else if (menuItemId == R.id.user_agent_chromium_on_linux) { // User Agent - Chromium on Linux.
1636 // Update the user agent.
1637 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
1639 // Reload the current WebView.
1640 currentWebView.reload();
1642 // Consume the event.
1644 } else if (menuItemId == R.id.user_agent_firefox_on_windows) { // User Agent - Firefox on Windows.
1645 // Update the user agent.
1646 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
1648 // Reload the current WebView.
1649 currentWebView.reload();
1651 // Consume the event.
1653 } else if (menuItemId == R.id.user_agent_chrome_on_windows) { // User Agent - Chrome on Windows.
1654 // Update the user agent.
1655 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
1657 // Reload the current WebView.
1658 currentWebView.reload();
1660 // Consume the event.
1662 } else if (menuItemId == R.id.user_agent_edge_on_windows) { // User Agent - Edge on Windows.
1663 // Update the user agent.
1664 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
1666 // Reload the current WebView.
1667 currentWebView.reload();
1669 // Consume the event.
1671 } else if (menuItemId == R.id.user_agent_internet_explorer_on_windows) { // User Agent - Internet Explorer on Windows.
1672 // Update the user agent.
1673 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
1675 // Reload the current WebView.
1676 currentWebView.reload();
1678 // Consume the event.
1680 } else if (menuItemId == R.id.user_agent_safari_on_macos) { // User Agent - Safari on macOS.
1681 // Update the user agent.
1682 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
1684 // Reload the current WebView.
1685 currentWebView.reload();
1687 // Consume the event.
1689 } else if (menuItemId == R.id.user_agent_custom) { // User Agent - Custom.
1690 // Update the user agent.
1691 currentWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
1693 // Reload the current WebView.
1694 currentWebView.reload();
1696 // Consume the event.
1698 } else if (menuItemId == R.id.font_size) { // Font size.
1699 // Instantiate the font size dialog.
1700 DialogFragment fontSizeDialogFragment = FontSizeDialog.displayDialog(currentWebView.getSettings().getTextZoom());
1702 // Show the font size dialog.
1703 fontSizeDialogFragment.show(getSupportFragmentManager(), getString(R.string.font_size));
1705 // Consume the event.
1707 } else if (menuItemId == R.id.swipe_to_refresh) { // Swipe to refresh.
1708 // Toggle the stored status of swipe to refresh.
1709 currentWebView.setSwipeToRefresh(!currentWebView.getSwipeToRefresh());
1711 // Update the swipe refresh layout.
1712 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
1713 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
1714 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
1715 } else { // Swipe to refresh is disabled.
1716 // Disable the swipe refresh layout.
1717 swipeRefreshLayout.setEnabled(false);
1720 // Consume the event.
1722 } else if (menuItemId == R.id.wide_viewport) { // Wide viewport.
1723 // Toggle the viewport.
1724 currentWebView.getSettings().setUseWideViewPort(!currentWebView.getSettings().getUseWideViewPort());
1726 // Consume the event.
1728 } else if (menuItemId == R.id.display_images) { // Display images.
1729 // Toggle the displaying of images.
1730 if (currentWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1731 // Disable loading of images.
1732 currentWebView.getSettings().setLoadsImagesAutomatically(false);
1734 // Reload the website to remove existing images.
1735 currentWebView.reload();
1736 } else { // Images are not currently loaded automatically.
1737 // Enable loading of images. Missing images will be loaded without the need for a reload.
1738 currentWebView.getSettings().setLoadsImagesAutomatically(true);
1741 // Consume the event.
1743 } else if (menuItemId == R.id.dark_webview) { // Dark WebView.
1744 // Check to see if dark WebView is supported by this WebView.
1745 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
1746 // Toggle the dark WebView setting.
1747 if (WebSettingsCompat.getForceDark(currentWebView.getSettings()) == WebSettingsCompat.FORCE_DARK_ON) { // Dark WebView is currently enabled.
1748 // Turn off dark WebView.
1749 WebSettingsCompat.setForceDark(currentWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
1750 } else { // Dark WebView is currently disabled.
1751 // Turn on dark WebView.
1752 WebSettingsCompat.setForceDark(currentWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
1756 // Consume the event.
1758 } else if (menuItemId == R.id.find_on_page) { // Find on page.
1759 // Get a handle for the views.
1760 Toolbar toolbar = findViewById(R.id.toolbar);
1761 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
1762 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
1764 // Set the minimum height of the find on page linear layout to match the toolbar.
1765 findOnPageLinearLayout.setMinimumHeight(toolbar.getHeight());
1767 // Hide the toolbar.
1768 toolbar.setVisibility(View.GONE);
1770 // Show the find on page linear layout.
1771 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1773 // Display the keyboard. The app must wait 200 ms before running the command to work around a bug in Android.
1774 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1775 findOnPageEditText.postDelayed(() -> {
1776 // Set the focus on the find on page edit text.
1777 findOnPageEditText.requestFocus();
1779 // Get a handle for the input method manager.
1780 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1782 // Remove the lint warning below that the input method manager might be null.
1783 assert inputMethodManager != null;
1785 // Display the keyboard. `0` sets no input flags.
1786 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1789 // Consume the event.
1791 } else if (menuItemId == R.id.print) { // Print.
1792 // Get a print manager instance.
1793 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1795 // Remove the lint error below that print manager might be null.
1796 assert printManager != null;
1798 // Create a print document adapter from the current WebView.
1799 PrintDocumentAdapter printDocumentAdapter = currentWebView.createPrintDocumentAdapter(getString(R.string.print));
1801 // Print the document.
1802 printManager.print(getString(R.string.privacy_browser_webpage), printDocumentAdapter, null);
1804 // Consume the event.
1806 } else if (menuItemId == R.id.save_url) { // Save URL.
1807 // Check the download preference.
1808 if (downloadWithExternalApp) { // Download with an external app.
1809 downloadUrlWithExternalApp(currentWebView.getCurrentUrl());
1810 } else { // Handle the download inside of Privacy Browser.
1811 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
1812 new PrepareSaveDialog(this, this, getSupportFragmentManager(), currentWebView.getSettings().getUserAgentString(),
1813 currentWebView.getAcceptCookies()).execute(currentWebView.getCurrentUrl());
1816 // Consume the event.
1818 } else if (menuItemId == R.id.save_archive) {
1819 // Open the file picker with a default file name built from the current domain name.
1820 saveWebpageArchiveActivityResultLauncher.launch(currentWebView.getCurrentDomainName() + ".mht");
1822 // Consume the event.
1824 } else if (menuItemId == R.id.save_image) { // Save image.
1825 // Open the file picker with a default file name built from the current domain name.
1826 saveWebpageImageActivityResultLauncher.launch(currentWebView.getCurrentDomainName() + ".png");
1828 // Consume the event.
1830 } else if (menuItemId == R.id.add_to_homescreen) { // Add to homescreen.
1831 // Instantiate the create home screen shortcut dialog.
1832 DialogFragment createHomeScreenShortcutDialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView.getTitle(), currentWebView.getUrl(),
1833 currentWebView.getFavoriteOrDefaultIcon());
1835 // Show the create home screen shortcut dialog.
1836 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
1838 // Consume the event.
1840 } else if (menuItemId == R.id.view_source) { // View source.
1841 // Create an intent to launch the view source activity.
1842 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
1844 // Add the variables to the intent.
1845 viewSourceIntent.putExtra(ViewSourceActivityKt.CURRENT_URL, currentWebView.getUrl());
1846 viewSourceIntent.putExtra(ViewSourceActivityKt.USER_AGENT, currentWebView.getSettings().getUserAgentString());
1849 startActivity(viewSourceIntent);
1851 // Consume the event.
1853 } else if (menuItemId == R.id.share_message) { // Share a message.
1854 // Prepare the share string.
1855 String shareString = currentWebView.getTitle() + " – " + currentWebView.getUrl();
1857 // Create the share intent.
1858 Intent shareMessageIntent = new Intent(Intent.ACTION_SEND);
1860 // Add the share string to the intent.
1861 shareMessageIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1863 // Set the MIME type.
1864 shareMessageIntent.setType("text/plain");
1866 // Set the intent to open in a new task.
1867 shareMessageIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1870 startActivity(Intent.createChooser(shareMessageIntent, getString(R.string.share_message)));
1872 // Consume the event.
1874 } else if (menuItemId == R.id.share_url) { // Share URL.
1875 // Create the share intent.
1876 Intent shareUrlIntent = new Intent(Intent.ACTION_SEND);
1878 // Add the URL to the intent.
1879 shareUrlIntent.putExtra(Intent.EXTRA_TEXT, currentWebView.getUrl());
1881 // Add the title to the intent.
1882 shareUrlIntent.putExtra(Intent.EXTRA_SUBJECT, currentWebView.getTitle());
1884 // Set the MIME type.
1885 shareUrlIntent.setType("text/plain");
1887 // Set the intent to open in a new task.
1888 shareUrlIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1891 startActivity(Intent.createChooser(shareUrlIntent, getString(R.string.share_url)));
1893 // Consume the event.
1895 } else if (menuItemId == R.id.open_with_app) { // Open with app.
1896 // Open the URL with an outside app.
1897 openWithApp(currentWebView.getUrl());
1899 // Consume the event.
1901 } else if (menuItemId == R.id.open_with_browser) { // Open with browser.
1902 // Open the URL with an outside browser.
1903 openWithBrowser(currentWebView.getUrl());
1905 // Consume the event.
1907 } else if (menuItemId == R.id.add_or_edit_domain) { // Add or edit domain.
1908 // Check if domain settings currently exist.
1909 if (currentWebView.getDomainSettingsApplied()) { // Edit the current domain settings.
1910 // Reapply the domain settings on returning to `MainWebViewActivity`.
1911 reapplyDomainSettingsOnRestart = true;
1913 // Create an intent to launch the domains activity.
1914 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1916 // Add the extra information to the intent.
1917 domainsIntent.putExtra("load_domain", currentWebView.getDomainSettingsDatabaseId());
1918 domainsIntent.putExtra("close_on_back", true);
1919 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1920 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1922 // Get the current certificate.
1923 SslCertificate sslCertificate = currentWebView.getCertificate();
1925 // Check to see if the SSL certificate is populated.
1926 if (sslCertificate != null) {
1927 // Extract the certificate to strings.
1928 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1929 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1930 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1931 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1932 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1933 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1934 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1935 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1937 // Add the certificate to the intent.
1938 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1939 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1940 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1941 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1942 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1943 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1944 domainsIntent.putExtra("ssl_start_date", startDateLong);
1945 domainsIntent.putExtra("ssl_end_date", endDateLong);
1949 startActivity(domainsIntent);
1950 } else { // Add a new domain.
1951 // Apply the new domain settings on returning to `MainWebViewActivity`.
1952 reapplyDomainSettingsOnRestart = true;
1954 // Get the current domain
1955 Uri currentUri = Uri.parse(currentWebView.getUrl());
1956 String currentDomain = currentUri.getHost();
1958 // Create the domain and store the database ID.
1959 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1961 // Create an intent to launch the domains activity.
1962 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1964 // Add the extra information to the intent.
1965 domainsIntent.putExtra("load_domain", newDomainDatabaseId);
1966 domainsIntent.putExtra("close_on_back", true);
1967 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1968 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1970 // Get the current certificate.
1971 SslCertificate sslCertificate = currentWebView.getCertificate();
1973 // Check to see if the SSL certificate is populated.
1974 if (sslCertificate != null) {
1975 // Extract the certificate to strings.
1976 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1977 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1978 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1979 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1980 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1981 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1982 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1983 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1985 // Add the certificate to the intent.
1986 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1987 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1988 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1989 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1990 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1991 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1992 domainsIntent.putExtra("ssl_start_date", startDateLong);
1993 domainsIntent.putExtra("ssl_end_date", endDateLong);
1997 startActivity(domainsIntent);
2000 // Consume the event.
2002 } else { // There is no match with the options menu. Pass the event up to the parent method.
2003 // Don't consume the event.
2004 return super.onOptionsItemSelected(menuItem);
2008 // removeAllCookies is deprecated, but it is required for API < 21.
2010 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2011 // Get a handle for the shared preferences.
2012 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2014 // Get the menu item ID.
2015 int menuItemId = menuItem.getItemId();
2017 // Run the commands that correspond to the selected menu item.
2018 if (menuItemId == R.id.clear_and_exit) { // Clear and exit.
2019 // Clear and exit Privacy Browser.
2021 } else if (menuItemId == R.id.home) { // Home.
2022 // Load the homepage.
2023 loadUrl(currentWebView, sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
2024 } else if (menuItemId == R.id.back) { // Back.
2025 // Check if the WebView can go back.
2026 if (currentWebView.canGoBack()) {
2027 // Get the current web back forward list.
2028 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
2030 // Get the previous entry URL.
2031 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
2033 // Apply the domain settings.
2034 applyDomainSettings(currentWebView, previousUrl, false, false, false);
2036 // Load the previous website in the history.
2037 currentWebView.goBack();
2039 } else if (menuItemId == R.id.forward) { // Forward.
2040 // Check if the WebView can go forward.
2041 if (currentWebView.canGoForward()) {
2042 // Get the current web back forward list.
2043 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
2045 // Get the next entry URL.
2046 String nextUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() + 1).getUrl();
2048 // Apply the domain settings.
2049 applyDomainSettings(currentWebView, nextUrl, false, false, false);
2051 // Load the next website in the history.
2052 currentWebView.goForward();
2054 } else if (menuItemId == R.id.history) { // History.
2055 // Instantiate the URL history dialog.
2056 DialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(currentWebView.getWebViewFragmentId());
2058 // Show the URL history dialog.
2059 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2060 } else if (menuItemId == R.id.open) { // Open.
2061 // Instantiate the open file dialog.
2062 DialogFragment openDialogFragment = new OpenDialog();
2064 // Show the open file dialog.
2065 openDialogFragment.show(getSupportFragmentManager(), getString(R.string.open));
2066 } else if (menuItemId == R.id.requests) { // Requests.
2067 // Populate the resource requests.
2068 RequestsActivity.resourceRequests = currentWebView.getResourceRequests();
2070 // Create an intent to launch the Requests activity.
2071 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2073 // Add the block third-party requests status to the intent.
2074 requestsIntent.putExtra("block_all_third_party_requests", currentWebView.getBlockAllThirdPartyRequests());
2077 startActivity(requestsIntent);
2078 } else if (menuItemId == R.id.downloads) { // Downloads.
2079 // Try the default system download manager.
2081 // Launch the default system Download Manager.
2082 Intent defaultDownloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2084 // Launch as a new task so that the download manager and Privacy Browser show as separate windows in the recent tasks list.
2085 defaultDownloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2088 startActivity(defaultDownloadManagerIntent);
2089 } catch (Exception defaultDownloadManagerException) {
2090 // Try a generic file manager.
2092 // Create a generic file manager intent.
2093 Intent genericFileManagerIntent = new Intent(Intent.ACTION_VIEW);
2095 // Open the download directory.
2096 genericFileManagerIntent.setDataAndType(Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()), DocumentsContract.Document.MIME_TYPE_DIR);
2098 // Launch as a new task so that the file manager and Privacy Browser show as separate windows in the recent tasks list.
2099 genericFileManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2102 startActivity(genericFileManagerIntent);
2103 } catch (Exception genericFileManagerException) {
2104 // Try an alternate file manager.
2106 // Create an alternate file manager intent.
2107 Intent alternateFileManagerIntent = new Intent(Intent.ACTION_VIEW);
2109 // Open the download directory.
2110 alternateFileManagerIntent.setDataAndType(Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()), "resource/folder");
2112 // Launch as a new task so that the file manager and Privacy Browser show as separate windows in the recent tasks list.
2113 alternateFileManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2115 // Open the alternate file manager.
2116 startActivity(alternateFileManagerIntent);
2117 } catch (Exception alternateFileManagerException) {
2118 // Display a snackbar.
2119 Snackbar.make(currentWebView, R.string.no_file_manager_detected, Snackbar.LENGTH_INDEFINITE).show();
2123 } else if (menuItemId == R.id.domains) { // Domains.
2124 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2125 reapplyDomainSettingsOnRestart = true;
2127 // Launch the domains activity.
2128 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2130 // Add the extra information to the intent.
2131 domainsIntent.putExtra("current_url", currentWebView.getUrl());
2132 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
2134 // Get the current certificate.
2135 SslCertificate sslCertificate = currentWebView.getCertificate();
2137 // Check to see if the SSL certificate is populated.
2138 if (sslCertificate != null) {
2139 // Extract the certificate to strings.
2140 String issuedToCName = sslCertificate.getIssuedTo().getCName();
2141 String issuedToOName = sslCertificate.getIssuedTo().getOName();
2142 String issuedToUName = sslCertificate.getIssuedTo().getUName();
2143 String issuedByCName = sslCertificate.getIssuedBy().getCName();
2144 String issuedByOName = sslCertificate.getIssuedBy().getOName();
2145 String issuedByUName = sslCertificate.getIssuedBy().getUName();
2146 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
2147 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
2149 // Add the certificate to the intent.
2150 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
2151 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
2152 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
2153 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
2154 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
2155 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
2156 domainsIntent.putExtra("ssl_start_date", startDateLong);
2157 domainsIntent.putExtra("ssl_end_date", endDateLong);
2161 startActivity(domainsIntent);
2162 } else if (menuItemId == R.id.settings) { // Settings.
2163 // Set the flag to reapply app settings on restart when returning from Settings.
2164 reapplyAppSettingsOnRestart = true;
2166 // Set the flag to reapply the domain settings on restart when returning from Settings.
2167 reapplyDomainSettingsOnRestart = true;
2169 // Launch the settings activity.
2170 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2171 startActivity(settingsIntent);
2172 } else if (menuItemId == R.id.import_export) { // Import/Export.
2173 // Create an intent to launch the import/export activity.
2174 Intent importExportIntent = new Intent(this, ImportExportActivity.class);
2177 startActivity(importExportIntent);
2178 } else if (menuItemId == R.id.logcat) { // Logcat.
2179 // Create an intent to launch the logcat activity.
2180 Intent logcatIntent = new Intent(this, LogcatActivity.class);
2183 startActivity(logcatIntent);
2184 } else if (menuItemId == R.id.guide) { // Guide.
2185 // Create an intent to launch the guide activity.
2186 Intent guideIntent = new Intent(this, GuideActivity.class);
2189 startActivity(guideIntent);
2190 } else if (menuItemId == R.id.about) { // About
2191 // Create an intent to launch the about activity.
2192 Intent aboutIntent = new Intent(this, AboutActivity.class);
2194 // Create a string array for the blocklist versions.
2195 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],
2196 ultraList.get(0).get(0)[0], ultraPrivacy.get(0).get(0)[0]};
2198 // Add the blocklist versions to the intent.
2199 aboutIntent.putExtra(AboutActivity.BLOCKLIST_VERSIONS, blocklistVersions);
2202 startActivity(aboutIntent);
2205 // Close the navigation drawer.
2206 drawerLayout.closeDrawer(GravityCompat.START);
2211 public void onPostCreate(Bundle savedInstanceState) {
2212 // Run the default commands.
2213 super.onPostCreate(savedInstanceState);
2215 // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished. This creates the navigation drawer icon.
2216 actionBarDrawerToggle.syncState();
2220 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2221 // Get the hit test result.
2222 final WebView.HitTestResult hitTestResult = currentWebView.getHitTestResult();
2224 // Define the URL strings.
2225 final String imageUrl;
2226 final String linkUrl;
2228 // Get handles for the system managers.
2229 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2231 // Remove the lint errors below that the clipboard manager might be null.
2232 assert clipboardManager != null;
2234 // Process the link according to the type.
2235 switch (hitTestResult.getType()) {
2236 // `SRC_ANCHOR_TYPE` is a link.
2237 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2238 // Get the target URL.
2239 linkUrl = hitTestResult.getExtra();
2241 // Set the target URL as the title of the `ContextMenu`.
2242 menu.setHeaderTitle(linkUrl);
2244 // Add an Open in New Tab entry.
2245 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2246 // Load the link URL in a new tab and move to it.
2247 addNewTab(linkUrl, true);
2249 // Consume the event.
2253 // Add an Open in Background entry.
2254 menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
2255 // Load the link URL in a new tab but do not move to it.
2256 addNewTab(linkUrl, false);
2258 // Consume the event.
2262 // Add an Open with App entry.
2263 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2264 openWithApp(linkUrl);
2266 // Consume the event.
2270 // Add an Open with Browser entry.
2271 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2272 openWithBrowser(linkUrl);
2274 // Consume the event.
2278 // Add a Copy URL entry.
2279 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2280 // Save the link URL in a `ClipData`.
2281 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2283 // Set the `ClipData` as the clipboard's primary clip.
2284 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2286 // Consume the event.
2290 // Add a Save URL entry.
2291 menu.add(R.string.save_url).setOnMenuItemClickListener((MenuItem item) -> {
2292 // Check the download preference.
2293 if (downloadWithExternalApp) { // Download with an external app.
2294 downloadUrlWithExternalApp(linkUrl);
2295 } else { // Handle the download inside of Privacy Browser.
2296 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2297 new PrepareSaveDialog(this, this, getSupportFragmentManager(), currentWebView.getSettings().getUserAgentString(),
2298 currentWebView.getAcceptCookies()).execute(linkUrl);
2301 // Consume the event.
2305 // Add an empty Cancel entry, which by default closes the context menu.
2306 menu.add(R.string.cancel);
2309 // `IMAGE_TYPE` is an image.
2310 case WebView.HitTestResult.IMAGE_TYPE:
2311 // Get the image URL.
2312 imageUrl = hitTestResult.getExtra();
2314 // Remove the incorrect lint warning below that the image URL might be null.
2315 assert imageUrl != null;
2317 // Set the context menu title.
2318 if (imageUrl.startsWith("data:")) { // The image data is contained in within the URL, making it exceedingly long.
2319 // Truncate the image URL before making it the title.
2320 menu.setHeaderTitle(imageUrl.substring(0, 100));
2321 } else { // The image URL does not contain the full image data.
2322 // Set the image URL as the title of the context menu.
2323 menu.setHeaderTitle(imageUrl);
2326 // Add an Open in New Tab entry.
2327 menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2328 // Load the image in a new tab.
2329 addNewTab(imageUrl, true);
2331 // Consume the event.
2335 // Add an Open with App entry.
2336 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2337 // Open the image URL with an external app.
2338 openWithApp(imageUrl);
2340 // Consume the event.
2344 // Add an Open with Browser entry.
2345 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2346 // Open the image URL with an external browser.
2347 openWithBrowser(imageUrl);
2349 // Consume the event.
2353 // Add a View Image entry.
2354 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2355 // Load the image in the current tab.
2356 loadUrl(currentWebView, imageUrl);
2358 // Consume the event.
2362 // Add a Save Image entry.
2363 menu.add(R.string.save_image).setOnMenuItemClickListener((MenuItem item) -> {
2364 // Check the download preference.
2365 if (downloadWithExternalApp) { // Download with an external app.
2366 downloadUrlWithExternalApp(imageUrl);
2367 } else { // Handle the download inside of Privacy Browser.
2368 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2369 new PrepareSaveDialog(this, this, getSupportFragmentManager(), currentWebView.getSettings().getUserAgentString(),
2370 currentWebView.getAcceptCookies()).execute(imageUrl);
2373 // Consume the event.
2377 // Add a Copy URL entry.
2378 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2379 // Save the image URL in a clip data.
2380 ClipData imageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2382 // Set the clip data as the clipboard's primary clip.
2383 clipboardManager.setPrimaryClip(imageTypeClipData);
2385 // Consume the event.
2389 // Add an empty Cancel entry, which by default closes the context menu.
2390 menu.add(R.string.cancel);
2393 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2394 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2395 // Get the image URL.
2396 imageUrl = hitTestResult.getExtra();
2398 // Instantiate a handler.
2399 Handler handler = new Handler();
2401 // Get a message from the handler.
2402 Message message = handler.obtainMessage();
2404 // Request the image details from the last touched node be returned in the message.
2405 currentWebView.requestFocusNodeHref(message);
2407 // Get the link URL from the message data.
2408 linkUrl = message.getData().getString("url");
2410 // Set the link URL as the title of the context menu.
2411 menu.setHeaderTitle(linkUrl);
2413 // Add an Open in New Tab entry.
2414 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2415 // Load the link URL in a new tab and move to it.
2416 addNewTab(linkUrl, true);
2418 // Consume the event.
2422 // Add an Open in Background entry.
2423 menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
2424 // Lod the link URL in a new tab but do not move to it.
2425 addNewTab(linkUrl, false);
2427 // Consume the event.
2431 // Add an Open Image in New Tab entry.
2432 menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2433 // Load the image in a new tab and move to it.
2434 addNewTab(imageUrl, true);
2436 // Consume the event.
2440 // Add an Open with App entry.
2441 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2442 // Open the link URL with an external app.
2443 openWithApp(linkUrl);
2445 // Consume the event.
2449 // Add an Open with Browser entry.
2450 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2451 // Open the link URL with an external browser.
2452 openWithBrowser(linkUrl);
2454 // Consume the event.
2458 // Add a View Image entry.
2459 menu.add(R.string.view_image).setOnMenuItemClickListener((MenuItem item) -> {
2460 // View the image in the current tab.
2461 loadUrl(currentWebView, imageUrl);
2463 // Consume the event.
2467 // Add a Save Image entry.
2468 menu.add(R.string.save_image).setOnMenuItemClickListener((MenuItem item) -> {
2469 // Check the download preference.
2470 if (downloadWithExternalApp) { // Download with an external app.
2471 downloadUrlWithExternalApp(imageUrl);
2472 } else { // Handle the download inside of Privacy Browser.
2473 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2474 new PrepareSaveDialog(this, this, getSupportFragmentManager(), currentWebView.getSettings().getUserAgentString(),
2475 currentWebView.getAcceptCookies()).execute(imageUrl);
2478 // Consume the event.
2482 // Add a Copy URL entry.
2483 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2484 // Save the link URL in a clip data.
2485 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2487 // Set the clip data as the clipboard's primary clip.
2488 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2490 // Consume the event.
2494 // Add a Save URL entry.
2495 menu.add(R.string.save_url).setOnMenuItemClickListener((MenuItem item) -> {
2496 // Check the download preference.
2497 if (downloadWithExternalApp) { // Download with an external app.
2498 downloadUrlWithExternalApp(linkUrl);
2499 } else { // Handle the download inside of Privacy Browser.
2500 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2501 new PrepareSaveDialog(this, this, getSupportFragmentManager(), currentWebView.getSettings().getUserAgentString(),
2502 currentWebView.getAcceptCookies()).execute(linkUrl);
2505 // Consume the event.
2509 // Add an empty Cancel entry, which by default closes the context menu.
2510 menu.add(R.string.cancel);
2513 case WebView.HitTestResult.EMAIL_TYPE:
2514 // Get the target URL.
2515 linkUrl = hitTestResult.getExtra();
2517 // Set the target URL as the title of the `ContextMenu`.
2518 menu.setHeaderTitle(linkUrl);
2520 // Add a Write Email entry.
2521 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2522 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2523 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2525 // Parse the url and set it as the data for the `Intent`.
2526 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2528 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2529 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2533 startActivity(emailIntent);
2534 } catch (ActivityNotFoundException exception) {
2535 // Display a snackbar.
2536 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
2539 // Consume the event.
2543 // Add a Copy Email Address entry.
2544 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2545 // Save the email address in a `ClipData`.
2546 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2548 // Set the `ClipData` as the clipboard's primary clip.
2549 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2551 // Consume the event.
2555 // Add an empty Cancel entry, which by default closes the context menu.
2556 menu.add(R.string.cancel);
2562 public void onCreateBookmark(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2563 // Get a handle for the bookmarks list view.
2564 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2567 Dialog dialog = dialogFragment.getDialog();
2569 // Remove the incorrect lint warning below that the dialog might be null.
2570 assert dialog != null;
2572 // Get the views from the dialog fragment.
2573 EditText createBookmarkNameEditText = dialog.findViewById(R.id.create_bookmark_name_edittext);
2574 EditText createBookmarkUrlEditText = dialog.findViewById(R.id.create_bookmark_url_edittext);
2576 // Extract the strings from the edit texts.
2577 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2578 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2580 // Create a favorite icon byte array output stream.
2581 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2583 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2584 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2586 // Convert the favorite icon byte array stream to a byte array.
2587 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2589 // Display the new bookmark below the current items in the (0 indexed) list.
2590 int newBookmarkDisplayOrder = bookmarksListView.getCount();
2592 // Create the bookmark.
2593 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2595 // Update the bookmarks cursor with the current contents of this folder.
2596 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2598 // Update the list view.
2599 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2601 // Scroll to the new bookmark.
2602 bookmarksListView.setSelection(newBookmarkDisplayOrder);
2606 public void onCreateBookmarkFolder(DialogFragment dialogFragment, @NonNull Bitmap favoriteIconBitmap) {
2607 // Get a handle for the bookmarks list view.
2608 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2611 Dialog dialog = dialogFragment.getDialog();
2613 // Remove the incorrect lint warning below that the dialog might be null.
2614 assert dialog != null;
2616 // Get handles for the views in the dialog fragment.
2617 EditText folderNameEditText = dialog.findViewById(R.id.folder_name_edittext);
2618 RadioButton defaultIconRadioButton = dialog.findViewById(R.id.default_icon_radiobutton);
2619 ImageView defaultIconImageView = dialog.findViewById(R.id.default_icon_imageview);
2621 // Get new folder name string.
2622 String folderNameString = folderNameEditText.getText().toString();
2624 // Create a folder icon bitmap.
2625 Bitmap folderIconBitmap;
2627 // Set the folder icon bitmap according to the dialog.
2628 if (defaultIconRadioButton.isChecked()) { // Use the default folder icon.
2629 // Get the default folder icon drawable.
2630 Drawable folderIconDrawable = defaultIconImageView.getDrawable();
2632 // Convert the folder icon drawable to a bitmap drawable.
2633 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2635 // Convert the folder icon bitmap drawable to a bitmap.
2636 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2637 } else { // Use the WebView favorite icon.
2638 // Copy the favorite icon bitmap to the folder icon bitmap.
2639 folderIconBitmap = favoriteIconBitmap;
2642 // Create a folder icon byte array output stream.
2643 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2645 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2646 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2648 // Convert the folder icon byte array stream to a byte array.
2649 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2651 // Move all the bookmarks down one in the display order.
2652 for (int i = 0; i < bookmarksListView.getCount(); i++) {
2653 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2654 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2657 // Create the folder, which will be placed at the top of the `ListView`.
2658 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2660 // Update the bookmarks cursor with the current contents of this folder.
2661 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2663 // Update the `ListView`.
2664 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2666 // Scroll to the new folder.
2667 bookmarksListView.setSelection(0);
2671 public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId, @NonNull Bitmap favoriteIconBitmap) {
2672 // Remove the incorrect lint warning below that the dialog fragment might be null.
2673 assert dialogFragment != null;
2676 Dialog dialog = dialogFragment.getDialog();
2678 // Remove the incorrect lint warning below that the dialog might be null.
2679 assert dialog != null;
2681 // Get handles for the views from the dialog.
2682 RadioButton currentFolderIconRadioButton = dialog.findViewById(R.id.current_icon_radiobutton);
2683 RadioButton defaultFolderIconRadioButton = dialog.findViewById(R.id.default_icon_radiobutton);
2684 ImageView defaultFolderIconImageView = dialog.findViewById(R.id.default_icon_imageview);
2685 EditText editFolderNameEditText = dialog.findViewById(R.id.folder_name_edittext);
2687 // Get the new folder name.
2688 String newFolderNameString = editFolderNameEditText.getText().toString();
2690 // Check if the favorite icon has changed.
2691 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
2692 // Update the name in the database.
2693 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2694 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
2695 // Create the new folder icon Bitmap.
2696 Bitmap folderIconBitmap;
2698 // Populate the new folder icon bitmap.
2699 if (defaultFolderIconRadioButton.isChecked()) {
2700 // Get the default folder icon drawable.
2701 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2703 // Convert the folder icon drawable to a bitmap drawable.
2704 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2706 // Convert the folder icon bitmap drawable to a bitmap.
2707 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2708 } else { // Use the `WebView` favorite icon.
2709 // Copy the favorite icon bitmap to the folder icon bitmap.
2710 folderIconBitmap = favoriteIconBitmap;
2713 // Create a folder icon byte array output stream.
2714 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2716 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2717 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2719 // Convert the folder icon byte array stream to a byte array.
2720 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2722 // Update the folder icon in the database.
2723 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, newFolderIconByteArray);
2724 } else { // The folder icon and the name have changed.
2725 // Get the new folder icon bitmap.
2726 Bitmap folderIconBitmap;
2727 if (defaultFolderIconRadioButton.isChecked()) {
2728 // Get the default folder icon drawable.
2729 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2731 // Convert the folder icon drawable to a bitmap drawable.
2732 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2734 // Convert the folder icon bitmap drawable to a bitmap.
2735 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2736 } else { // Use the `WebView` favorite icon.
2737 // Copy the favorite icon bitmap to the folder icon bitmap.
2738 folderIconBitmap = favoriteIconBitmap;
2741 // Create a folder icon byte array output stream.
2742 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2744 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2745 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2747 // Convert the folder icon byte array stream to a byte array.
2748 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2750 // Update the folder name and icon in the database.
2751 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, newFolderIconByteArray);
2754 // Update the bookmarks cursor with the current contents of this folder.
2755 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2757 // Update the `ListView`.
2758 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2761 // Override `onBackPressed()` to handle the navigation drawer and and the WebViews.
2763 public void onBackPressed() {
2764 // Check the different options for processing `back`.
2765 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
2766 // Close the navigation drawer.
2767 drawerLayout.closeDrawer(GravityCompat.START);
2768 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
2769 // close the bookmarks drawer.
2770 drawerLayout.closeDrawer(GravityCompat.END);
2771 } else if (displayingFullScreenVideo) { // A full screen video is shown.
2772 // Exit the full screen video.
2773 exitFullScreenVideo();
2774 } else if (currentWebView.canGoBack()) { // There is at least one item in the current WebView history.
2775 // Get the current web back forward list.
2776 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
2778 // Get the previous entry URL.
2779 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
2781 // Apply the domain settings.
2782 applyDomainSettings(currentWebView, previousUrl, false, false, false);
2785 currentWebView.goBack();
2786 } else if (tabLayout.getTabCount() > 1) { // There are at least two tabs.
2787 // Close the current tab.
2789 } else { // There isn't anything to do in Privacy Browser.
2790 // Close Privacy Browser. `finishAndRemoveTask()` also removes Privacy Browser from the recent app list.
2791 finishAndRemoveTask();
2793 // Manually kill Privacy Browser. Otherwise, it is glitchy when restarted.
2798 // Process the results of a file browse.
2800 public void onActivityResult(int requestCode, int resultCode, Intent returnedIntent) {
2801 // Run the default commands.
2802 super.onActivityResult(requestCode, resultCode, returnedIntent);
2804 // Run the commands that correlate to the specified request code.
2805 switch (requestCode) {
2806 case BROWSE_FILE_UPLOAD_REQUEST_CODE:
2807 // Pass the file to the WebView.
2808 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, returnedIntent));
2811 case BROWSE_OPEN_REQUEST_CODE:
2812 // Don't do anything if the user pressed back from the file picker.
2813 if (resultCode == Activity.RESULT_OK) {
2814 // Get a handle for the open dialog fragment.
2815 DialogFragment openDialogFragment = (DialogFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.open));
2817 // Only update the file name if the dialog still exists.
2818 if (openDialogFragment != null) {
2819 // Get a handle for the open dialog.
2820 Dialog openDialog = openDialogFragment.getDialog();
2822 // Remove the incorrect lint warning below that the dialog might be null.
2823 assert openDialog != null;
2825 // Get a handle for the file name edit text.
2826 EditText fileNameEditText = openDialog.findViewById(R.id.file_name_edittext);
2828 // Get the file name URI from the intent.
2829 Uri fileNameUri = returnedIntent.getData();
2831 // Get the file name string from the URI.
2832 String fileNameString = fileNameUri.toString();
2834 // Set the file name text.
2835 fileNameEditText.setText(fileNameString);
2837 // Move the cursor to the end of the file name edit text.
2838 fileNameEditText.setSelection(fileNameString.length());
2845 private void loadUrlFromTextBox() {
2846 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
2847 String unformattedUrlString = urlEditText.getText().toString().trim();
2849 // Initialize the formatted URL string.
2852 // Check to see if the unformatted URL string is a valid URL. Otherwise, convert it into a search.
2853 if (unformattedUrlString.startsWith("content://")) { // This is a Content URL.
2854 // Load the entire content URL.
2855 url = unformattedUrlString;
2856 } else if (Patterns.WEB_URL.matcher(unformattedUrlString).matches() || unformattedUrlString.startsWith("http://") || unformattedUrlString.startsWith("https://") ||
2857 unformattedUrlString.startsWith("file://")) { // This is a standard URL.
2858 // Add `https://` at the beginning if there is no protocol. Otherwise the app will segfault.
2859 if (!unformattedUrlString.startsWith("http") && !unformattedUrlString.startsWith("file://")) {
2860 unformattedUrlString = "https://" + unformattedUrlString;
2863 // Initialize the unformatted URL.
2864 URL unformattedUrl = null;
2866 // 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.
2868 unformattedUrl = new URL(unformattedUrlString);
2869 } catch (MalformedURLException e) {
2870 e.printStackTrace();
2873 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2874 String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2875 String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2876 String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2877 String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2878 String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2881 Uri.Builder uri = new Uri.Builder();
2882 uri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2884 // Decode the URI as a UTF-8 string in.
2886 url = URLDecoder.decode(uri.build().toString(), "UTF-8");
2887 } catch (UnsupportedEncodingException exception) {
2888 // Do nothing. The formatted URL string will remain blank.
2890 } else if (!unformattedUrlString.isEmpty()){ // This is not a URL, but rather a search string.
2891 // Create an encoded URL String.
2892 String encodedUrlString;
2894 // Sanitize the search input.
2896 encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2897 } catch (UnsupportedEncodingException exception) {
2898 encodedUrlString = "";
2901 // Add the base search URL.
2902 url = searchURL + encodedUrlString;
2905 // 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.
2906 urlEditText.clearFocus();
2909 loadUrl(currentWebView, url);
2912 private void loadUrl(NestedScrollWebView nestedScrollWebView, String url) {
2913 // Sanitize the URL.
2914 url = sanitizeUrl(url);
2916 // Apply the domain settings and load the URL.
2917 applyDomainSettings(nestedScrollWebView, url, true, false, true);
2920 public void findPreviousOnPage(View view) {
2921 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
2922 currentWebView.findNext(false);
2925 public void findNextOnPage(View view) {
2926 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2927 currentWebView.findNext(true);
2930 public void closeFindOnPage(View view) {
2931 // Get a handle for the views.
2932 Toolbar toolbar = findViewById(R.id.toolbar);
2933 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
2934 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
2936 // Delete the contents of `find_on_page_edittext`.
2937 findOnPageEditText.setText(null);
2939 // Clear the highlighted phrases if the WebView is not null.
2940 if (currentWebView != null) {
2941 currentWebView.clearMatches();
2944 // Hide the find on page linear layout.
2945 findOnPageLinearLayout.setVisibility(View.GONE);
2947 // Show the toolbar.
2948 toolbar.setVisibility(View.VISIBLE);
2950 // Get a handle for the input method manager.
2951 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
2953 // Remove the lint warning below that the input method manager might be null.
2954 assert inputMethodManager != null;
2956 // Hide the keyboard.
2957 inputMethodManager.hideSoftInputFromWindow(toolbar.getWindowToken(), 0);
2961 public void onApplyNewFontSize(DialogFragment dialogFragment) {
2962 // Remove the incorrect lint warning below that the dialog fragment might be null.
2963 assert dialogFragment != null;
2966 Dialog dialog = dialogFragment.getDialog();
2968 // Remove the incorrect lint warning below tha the dialog might be null.
2969 assert dialog != null;
2971 // Get a handle for the font size edit text.
2972 EditText fontSizeEditText = dialog.findViewById(R.id.font_size_edittext);
2974 // Initialize the new font size variable with the current font size.
2975 int newFontSize = currentWebView.getSettings().getTextZoom();
2977 // Get the font size from the edit text.
2979 newFontSize = Integer.parseInt(fontSizeEditText.getText().toString());
2980 } catch (Exception exception) {
2981 // If the edit text does not contain a valid font size do nothing.
2984 // Apply the new font size.
2985 currentWebView.getSettings().setTextZoom(newFontSize);
2989 public void onOpen(DialogFragment dialogFragment) {
2991 Dialog dialog = dialogFragment.getDialog();
2993 // Remove the incorrect lint warning below that the dialog might be null.
2994 assert dialog != null;
2996 // Get handles for the views.
2997 EditText fileNameEditText = dialog.findViewById(R.id.file_name_edittext);
2998 CheckBox mhtCheckBox = dialog.findViewById(R.id.mht_checkbox);
3000 // Get the file path string.
3001 String openFilePath = fileNameEditText.getText().toString();
3003 // Apply the domain settings. This resets the favorite icon and removes any domain settings.
3004 applyDomainSettings(currentWebView, openFilePath, true, false, false);
3006 // Open the file according to the type.
3007 if (mhtCheckBox.isChecked()) { // Force opening of an MHT file.
3009 // Get the MHT file input stream.
3010 InputStream mhtFileInputStream = getContentResolver().openInputStream(Uri.parse(openFilePath));
3012 // Create a temporary MHT file.
3013 File temporaryMhtFile = File.createTempFile("temporary_mht_file", ".mht", getCacheDir());
3015 // Get a file output stream for the temporary MHT file.
3016 FileOutputStream temporaryMhtFileOutputStream = new FileOutputStream(temporaryMhtFile);
3018 // Create a transfer byte array.
3019 byte[] transferByteArray = new byte[1024];
3021 // Create an integer to track the number of bytes read.
3024 // Copy the temporary MHT file input stream to the MHT output stream.
3025 while ((bytesRead = mhtFileInputStream.read(transferByteArray)) > 0) {
3026 temporaryMhtFileOutputStream.write(transferByteArray, 0, bytesRead);
3029 // Flush the temporary MHT file output stream.
3030 temporaryMhtFileOutputStream.flush();
3032 // Close the streams.
3033 temporaryMhtFileOutputStream.close();
3034 mhtFileInputStream.close();
3036 // Load the temporary MHT file.
3037 currentWebView.loadUrl(temporaryMhtFile.toString());
3038 } catch (Exception exception) {
3039 // Display a snackbar.
3040 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
3042 } else { // Let the WebView handle opening of the file.
3044 currentWebView.loadUrl(openFilePath);
3048 private void downloadUrlWithExternalApp(String url) {
3049 // Create a download intent. Not specifying the action type will display the maximum number of options.
3050 Intent downloadIntent = new Intent();
3052 // Set the URI and the mime type.
3053 downloadIntent.setDataAndType(Uri.parse(url), "text/html");
3055 // Flag the intent to open in a new task.
3056 downloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3058 // Show the chooser.
3059 startActivity(Intent.createChooser(downloadIntent, getString(R.string.download_with_external_app)));
3062 public void onSaveUrl(@NonNull String originalUrlString, @NonNull String fileNameString, @NonNull DialogFragment dialogFragment) {
3063 // Store the URL. This will be used in the save URL activity result launcher.
3064 if (originalUrlString.startsWith("data:")) {
3065 // Save the original URL.
3066 saveUrlString = originalUrlString;
3069 Dialog dialog = dialogFragment.getDialog();
3071 // Remove the incorrect lint warning below that the dialog might be null.
3072 assert dialog != null;
3074 // Get a handle for the dialog URL edit text.
3075 EditText dialogUrlEditText = dialog.findViewById(R.id.url_edittext);
3077 // Get the URL from the edit text, which may have been modified.
3078 saveUrlString = dialogUrlEditText.getText().toString();
3081 // Open the file picker.
3082 saveUrlActivityResultLauncher.launch(fileNameString);
3085 // Remove the warning that `OnTouchListener()` needs to override `performClick()`, as the only purpose of setting the `OnTouchListener()` is to make it do nothing.
3086 @SuppressLint("ClickableViewAccessibility")
3087 private void initializeApp() {
3088 // Get a handle for the input method.
3089 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
3091 // Remove the lint warning below that the input method manager might be null.
3092 assert inputMethodManager != null;
3094 // Initialize the gray foreground color spans for highlighting the URLs.
3095 initialGrayColorSpan = new ForegroundColorSpan(getColor(R.color.gray_500));
3096 finalGrayColorSpan = new ForegroundColorSpan(getColor(R.color.gray_500));
3098 // Get the current theme status.
3099 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
3101 // Set the red color span according to the theme.
3102 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
3103 redColorSpan = new ForegroundColorSpan(getColor(R.color.red_a700));
3105 redColorSpan = new ForegroundColorSpan(getColor(R.color.red_900));
3108 // Remove the formatting from the URL edit text when the user is editing the text.
3109 urlEditText.setOnFocusChangeListener((View v, boolean hasFocus) -> {
3110 if (hasFocus) { // The user is editing the URL text box.
3111 // Remove the highlighting.
3112 urlEditText.getText().removeSpan(redColorSpan);
3113 urlEditText.getText().removeSpan(initialGrayColorSpan);
3114 urlEditText.getText().removeSpan(finalGrayColorSpan);
3115 } else { // The user has stopped editing the URL text box.
3116 // Move to the beginning of the string.
3117 urlEditText.setSelection(0);
3119 // Reapply the highlighting.
3124 // Set the go button on the keyboard to load the URL in `urlTextBox`.
3125 urlEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
3126 // If the event is a key-down event on the `enter` button, load the URL.
3127 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
3128 // Load the URL into the mainWebView and consume the event.
3129 loadUrlFromTextBox();
3131 // If the enter key was pressed, consume the event.
3134 // If any other key was pressed, do not consume the event.
3139 // Create an Orbot status broadcast receiver.
3140 orbotStatusBroadcastReceiver = new BroadcastReceiver() {
3142 public void onReceive(Context context, Intent intent) {
3143 // Store the content of the status message in `orbotStatus`.
3144 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
3146 // If Privacy Browser is waiting on the proxy, load the website now that Orbot is connected.
3147 if ((orbotStatus != null) && orbotStatus.equals(ProxyHelper.ORBOT_STATUS_ON) && waitingForProxy) {
3148 // Reset the waiting for proxy status.
3149 waitingForProxy = false;
3151 // Get a list of the current fragments.
3152 List<Fragment> fragmentList = getSupportFragmentManager().getFragments();
3154 // Check each fragment to see if it is a waiting for proxy dialog. Sometimes more than one is displayed.
3155 for (int i = 0; i < fragmentList.size(); i++) {
3156 // Get the fragment tag.
3157 String fragmentTag = fragmentList.get(i).getTag();
3159 // Check to see if it is the waiting for proxy dialog.
3160 if ((fragmentTag!= null) && fragmentTag.equals(getString(R.string.waiting_for_proxy_dialog))) {
3161 // Dismiss the waiting for proxy dialog.
3162 ((DialogFragment) fragmentList.get(i)).dismiss();
3166 // Reload existing URLs and load any URLs that are waiting for the proxy.
3167 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3168 // Get the WebView tab fragment.
3169 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3171 // Get the fragment view.
3172 View fragmentView = webViewTabFragment.getView();
3174 // Only process the WebViews if they exist.
3175 if (fragmentView != null) {
3176 // Get the nested scroll WebView from the tab fragment.
3177 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3179 // Get the waiting for proxy URL string.
3180 String waitingForProxyUrlString = nestedScrollWebView.getWaitingForProxyUrlString();
3182 // Load the pending URL if it exists.
3183 if (!waitingForProxyUrlString.isEmpty()) { // A URL is waiting to be loaded.
3185 loadUrl(nestedScrollWebView, waitingForProxyUrlString);
3187 // Reset the waiting for proxy URL string.
3188 nestedScrollWebView.setWaitingForProxyUrlString("");
3189 } else { // No URL is waiting to be loaded.
3190 // Reload the existing URL.
3191 nestedScrollWebView.reload();
3199 // Register the Orbot status broadcast receiver on `this` context.
3200 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
3202 // Get handles for views that need to be modified.
3203 LinearLayout bookmarksHeaderLinearLayout = findViewById(R.id.bookmarks_header_linearlayout);
3204 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
3205 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
3206 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
3207 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
3208 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
3210 // Update the web view pager every time a tab is modified.
3211 webViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
3213 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
3218 public void onPageSelected(int position) {
3219 // Close the find on page bar if it is open.
3220 closeFindOnPage(null);
3222 // Set the current WebView.
3223 setCurrentWebView(position);
3225 // 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.
3226 if (tabLayout.getSelectedTabPosition() != position) {
3227 // Wait until the new tab has been created.
3228 tabLayout.post(() -> {
3229 // Get a handle for the tab.
3230 TabLayout.Tab tab = tabLayout.getTabAt(position);
3232 // Assert that the tab is not null.
3242 public void onPageScrollStateChanged(int state) {
3247 // Display the View SSL Certificate dialog when the currently selected tab is reselected.
3248 tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
3250 public void onTabSelected(TabLayout.Tab tab) {
3251 // Select the same page in the view pager.
3252 webViewPager.setCurrentItem(tab.getPosition());
3256 public void onTabUnselected(TabLayout.Tab tab) {
3261 public void onTabReselected(TabLayout.Tab tab) {
3262 // Instantiate the View SSL Certificate dialog.
3263 DialogFragment viewSslCertificateDialogFragment = ViewSslCertificateDialog.displayDialog(currentWebView.getWebViewFragmentId(), currentWebView.getFavoriteOrDefaultIcon());
3265 // Display the View SSL Certificate dialog.
3266 viewSslCertificateDialogFragment.show(getSupportFragmentManager(), getString(R.string.view_ssl_certificate));
3270 // Set a touch listener on the bookmarks header linear layout so that touches don't pass through to the button underneath.
3271 bookmarksHeaderLinearLayout.setOnTouchListener((view, motionEvent) -> {
3272 // Consume the touch.
3276 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
3277 launchBookmarksActivityFab.setOnClickListener(v -> {
3278 // Get a copy of the favorite icon bitmap.
3279 Bitmap favoriteIconBitmap = currentWebView.getFavoriteOrDefaultIcon();
3281 // Create a favorite icon byte array output stream.
3282 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3284 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
3285 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
3287 // Convert the favorite icon byte array stream to a byte array.
3288 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
3290 // Create an intent to launch the bookmarks activity.
3291 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
3293 // Add the extra information to the intent.
3294 bookmarksIntent.putExtra("current_url", currentWebView.getUrl());
3295 bookmarksIntent.putExtra("current_title", currentWebView.getTitle());
3296 bookmarksIntent.putExtra("current_folder", currentBookmarksFolder);
3297 bookmarksIntent.putExtra("favorite_icon_byte_array", favoriteIconByteArray);
3300 startActivity(bookmarksIntent);
3303 // Set the create new bookmark folder FAB to display an alert dialog.
3304 createBookmarkFolderFab.setOnClickListener(v -> {
3305 // Create a create bookmark folder dialog.
3306 DialogFragment createBookmarkFolderDialog = CreateBookmarkFolderDialog.createBookmarkFolder(currentWebView.getFavoriteOrDefaultIcon());
3308 // Show the create bookmark folder dialog.
3309 createBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.create_folder));
3312 // Set the create new bookmark FAB to display an alert dialog.
3313 createBookmarkFab.setOnClickListener(view -> {
3314 // Instantiate the create bookmark dialog.
3315 DialogFragment createBookmarkDialog = CreateBookmarkDialog.createBookmark(currentWebView.getUrl(), currentWebView.getTitle(), currentWebView.getFavoriteOrDefaultIcon());
3317 // Display the create bookmark dialog.
3318 createBookmarkDialog.show(getSupportFragmentManager(), getString(R.string.create_bookmark));
3321 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
3322 findOnPageEditText.addTextChangedListener(new TextWatcher() {
3324 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
3329 public void onTextChanged(CharSequence s, int start, int before, int count) {
3334 public void afterTextChanged(Editable s) {
3335 // 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.
3336 if (currentWebView != null) {
3337 currentWebView.findAllAsync(findOnPageEditText.getText().toString());
3342 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
3343 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
3344 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
3345 // Hide the soft keyboard.
3346 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
3348 // Consume the event.
3350 } else { // A different key was pressed.
3351 // Do not consume the event.
3356 // Implement swipe to refresh.
3357 swipeRefreshLayout.setOnRefreshListener(() -> {
3358 // Reload the website.
3359 currentWebView.reload();
3362 // Store the default progress view offsets for use later in `initializeWebView()`.
3363 defaultProgressViewStartOffset = swipeRefreshLayout.getProgressViewStartOffset();
3364 defaultProgressViewEndOffset = swipeRefreshLayout.getProgressViewEndOffset();
3366 // Set the refresh color scheme according to the theme.
3367 swipeRefreshLayout.setColorSchemeResources(R.color.blue_text);
3369 // Initialize a color background typed value.
3370 TypedValue colorBackgroundTypedValue = new TypedValue();
3372 // Get the color background from the theme.
3373 getTheme().resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true);
3375 // Get the color background int from the typed value.
3376 int colorBackgroundInt = colorBackgroundTypedValue.data;
3378 // Set the swipe refresh background color.
3379 swipeRefreshLayout.setProgressBackgroundColorSchemeColor(colorBackgroundInt);
3381 // The drawer titles identify the drawer layouts in accessibility mode.
3382 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
3383 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
3385 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
3386 currentBookmarksFolder = "";
3388 // Load the home folder, which is `""` in the database.
3389 loadBookmarksFolder();
3391 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
3392 // Convert the id from long to int to match the format of the bookmarks database.
3393 int databaseId = (int) id;
3395 // Get the bookmark cursor for this ID.
3396 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseId);
3398 // Move the bookmark cursor to the first row.
3399 bookmarkCursor.moveToFirst();
3401 // Act upon the bookmark according to the type.
3402 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
3403 // Store the new folder name in `currentBookmarksFolder`.
3404 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME));
3406 // Load the new folder.
3407 loadBookmarksFolder();
3408 } else { // The selected bookmark is not a folder.
3409 // Load the bookmark URL.
3410 loadUrl(currentWebView, bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_URL)));
3412 // Close the bookmarks drawer.
3413 drawerLayout.closeDrawer(GravityCompat.END);
3416 // Close the `Cursor`.
3417 bookmarkCursor.close();
3420 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
3421 // Convert the database ID from `long` to `int`.
3422 int databaseId = (int) id;
3424 // Find out if the selected bookmark is a folder.
3425 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
3427 // Check to see if the bookmark is a folder.
3428 if (isFolder) { // The bookmark is a folder.
3429 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
3430 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME));
3432 // Instantiate the edit folder bookmark dialog.
3433 DialogFragment editBookmarkFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId, currentWebView.getFavoriteOrDefaultIcon());
3435 // Show the edit folder bookmark dialog.
3436 editBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.edit_folder));
3437 } else { // The bookmark is not a folder.
3438 // Get the bookmark cursor for this ID.
3439 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseId);
3441 // Move the bookmark cursor to the first row.
3442 bookmarkCursor.moveToFirst();
3444 // Load the bookmark in a new tab but do not switch to the tab or close the drawer.
3445 addNewTab(bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_URL)), false);
3447 // Display a snackbar.
3448 Snackbar.make(drawerLayout, R.string.bookmark_opened_in_background, Snackbar.LENGTH_SHORT).show();
3451 // Consume the event.
3455 // The drawer listener is used to update the navigation menu.
3456 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
3458 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
3462 public void onDrawerOpened(@NonNull View drawerView) {
3466 public void onDrawerClosed(@NonNull View drawerView) {
3467 // Reset the drawer icon when the drawer is closed. Otherwise, it is an arrow if the drawer is open when the app is restarted.
3468 actionBarDrawerToggle.syncState();
3472 public void onDrawerStateChanged(int newState) {
3473 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // A drawer is opening or closing.
3474 // Update the navigation menu items if the WebView is not null.
3475 if (currentWebView != null) {
3476 navigationBackMenuItem.setEnabled(currentWebView.canGoBack());
3477 navigationForwardMenuItem.setEnabled(currentWebView.canGoForward());
3478 navigationHistoryMenuItem.setEnabled((currentWebView.canGoBack() || currentWebView.canGoForward()));
3479 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
3481 // Hide the keyboard (if displayed).
3482 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
3485 // 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.
3486 urlEditText.clearFocus();
3488 // 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.
3489 if (currentWebView != null) {
3490 // Clearing the focus from the WebView removes any text selection markers and context menus, which otherwise draw above the open drawers.
3491 currentWebView.clearFocus();
3497 // Replace the header that `WebView` creates for `X-Requested-With` with a null value. The default value is the application ID (com.stoutner.privacybrowser.standard).
3498 customHeaders.put("X-Requested-With", "");
3500 // Inflate a bare WebView to get the default user agent. It is not used to render content on the screen.
3501 @SuppressLint("InflateParams") View webViewLayout = getLayoutInflater().inflate(R.layout.bare_webview, null, false);
3503 // Get a handle for the WebView.
3504 WebView bareWebView = webViewLayout.findViewById(R.id.bare_webview);
3506 // Store the default user agent.
3507 webViewDefaultUserAgent = bareWebView.getSettings().getUserAgentString();
3509 // Destroy the bare WebView.
3510 bareWebView.destroy();
3513 private void applyAppSettings() {
3514 // Get a handle for the shared preferences.
3515 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3517 // Store the values from the shared preferences in variables.
3518 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3519 sanitizeTrackingQueries = sharedPreferences.getBoolean(getString(R.string.tracking_queries_key), true);
3520 sanitizeAmpRedirects = sharedPreferences.getBoolean(getString(R.string.amp_redirects_key), true);
3521 proxyMode = sharedPreferences.getString("proxy", getString(R.string.proxy_default_value));
3522 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3523 downloadWithExternalApp = sharedPreferences.getBoolean(getString(R.string.download_with_external_app_key), false);
3524 hideAppBar = sharedPreferences.getBoolean("hide_app_bar", true);
3525 scrollAppBar = sharedPreferences.getBoolean(getString(R.string.scroll_app_bar_key), true);
3527 // Apply the saved proxy mode if the app has been restarted.
3528 if (savedProxyMode != null) {
3529 // Apply the saved proxy mode.
3530 proxyMode = savedProxyMode;
3532 // Reset the saved proxy mode.
3533 savedProxyMode = null;
3536 // Get the search string.
3537 String searchString = sharedPreferences.getString("search", getString(R.string.search_default_value));
3539 // Set the search string.
3540 if (searchString.equals("Custom URL")) { // A custom search string is used.
3541 searchURL = sharedPreferences.getString("search_custom_url", getString(R.string.search_custom_url_default_value));
3542 } else { // A custom search string is not used.
3543 searchURL = searchString;
3549 // Adjust the layout and scrolling parameters according to the position of the app bar.
3550 if (bottomAppBar) { // The app bar is on the bottom.
3552 if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) { // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
3553 // Reset the WebView padding to fill the available space.
3554 swipeRefreshLayout.setPadding(0, 0, 0, 0);
3555 } else { // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
3556 // Move the WebView above the app bar layout.
3557 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight);
3559 // Show the app bar if it is scrolled off the screen.
3560 if (appBarLayout.getTranslationY() != 0) {
3561 // Animate the bottom app bar onto the screen.
3562 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0);
3565 objectAnimator.start();
3568 } else { // The app bar is on the top.
3569 // Get the current layout parameters. Using coordinator layout parameters allows the `setBehavior()` command and using app bar layout parameters allows the `setScrollFlags()` command.
3570 CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
3571 AppBarLayout.LayoutParams toolbarLayoutParams = (AppBarLayout.LayoutParams) toolbar.getLayoutParams();
3572 AppBarLayout.LayoutParams findOnPageLayoutParams = (AppBarLayout.LayoutParams) findOnPageLinearLayout.getLayoutParams();
3573 AppBarLayout.LayoutParams tabsLayoutParams = (AppBarLayout.LayoutParams) tabsLinearLayout.getLayoutParams();
3575 // Add the scrolling behavior to the layout parameters.
3577 // Enable scrolling of the app bar.
3578 swipeRefreshLayoutParams.setBehavior(new AppBarLayout.ScrollingViewBehavior());
3579 toolbarLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3580 findOnPageLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3581 tabsLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3583 // Disable scrolling of the app bar.
3584 swipeRefreshLayoutParams.setBehavior(null);
3585 toolbarLayoutParams.setScrollFlags(0);
3586 findOnPageLayoutParams.setScrollFlags(0);
3587 tabsLayoutParams.setScrollFlags(0);
3589 // Expand the app bar if it is currently collapsed.
3590 appBarLayout.setExpanded(true);
3593 // Set the app bar scrolling for each WebView.
3594 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3595 // Get the WebView tab fragment.
3596 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3598 // Get the fragment view.
3599 View fragmentView = webViewTabFragment.getView();
3601 // Only modify the WebViews if they exist.
3602 if (fragmentView != null) {
3603 // Get the nested scroll WebView from the tab fragment.
3604 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3606 // Set the app bar scrolling.
3607 nestedScrollWebView.setNestedScrollingEnabled(scrollAppBar);
3612 // Update the full screen browsing mode settings.
3613 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
3614 // Update the visibility of the app bar, which might have changed in the settings.
3616 // Hide the tab linear layout.
3617 tabsLinearLayout.setVisibility(View.GONE);
3619 // Hide the action bar.
3622 // Show the tab linear layout.
3623 tabsLinearLayout.setVisibility(View.VISIBLE);
3625 // Show the action bar.
3629 /* Hide the system bars.
3630 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3631 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
3632 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3633 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3635 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
3636 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3637 } else { // Privacy Browser is not in full screen browsing mode.
3638 // 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.
3639 inFullScreenBrowsingMode = false;
3641 // Show the tab linear layout.
3642 tabsLinearLayout.setVisibility(View.VISIBLE);
3644 // Show the action bar.
3647 // Remove the `SYSTEM_UI` flags from the root frame layout.
3648 rootFrameLayout.setSystemUiVisibility(0);
3653 public void navigateHistory(@NonNull String url, int steps) {
3654 // Apply the domain settings.
3655 applyDomainSettings(currentWebView, url, false, false, false);
3657 // Load the history entry.
3658 currentWebView.goBackOrForward(steps);
3662 public void pinnedErrorGoBack() {
3663 // Get the current web back forward list.
3664 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
3666 // Get the previous entry URL.
3667 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
3669 // Apply the domain settings.
3670 applyDomainSettings(currentWebView, previousUrl, false, false, false);
3673 currentWebView.goBack();
3676 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
3677 @SuppressLint("SetJavaScriptEnabled")
3678 private void applyDomainSettings(NestedScrollWebView nestedScrollWebView, String url, boolean resetTab, boolean reloadWebsite, boolean loadUrl) {
3679 // Store the current URL.
3680 nestedScrollWebView.setCurrentUrl(url);
3682 // Parse the URL into a URI.
3683 Uri uri = Uri.parse(url);
3685 // Extract the domain from `uri`.
3686 String newHostName = uri.getHost();
3688 // Strings don't like to be null.
3689 if (newHostName == null) {
3693 // 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.
3694 if (!nestedScrollWebView.getCurrentDomainName().equals(newHostName) || newHostName.equals("")) {
3695 // Set the new host name as the current domain name.
3696 nestedScrollWebView.setCurrentDomainName(newHostName);
3698 // Reset the ignoring of pinned domain information.
3699 nestedScrollWebView.setIgnorePinnedDomainInformation(false);
3701 // Clear any pinned SSL certificate or IP addresses.
3702 nestedScrollWebView.clearPinnedSslCertificate();
3703 nestedScrollWebView.setPinnedIpAddresses("");
3705 // Reset the favorite icon if specified.
3707 // Initialize the favorite icon.
3708 nestedScrollWebView.initializeFavoriteIcon();
3710 // Get the current page position.
3711 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
3713 // Get the corresponding tab.
3714 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
3716 // Update the tab if it isn't null, which sometimes happens when restarting from the background.
3718 // Get the tab custom view.
3719 View tabCustomView = tab.getCustomView();
3721 // Remove the warning below that the tab custom view might be null.
3722 assert tabCustomView != null;
3724 // Get the tab views.
3725 ImageView tabFavoriteIconImageView = tabCustomView.findViewById(R.id.favorite_icon_imageview);
3726 TextView tabTitleTextView = tabCustomView.findViewById(R.id.title_textview);
3728 // Set the default favorite icon as the favorite icon for this tab.
3729 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(nestedScrollWebView.getFavoriteOrDefaultIcon(), 64, 64, true));
3731 // Set the loading title text.
3732 tabTitleTextView.setText(R.string.loading);
3736 // Get a full domain name cursor.
3737 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3739 // Initialize `domainSettingsSet`.
3740 Set<String> domainSettingsSet = new HashSet<>();
3742 // Get the domain name column index.
3743 int domainNameColumnIndex = domainNameCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.DOMAIN_NAME);
3745 // Populate the domain settings set.
3746 for (int i = 0; i < domainNameCursor.getCount(); i++) {
3747 // Move the domains cursor to the current row.
3748 domainNameCursor.moveToPosition(i);
3750 // Store the domain name in the domain settings set.
3751 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3754 // Close the domain name cursor.
3755 domainNameCursor.close();
3757 // Initialize the domain name in database variable.
3758 String domainNameInDatabase = null;
3760 // Check the hostname against the domain settings set.
3761 if (domainSettingsSet.contains(newHostName)) { // The hostname is contained in the domain settings set.
3762 // Record the domain name in the database.
3763 domainNameInDatabase = newHostName;
3765 // Set the domain settings applied tracker to true.
3766 nestedScrollWebView.setDomainSettingsApplied(true);
3767 } else { // The hostname is not contained in the domain settings set.
3768 // Set the domain settings applied tracker to false.
3769 nestedScrollWebView.setDomainSettingsApplied(false);
3772 // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3773 while (!nestedScrollWebView.getDomainSettingsApplied() && newHostName.contains(".")) { // Stop checking if domain settings are already applied or there are no more `.` in the hostname.
3774 if (domainSettingsSet.contains("*." + newHostName)) { // Check the host name prepended by `*.`.
3775 // Set the domain settings applied tracker to true.
3776 nestedScrollWebView.setDomainSettingsApplied(true);
3778 // Store the applied domain names as it appears in the database.
3779 domainNameInDatabase = "*." + newHostName;
3782 // Strip out the lowest subdomain of of the host name.
3783 newHostName = newHostName.substring(newHostName.indexOf(".") + 1);
3787 // Get a handle for the shared preferences.
3788 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3790 // Store the general preference information.
3791 String defaultFontSizeString = sharedPreferences.getString("font_size", getString(R.string.font_size_default_value));
3792 String defaultUserAgentName = sharedPreferences.getString("user_agent", getString(R.string.user_agent_default_value));
3793 boolean defaultSwipeToRefresh = sharedPreferences.getBoolean("swipe_to_refresh", true);
3794 String webViewTheme = sharedPreferences.getString("webview_theme", getString(R.string.webview_theme_default_value));
3795 boolean wideViewport = sharedPreferences.getBoolean("wide_viewport", true);
3796 boolean displayWebpageImages = sharedPreferences.getBoolean("display_webpage_images", true);
3798 // Get the WebView theme entry values string array.
3799 String[] webViewThemeEntryValuesStringArray = getResources().getStringArray(R.array.webview_theme_entry_values);
3801 // Get a handle for the cookie manager.
3802 CookieManager cookieManager = CookieManager.getInstance();
3804 // Initialize the user agent array adapter and string array.
3805 ArrayAdapter<CharSequence> userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item);
3806 String[] userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
3808 if (nestedScrollWebView.getDomainSettingsApplied()) { // The url has custom domain settings.
3809 // Remove the incorrect lint warning below that the domain name in database might be null.
3810 assert domainNameInDatabase != null;
3812 // Get a cursor for the current host.
3813 Cursor currentDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3815 // Move to the first position.
3816 currentDomainSettingsCursor.moveToFirst();
3818 // Get the settings from the cursor.
3819 nestedScrollWebView.setDomainSettingsDatabaseId(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ID)));
3820 nestedScrollWebView.getSettings().setJavaScriptEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3821 nestedScrollWebView.setAcceptCookies(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.COOKIES)) == 1);
3822 nestedScrollWebView.getSettings().setDomStorageEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3823 // Form data can be removed once the minimum API >= 26.
3824 boolean saveFormData = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3825 nestedScrollWebView.setEasyListEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3826 nestedScrollWebView.setEasyPrivacyEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3827 nestedScrollWebView.setFanboysAnnoyanceListEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3828 nestedScrollWebView.setFanboysSocialBlockingListEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(
3829 DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3830 nestedScrollWebView.setUltraListEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ULTRALIST)) == 1);
3831 nestedScrollWebView.setUltraPrivacyEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_ULTRAPRIVACY)) == 1);
3832 nestedScrollWebView.setBlockAllThirdPartyRequests(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
3833 String userAgentName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.USER_AGENT));
3834 int fontSize = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.FONT_SIZE));
3835 int swipeToRefreshInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
3836 int webViewThemeInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.WEBVIEW_THEME));
3837 int wideViewportInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.WIDE_VIEWPORT));
3838 int displayWebpageImagesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.DISPLAY_IMAGES));
3839 boolean pinnedSslCertificate = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3840 String pinnedSslIssuedToCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3841 String pinnedSslIssuedToOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3842 String pinnedSslIssuedToUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3843 String pinnedSslIssuedByCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3844 String pinnedSslIssuedByOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3845 String pinnedSslIssuedByUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3846 Date pinnedSslStartDate = new Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_START_DATE)));
3847 Date pinnedSslEndDate = new Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_END_DATE)));
3848 boolean pinnedIpAddresses = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.PINNED_IP_ADDRESSES)) == 1);
3849 String pinnedHostIpAddresses = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.IP_ADDRESSES));
3851 // Close the current host domain settings cursor.
3852 currentDomainSettingsCursor.close();
3854 // If there is a pinned SSL certificate, store it in the WebView.
3855 if (pinnedSslCertificate) {
3856 nestedScrollWebView.setPinnedSslCertificate(pinnedSslIssuedToCName, pinnedSslIssuedToOName, pinnedSslIssuedToUName, pinnedSslIssuedByCName, pinnedSslIssuedByOName, pinnedSslIssuedByUName,
3857 pinnedSslStartDate, pinnedSslEndDate);
3860 // If there is a pinned IP address, store it in the WebView.
3861 if (pinnedIpAddresses) {
3862 nestedScrollWebView.setPinnedIpAddresses(pinnedHostIpAddresses);
3865 // Apply the cookie domain settings.
3866 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptCookies());
3868 // Apply the form data setting if the API < 26.
3869 if (Build.VERSION.SDK_INT < 26) {
3870 nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
3873 // Apply the font size.
3874 try { // Try the specified font size to see if it is valid.
3875 if (fontSize == 0) { // Apply the default font size.
3876 // Try to set the font size from the value in the app settings.
3877 nestedScrollWebView.getSettings().setTextZoom(Integer.parseInt(defaultFontSizeString));
3878 } else { // Apply the font size from domain settings.
3879 nestedScrollWebView.getSettings().setTextZoom(fontSize);
3881 } catch (Exception exception) { // The specified font size is invalid
3882 // Set the font size to be 100%
3883 nestedScrollWebView.getSettings().setTextZoom(100);
3886 // Set the user agent.
3887 if (userAgentName.equals(getString(R.string.system_default_user_agent))) { // Use the system default user agent.
3888 // Get the array position of the default user agent name.
3889 int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3891 // Set the user agent according to the system default.
3892 switch (defaultUserAgentArrayPosition) {
3893 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
3894 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3895 nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
3898 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3899 // Set the user agent to `""`, which uses the default value.
3900 nestedScrollWebView.getSettings().setUserAgentString("");
3903 case SETTINGS_CUSTOM_USER_AGENT:
3904 // Set the default custom user agent.
3905 nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
3909 // Get the user agent string from the user agent data array
3910 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
3912 } else { // Set the user agent according to the stored name.
3913 // Get the array position of the user agent name.
3914 int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
3916 switch (userAgentArrayPosition) {
3917 case UNRECOGNIZED_USER_AGENT: // The user agent name contains a custom user agent.
3918 nestedScrollWebView.getSettings().setUserAgentString(userAgentName);
3921 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3922 // Set the user agent to `""`, which uses the default value.
3923 nestedScrollWebView.getSettings().setUserAgentString("");
3927 // Get the user agent string from the user agent data array.
3928 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3932 // Set swipe to refresh.
3933 switch (swipeToRefreshInt) {
3934 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
3935 // Store the swipe to refresh status in the nested scroll WebView.
3936 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
3938 // Update the swipe refresh layout.
3939 if (defaultSwipeToRefresh) { // Swipe to refresh is enabled.
3940 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
3941 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);
3952 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
3953 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
3956 case DomainsDatabaseHelper.DISABLED:
3957 // Store the swipe to refresh status in the nested scroll WebView.
3958 nestedScrollWebView.setSwipeToRefresh(false);
3960 // Disable swipe to refresh.
3961 swipeRefreshLayout.setEnabled(false);
3964 // Check to see if WebView themes are supported.
3965 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
3966 // Set the WebView theme.
3967 switch (webViewThemeInt) {
3968 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
3969 // Set the WebView theme. A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
3970 if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) { // The light theme is selected.
3971 // Turn off the WebView dark mode.
3972 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
3973 } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) { // The dark theme is selected.
3974 // Turn on the WebView dark mode.
3975 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
3976 } else { // The system default theme is selected.
3977 // Get the current system theme status.
3978 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
3980 // Set the WebView theme according to the current system theme status.
3981 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) { // The system is in day mode.
3982 // Turn off the WebView dark mode.
3983 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
3984 } else { // The system is in night mode.
3985 // Turn on the WebView dark mode.
3986 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
3991 case DomainsDatabaseHelper.LIGHT_THEME:
3992 // Turn off the WebView dark mode.
3993 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
3996 case DomainsDatabaseHelper.DARK_THEME:
3997 // Turn on the WebView dark mode.
3998 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4003 // Set the viewport.
4004 switch (wideViewportInt) {
4005 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4006 nestedScrollWebView.getSettings().setUseWideViewPort(wideViewport);
4009 case DomainsDatabaseHelper.ENABLED:
4010 nestedScrollWebView.getSettings().setUseWideViewPort(true);
4013 case DomainsDatabaseHelper.DISABLED:
4014 nestedScrollWebView.getSettings().setUseWideViewPort(false);
4018 // Set the loading of webpage images.
4019 switch (displayWebpageImagesInt) {
4020 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4021 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
4024 case DomainsDatabaseHelper.ENABLED:
4025 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(true);
4028 case DomainsDatabaseHelper.DISABLED:
4029 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(false);
4033 // Set a background on the URL relative layout to indicate that custom domain settings are being used.
4034 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.domain_settings_url_background, null));
4035 } else { // The new URL does not have custom domain settings. Load the defaults.
4036 // Store the values from the shared preferences.
4037 nestedScrollWebView.getSettings().setJavaScriptEnabled(sharedPreferences.getBoolean("javascript", false));
4038 nestedScrollWebView.setAcceptCookies(sharedPreferences.getBoolean(getString(R.string.cookies_key), false));
4039 nestedScrollWebView.getSettings().setDomStorageEnabled(sharedPreferences.getBoolean("dom_storage", false));
4040 boolean saveFormData = sharedPreferences.getBoolean("save_form_data", false); // Form data can be removed once the minimum API >= 26.
4041 nestedScrollWebView.setEasyListEnabled(sharedPreferences.getBoolean("easylist", true));
4042 nestedScrollWebView.setEasyPrivacyEnabled(sharedPreferences.getBoolean("easyprivacy", true));
4043 nestedScrollWebView.setFanboysAnnoyanceListEnabled(sharedPreferences.getBoolean("fanboys_annoyance_list", true));
4044 nestedScrollWebView.setFanboysSocialBlockingListEnabled(sharedPreferences.getBoolean("fanboys_social_blocking_list", true));
4045 nestedScrollWebView.setUltraListEnabled(sharedPreferences.getBoolean("ultralist", true));
4046 nestedScrollWebView.setUltraPrivacyEnabled(sharedPreferences.getBoolean("ultraprivacy", true));
4047 nestedScrollWebView.setBlockAllThirdPartyRequests(sharedPreferences.getBoolean("block_all_third_party_requests", false));
4049 // Apply the default cookie setting.
4050 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptCookies());
4052 // Apply the default font size setting.
4054 // Try to set the font size from the value in the app settings.
4055 nestedScrollWebView.getSettings().setTextZoom(Integer.parseInt(defaultFontSizeString));
4056 } catch (Exception exception) {
4057 // If the app settings value is invalid, set the font size to 100%.
4058 nestedScrollWebView.getSettings().setTextZoom(100);
4061 // Apply the form data setting if the API < 26.
4062 if (Build.VERSION.SDK_INT < 26) {
4063 nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
4066 // Store the swipe to refresh status in the nested scroll WebView.
4067 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
4069 // Update the swipe refresh layout.
4070 if (defaultSwipeToRefresh) { // Swipe to refresh is enabled.
4071 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
4072 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
4073 } else { // Swipe to refresh is disabled.
4074 // Disable the swipe refresh layout.
4075 swipeRefreshLayout.setEnabled(false);
4078 // Reset the pinned variables.
4079 nestedScrollWebView.setDomainSettingsDatabaseId(-1);
4081 // Get the array position of the user agent name.
4082 int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
4084 // Set the user agent.
4085 switch (userAgentArrayPosition) {
4086 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
4087 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
4088 nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
4091 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4092 // Set the user agent to `""`, which uses the default value.
4093 nestedScrollWebView.getSettings().setUserAgentString("");
4096 case SETTINGS_CUSTOM_USER_AGENT:
4097 // Set the default custom user agent.
4098 nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
4102 // Get the user agent string from the user agent data array
4103 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4106 // Apply the WebView theme if supported by the installed WebView.
4107 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
4108 // Set the WebView theme. A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
4109 if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) { // The light theme is selected.
4110 // Turn off the WebView dark mode.
4111 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4112 } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) { // The dark theme is selected.
4113 // Turn on the WebView dark mode.
4114 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4115 } else { // The system default theme is selected.
4116 // Get the current system theme status.
4117 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4119 // Set the WebView theme according to the current system theme status.
4120 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) { // The system is in day mode.
4121 // Turn off the WebView dark mode.
4122 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4123 } else { // The system is in night mode.
4124 // Turn on the WebView dark mode.
4125 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4130 // Set the viewport.
4131 nestedScrollWebView.getSettings().setUseWideViewPort(wideViewport);
4133 // Set the loading of webpage images.
4134 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
4136 // Set a transparent background on the URL relative layout.
4137 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.color.transparent, null));
4140 // Close the domains database helper.
4141 domainsDatabaseHelper.close();
4143 // Update the privacy icons.
4144 updatePrivacyIcons(true);
4147 // Reload the website if returning from the Domains activity.
4148 if (reloadWebsite) {
4149 nestedScrollWebView.reload();
4152 // 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.
4154 nestedScrollWebView.loadUrl(url, customHeaders);
4158 private void applyProxy(boolean reloadWebViews) {
4159 // Set the proxy according to the mode.
4160 proxyHelper.setProxy(getApplicationContext(), appBarLayout, proxyMode);
4162 // Reset the waiting for proxy tracker.
4163 waitingForProxy = false;
4165 // Get the current theme status.
4166 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4168 // Update the user interface and reload the WebViews if requested.
4169 switch (proxyMode) {
4170 case ProxyHelper.NONE:
4171 // Initialize a color background typed value.
4172 TypedValue colorBackgroundTypedValue = new TypedValue();
4174 // Get the color background from the theme.
4175 getTheme().resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true);
4177 // Get the color background int from the typed value.
4178 int colorBackgroundInt = colorBackgroundTypedValue.data;
4180 // Set the default app bar layout background.
4181 appBarLayout.setBackgroundColor(colorBackgroundInt);
4184 case ProxyHelper.TOR:
4185 // Set the app bar background to indicate proxying through Orbot is enabled.
4186 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4187 appBarLayout.setBackgroundResource(R.color.blue_50);
4189 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4192 // Check to see if Orbot is installed.
4194 // Get the package manager.
4195 PackageManager packageManager = getPackageManager();
4197 // 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.
4198 packageManager.getPackageInfo("org.torproject.android", 0);
4200 // Check to see if the proxy is ready.
4201 if (!orbotStatus.equals(ProxyHelper.ORBOT_STATUS_ON)) { // Orbot is not ready.
4202 // Set the waiting for proxy status.
4203 waitingForProxy = true;
4205 // Show the waiting for proxy dialog if it isn't already displayed.
4206 if (getSupportFragmentManager().findFragmentByTag(getString(R.string.waiting_for_proxy_dialog)) == null) {
4207 // Get a handle for the waiting for proxy alert dialog.
4208 DialogFragment waitingForProxyDialogFragment = new WaitingForProxyDialog();
4210 // Try to show the dialog. Sometimes the window is not yet active if returning from Settings.
4212 // Show the waiting for proxy alert dialog.
4213 waitingForProxyDialogFragment.show(getSupportFragmentManager(), getString(R.string.waiting_for_proxy_dialog));
4214 } catch (Exception waitingForTorException) {
4215 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
4216 pendingDialogsArrayList.add(new PendingDialog(waitingForProxyDialogFragment, getString(R.string.waiting_for_proxy_dialog)));
4220 } catch (PackageManager.NameNotFoundException exception) { // Orbot is not installed.
4221 // Show the Orbot not installed dialog if it is not already displayed.
4222 if (getSupportFragmentManager().findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
4223 // Get a handle for the Orbot not installed alert dialog.
4224 DialogFragment orbotNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode);
4226 // Try to show the dialog. Sometimes the window is not yet active if returning from Settings.
4228 // Display the Orbot not installed alert dialog.
4229 orbotNotInstalledDialogFragment.show(getSupportFragmentManager(), getString(R.string.proxy_not_installed_dialog));
4230 } catch (Exception orbotNotInstalledException) {
4231 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
4232 pendingDialogsArrayList.add(new PendingDialog(orbotNotInstalledDialogFragment, getString(R.string.proxy_not_installed_dialog)));
4238 case ProxyHelper.I2P:
4239 // Set the app bar background to indicate proxying through Orbot is enabled.
4240 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4241 appBarLayout.setBackgroundResource(R.color.blue_50);
4243 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4246 // Check to see if I2P is installed.
4248 // Get the package manager.
4249 PackageManager packageManager = getPackageManager();
4251 // Check to see if I2P is in the list. This will throw an error and drop to the catch section if it isn't installed.
4252 packageManager.getPackageInfo("net.i2p.android.router", 0);
4253 } catch (PackageManager.NameNotFoundException exception) { // I2P is not installed.
4254 // Sow the I2P not installed dialog if it is not already displayed.
4255 if (getSupportFragmentManager().findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
4256 // Get a handle for the waiting for proxy alert dialog.
4257 DialogFragment i2pNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode);
4259 // Try to show the dialog. Sometimes the window is not yet active if returning from Settings.
4261 // Display the I2P not installed alert dialog.
4262 i2pNotInstalledDialogFragment.show(getSupportFragmentManager(), getString(R.string.proxy_not_installed_dialog));
4263 } catch (Exception i2pNotInstalledException) {
4264 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
4265 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("open_intents_in_new_tab", 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("clear_everything", 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("clear_cookies", 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("clear_dom_storage", 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("clear_form_data", 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("clear_cache", 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/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 // Clear the custom headers.
4877 customHeaders.clear();
4879 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
4880 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
4881 if (clearEverything) {
4883 // Delete the folder.
4884 Process deleteAppWebviewProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
4886 // Wait until the process has finished.
4887 deleteAppWebviewProcess.waitFor();
4888 } catch (Exception exception) {
4889 // Do nothing if an error is thrown.
4893 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
4894 finishAndRemoveTask();
4896 // Remove the terminated program from RAM. The status code is `0`.
4900 public void bookmarksBack(View view) {
4901 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
4902 // close the bookmarks drawer.
4903 drawerLayout.closeDrawer(GravityCompat.END);
4904 } else { // A subfolder is displayed.
4905 // Place the former parent folder in `currentFolder`.
4906 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolderName(currentBookmarksFolder);
4908 // Load the new folder.
4909 loadBookmarksFolder();
4913 private void setCurrentWebView(int pageNumber) {
4914 // Stop the swipe to refresh indicator if it is running
4915 swipeRefreshLayout.setRefreshing(false);
4917 // Get the WebView tab fragment.
4918 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(pageNumber);
4920 // Get the fragment view.
4921 View webViewFragmentView = webViewTabFragment.getView();
4923 // Set the current WebView if the fragment view is not null.
4924 if (webViewFragmentView != null) { // The fragment has been populated.
4925 // Store the current WebView.
4926 currentWebView = webViewFragmentView.findViewById(R.id.nestedscroll_webview);
4928 // Update the status of swipe to refresh.
4929 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
4930 // Enable the swipe refresh layout if the WebView is scrolled all the way to the top. It is updated every time the scroll changes.
4931 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
4932 } else { // Swipe to refresh is disabled.
4933 // Disable the swipe refresh layout.
4934 swipeRefreshLayout.setEnabled(false);
4937 // Get a handle for the cookie manager.
4938 CookieManager cookieManager = CookieManager.getInstance();
4940 // Set the cookie status.
4941 cookieManager.setAcceptCookie(currentWebView.getAcceptCookies());
4943 // Update the privacy icons. `true` redraws the icons in the app bar.
4944 updatePrivacyIcons(true);
4946 // Get a handle for the input method manager.
4947 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
4949 // Remove the lint warning below that the input method manager might be null.
4950 assert inputMethodManager != null;
4952 // Get the current URL.
4953 String url = currentWebView.getUrl();
4955 // Update the URL edit text if not loading a new intent. Otherwise, this will be handled by `onPageStarted()` (if called) and `onPageFinished()`.
4956 if (!loadingNewIntent) { // A new intent is not being loaded.
4957 if ((url == null) || url.equals("about:blank")) { // The WebView is blank.
4958 // Display the hint in the URL edit text.
4959 urlEditText.setText("");
4961 // Request focus for the URL text box.
4962 urlEditText.requestFocus();
4964 // Display the keyboard.
4965 inputMethodManager.showSoftInput(urlEditText, 0);
4966 } else { // The WebView has a loaded URL.
4967 // Clear the focus from the URL text box.
4968 urlEditText.clearFocus();
4970 // Hide the soft keyboard.
4971 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
4973 // Display the current URL in the URL text box.
4974 urlEditText.setText(url);
4976 // Highlight the URL text.
4979 } else { // A new intent is being loaded.
4980 // Reset the loading new intent tracker.
4981 loadingNewIntent = false;
4984 // Set the background to indicate the domain settings status.
4985 if (currentWebView.getDomainSettingsApplied()) {
4986 // Set a background on the URL relative layout to indicate that custom domain settings are being used.
4987 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.domain_settings_url_background, null));
4989 // Remove any background on the URL relative layout.
4990 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.color.transparent, null));
4992 } else { // The fragment has not been populated. Try again in 100 milliseconds.
4993 // Create a handler to set the current WebView.
4994 Handler setCurrentWebViewHandler = new Handler();
4996 // Create a runnable to set the current WebView.
4997 Runnable setCurrentWebWebRunnable = () -> {
4998 // Set the current WebView.
4999 setCurrentWebView(pageNumber);
5002 // Try setting the current WebView again after 100 milliseconds.
5003 setCurrentWebViewHandler.postDelayed(setCurrentWebWebRunnable, 100);
5007 @SuppressLint("ClickableViewAccessibility")
5009 public void initializeWebView(NestedScrollWebView nestedScrollWebView, int pageNumber, ProgressBar progressBar, String url, Boolean restoringState) {
5010 // Get a handle for the shared preferences.
5011 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
5013 // Get the WebView theme.
5014 String webViewTheme = sharedPreferences.getString("webview_theme", getString(R.string.webview_theme_default_value));
5016 // Get the WebView theme entry values string array.
5017 String[] webViewThemeEntryValuesStringArray = getResources().getStringArray(R.array.webview_theme_entry_values);
5019 // Apply the WebView theme if supported by the installed WebView.
5020 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
5021 // Set the WebView theme. A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
5022 if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) { // The light theme is selected.
5023 // Turn off the WebView dark mode.
5024 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
5026 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
5027 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
5028 nestedScrollWebView.setVisibility(View.VISIBLE);
5029 } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) { // The dark theme is selected.
5030 // Turn on the WebView dark mode.
5031 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
5032 } else { // The system default theme is selected.
5033 // Get the current system theme status.
5034 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
5036 // Set the WebView theme according to the current system theme status.
5037 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) { // The system is in day mode.
5038 // Turn off the WebView dark mode.
5039 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
5041 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
5042 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
5043 nestedScrollWebView.setVisibility(View.VISIBLE);
5044 } else { // The system is in night mode.
5045 // Turn on the WebView dark mode.
5046 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
5051 // Get a handle for the activity
5052 Activity activity = this;
5054 // Get a handle for the input method manager.
5055 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
5057 // Instantiate the blocklist helper.
5058 BlocklistHelper blocklistHelper = new BlocklistHelper();
5060 // Remove the lint warning below that the input method manager might be null.
5061 assert inputMethodManager != null;
5063 // Set the app bar scrolling.
5064 nestedScrollWebView.setNestedScrollingEnabled(scrollAppBar);
5066 // Allow pinch to zoom.
5067 nestedScrollWebView.getSettings().setBuiltInZoomControls(true);
5069 // Hide zoom controls.
5070 nestedScrollWebView.getSettings().setDisplayZoomControls(false);
5072 // Don't allow mixed content (HTTP and HTTPS) on the same website.
5073 nestedScrollWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW);
5075 // Set the WebView to load in overview mode (zoomed out to the maximum width).
5076 nestedScrollWebView.getSettings().setLoadWithOverviewMode(true);
5078 // Explicitly disable geolocation.
5079 nestedScrollWebView.getSettings().setGeolocationEnabled(false);
5081 // Allow loading of file:// URLs. This is necessary for opening MHT web archives, which are copies into a temporary cache location.
5082 nestedScrollWebView.getSettings().setAllowFileAccess(true);
5084 // Create a double-tap gesture detector to toggle full-screen mode.
5085 GestureDetector doubleTapGestureDetector = new GestureDetector(getApplicationContext(), new GestureDetector.SimpleOnGestureListener() {
5086 // Override `onDoubleTap()`. All other events are handled using the default settings.
5088 public boolean onDoubleTap(MotionEvent event) {
5089 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
5090 // Toggle the full screen browsing mode tracker.
5091 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
5093 // Toggle the full screen browsing mode.
5094 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
5095 // Hide the app bar if specified.
5096 if (hideAppBar) { // The app bar is hidden.
5097 // Close the find on page bar if it is visible.
5098 closeFindOnPage(null);
5100 // Hide the tab linear layout.
5101 tabsLinearLayout.setVisibility(View.GONE);
5103 // Hide the action bar.
5106 // Set layout and scrolling parameters according to the position of the app bar.
5107 if (bottomAppBar) { // The app bar is at the bottom.
5108 // Reset the WebView padding to fill the available space.
5109 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5110 } else { // The app bar is at the top.
5111 // Check to see if the app bar is normally scrolled.
5112 if (scrollAppBar) { // The app bar is scrolled when it is displayed.
5113 // Get the swipe refresh layout parameters.
5114 CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
5116 // Remove the off-screen scrolling layout.
5117 swipeRefreshLayoutParams.setBehavior(null);
5118 } else { // The app bar is not scrolled when it is displayed.
5119 // Remove the padding from the top of the swipe refresh layout.
5120 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5122 // The swipe refresh circle must be moved above the now removed status bar location.
5123 swipeRefreshLayout.setProgressViewOffset(false, -200, defaultProgressViewEndOffset);
5126 } else { // The app bar is not hidden.
5127 // Adjust the UI for the bottom app bar.
5129 // Adjust the UI according to the scrolling of the app bar.
5131 // Reset the WebView padding to fill the available space.
5132 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5134 // Move the WebView above the app bar layout.
5135 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight);
5140 /* Hide the system bars.
5141 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5142 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5143 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5144 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5146 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5147 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5148 } else { // Switch to normal viewing mode.
5149 // Show the app bar if it was hidden.
5151 // Show the tab linear layout.
5152 tabsLinearLayout.setVisibility(View.VISIBLE);
5154 // Show the action bar.
5158 // Set layout and scrolling parameters according to the position of the app bar.
5159 if (bottomAppBar) { // The app bar is at the bottom.
5162 // Reset the WebView padding to fill the available space.
5163 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5165 // Move the WebView above the app bar layout.
5166 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight);
5168 } else { // The app bar is at the top.
5169 // Check to see if the app bar is normally scrolled.
5170 if (scrollAppBar) { // The app bar is scrolled when it is displayed.
5171 // Get the swipe refresh layout parameters.
5172 CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
5174 // Add the off-screen scrolling layout.
5175 swipeRefreshLayoutParams.setBehavior(new AppBarLayout.ScrollingViewBehavior());
5176 } else { // The app bar is not scrolled when it is displayed.
5177 // The swipe refresh layout must be manually moved below the app bar layout.
5178 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0);
5180 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5181 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight);
5185 // Remove the `SYSTEM_UI` flags from the root frame layout.
5186 rootFrameLayout.setSystemUiVisibility(0);
5189 // Consume the double-tap.
5191 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
5197 public boolean onFling(MotionEvent motionEvent1, MotionEvent motionEvent2, float velocityX, float velocityY) {
5198 // Scroll the bottom app bar if enabled.
5199 if (bottomAppBar && scrollAppBar && !objectAnimator.isRunning()) {
5200 // Calculate the Y change.
5201 float motionY = motionEvent2.getY() - motionEvent1.getY();
5203 // Scroll the app bar if the change is greater than 100 pixels.
5205 // Animate the bottom app bar onto the screen.
5206 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0);
5207 } else if (motionY < -50) {
5208 // Animate the bottom app bar off the screen.
5209 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", appBarLayout.getHeight());
5213 objectAnimator.start();
5216 // Do not consume the event.
5221 // Pass all touch events on the WebView through the double-tap gesture detector.
5222 nestedScrollWebView.setOnTouchListener((View view, MotionEvent event) -> {
5223 // Call `performClick()` on the view, which is required for accessibility.
5224 view.performClick();
5226 // Send the event to the gesture detector.
5227 return doubleTapGestureDetector.onTouchEvent(event);
5230 // Register the WebView for a context menu. This is used to see link targets and download images.
5231 registerForContextMenu(nestedScrollWebView);
5233 // Allow the downloading of files.
5234 nestedScrollWebView.setDownloadListener((String downloadUrl, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
5235 // Check the download preference.
5236 if (downloadWithExternalApp) { // Download with an external app.
5237 downloadUrlWithExternalApp(downloadUrl);
5238 } else { // Handle the download inside of Privacy Browser.
5239 // Define a formatted file size string.
5240 String formattedFileSizeString;
5242 // Process the content length if it contains data.
5243 if (contentLength > 0) { // The content length is greater than 0.
5244 // Format the content length as a string.
5245 formattedFileSizeString = NumberFormat.getInstance().format(contentLength) + " " + getString(R.string.bytes);
5246 } else { // The content length is not greater than 0.
5247 // Set the formatted file size string to be `unknown size`.
5248 formattedFileSizeString = getString(R.string.unknown_size);
5251 // Get the file name from the content disposition.
5252 String fileNameString = PrepareSaveDialog.getFileNameFromHeaders(this, contentDisposition, mimetype, downloadUrl);
5254 // Instantiate the save dialog.
5255 DialogFragment saveDialogFragment = SaveDialog.saveUrl(downloadUrl, formattedFileSizeString, fileNameString, userAgent,
5256 nestedScrollWebView.getAcceptCookies());
5258 // 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.
5260 // Show the save dialog. It must be named `save_dialog` so that the file picker can update the file name.
5261 saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
5262 } catch (Exception exception) { // The dialog could not be shown.
5263 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
5264 pendingDialogsArrayList.add(new PendingDialog(saveDialogFragment, getString(R.string.save_dialog)));
5269 // Update the find on page count.
5270 nestedScrollWebView.setFindListener(new WebView.FindListener() {
5271 // Get a handle for `findOnPageCountTextView`.
5272 final TextView findOnPageCountTextView = findViewById(R.id.find_on_page_count_textview);
5275 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
5276 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
5277 // Set `findOnPageCountTextView` to `0/0`.
5278 findOnPageCountTextView.setText(R.string.zero_of_zero);
5279 } else if (isDoneCounting) { // There are matches.
5280 // `activeMatchOrdinal` is zero-based.
5281 int activeMatch = activeMatchOrdinal + 1;
5283 // Build the match string.
5284 String matchString = activeMatch + "/" + numberOfMatches;
5286 // Set `findOnPageCountTextView`.
5287 findOnPageCountTextView.setText(matchString);
5292 // Process scroll changes.
5293 nestedScrollWebView.setOnScrollChangeListener((view, scrollX, scrollY, oldScrollX, oldScrollY) -> {
5294 // Set the swipe to refresh status.
5295 if (nestedScrollWebView.getSwipeToRefresh()) {
5296 // Only enable swipe to refresh if the WebView is scrolled to the top.
5297 swipeRefreshLayout.setEnabled(nestedScrollWebView.getScrollY() == 0);
5299 // Disable swipe to refresh.
5300 swipeRefreshLayout.setEnabled(false);
5303 // Reinforce the system UI visibility flags if in full screen browsing mode.
5304 // This hides the status and navigation bars, which are displayed if other elements are shown, like dialog boxes, the options menu, or the keyboard.
5305 if (inFullScreenBrowsingMode) {
5306 /* Hide the system bars.
5307 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5308 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5309 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5310 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5312 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5313 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5317 // Set the web chrome client.
5318 nestedScrollWebView.setWebChromeClient(new WebChromeClient() {
5319 // Update the progress bar when a page is loading.
5321 public void onProgressChanged(WebView view, int progress) {
5322 // Update the progress bar.
5323 progressBar.setProgress(progress);
5325 // Set the visibility of the progress bar.
5326 if (progress < 100) {
5327 // Show the progress bar.
5328 progressBar.setVisibility(View.VISIBLE);
5330 // Hide the progress bar.
5331 progressBar.setVisibility(View.GONE);
5333 //Stop the swipe to refresh indicator if it is running
5334 swipeRefreshLayout.setRefreshing(false);
5336 // 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.
5337 nestedScrollWebView.setVisibility(View.VISIBLE);
5341 // Set the favorite icon when it changes.
5343 public void onReceivedIcon(WebView view, Bitmap icon) {
5344 // Only update the favorite icon if the website has finished loading.
5345 if (progressBar.getVisibility() == View.GONE) {
5346 // Store the new favorite icon.
5347 nestedScrollWebView.setFavoriteOrDefaultIcon(icon);
5349 // Get the current page position.
5350 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5352 // Get the current tab.
5353 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
5355 // Check to see if the tab has been populated.
5357 // Get the custom view from the tab.
5358 View tabView = tab.getCustomView();
5360 // Check to see if the custom tab view has been populated.
5361 if (tabView != null) {
5362 // Get the favorite icon image view from the tab.
5363 ImageView tabFavoriteIconImageView = tabView.findViewById(R.id.favorite_icon_imageview);
5365 // Display the favorite icon in the tab.
5366 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
5372 // Save a copy of the title when it changes.
5374 public void onReceivedTitle(WebView view, String title) {
5375 // Get the current page position.
5376 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5378 // Get the current tab.
5379 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
5381 // Only populate the title text view if the tab has been fully created.
5383 // Get the custom view from the tab.
5384 View tabView = tab.getCustomView();
5386 // Only populate the title text view if the tab view has been fully populated.
5387 if (tabView != null) {
5388 // Get the title text view from the tab.
5389 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
5391 // Set the title according to the URL.
5392 if (title.equals("about:blank")) {
5393 // Set the title to indicate a new tab.
5394 tabTitleTextView.setText(R.string.new_tab);
5396 // Set the title as the tab text.
5397 tabTitleTextView.setText(title);
5403 // Enter full screen video.
5405 public void onShowCustomView(View video, CustomViewCallback callback) {
5406 // Set the full screen video flag.
5407 displayingFullScreenVideo = true;
5409 // Hide the keyboard.
5410 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
5412 // Hide the coordinator layout.
5413 coordinatorLayout.setVisibility(View.GONE);
5415 /* Hide the system bars.
5416 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5417 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5418 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5419 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5421 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5422 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5424 // Disable the sliding drawers.
5425 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
5427 // Add the video view to the full screen video frame layout.
5428 fullScreenVideoFrameLayout.addView(video);
5430 // Show the full screen video frame layout.
5431 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
5433 // Disable the screen timeout while the video is playing. YouTube does this automatically, but not all other videos do.
5434 fullScreenVideoFrameLayout.setKeepScreenOn(true);
5437 // Exit full screen video.
5439 public void onHideCustomView() {
5440 // Exit the full screen video.
5441 exitFullScreenVideo();
5446 public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
5447 // Store the file path callback.
5448 fileChooserCallback = filePathCallback;
5450 // Create an intent to open a chooser based on the file chooser parameters.
5451 Intent fileChooserIntent = fileChooserParams.createIntent();
5453 // Get a handle for the package manager.
5454 PackageManager packageManager = getPackageManager();
5456 // Check to see if the file chooser intent resolves to an installed package.
5457 if (fileChooserIntent.resolveActivity(packageManager) != null) { // The file chooser intent is fine.
5458 // Start the file chooser intent.
5459 startActivityForResult(fileChooserIntent, BROWSE_FILE_UPLOAD_REQUEST_CODE);
5460 } else { // The file chooser intent will cause a crash.
5461 // Create a generic intent to open a chooser.
5462 Intent genericFileChooserIntent = new Intent(Intent.ACTION_GET_CONTENT);
5464 // Request an openable file.
5465 genericFileChooserIntent.addCategory(Intent.CATEGORY_OPENABLE);
5467 // Set the file type to everything.
5468 genericFileChooserIntent.setType("*/*");
5470 // Start the generic file chooser intent.
5471 startActivityForResult(genericFileChooserIntent, BROWSE_FILE_UPLOAD_REQUEST_CODE);
5477 nestedScrollWebView.setWebViewClient(new WebViewClient() {
5478 // `shouldOverrideUrlLoading` makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
5479 // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
5481 public boolean shouldOverrideUrlLoading(WebView view, String url) {
5482 // Sanitize the url.
5483 url = sanitizeUrl(url);
5485 // Handle the URL according to the type.
5486 if (url.startsWith("http")) { // Load the URL in Privacy Browser.
5487 // Load the URL. By using `loadUrl()`, instead of `loadUrlFromBase()`, the Referer header will never be sent.
5488 loadUrl(nestedScrollWebView, url);
5490 // Returning true indicates that Privacy Browser is manually handling the loading of the URL.
5491 // Custom headers cannot be added if false is returned and the WebView handles the loading of the URL.
5493 } else if (url.startsWith("mailto:")) { // Load the email address in an external email program.
5494 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
5495 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
5497 // Parse the url and set it as the data for the intent.
5498 emailIntent.setData(Uri.parse(url));
5500 // Open the email program in a new task instead of as part of Privacy Browser.
5501 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5505 startActivity(emailIntent);
5506 } catch (ActivityNotFoundException exception) {
5507 // Display a snackbar.
5508 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
5512 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5514 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
5515 // Open the dialer and load the phone number, but wait for the user to place the call.
5516 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
5518 // Add the phone number to the intent.
5519 dialIntent.setData(Uri.parse(url));
5521 // Open the dialer in a new task instead of as part of Privacy Browser.
5522 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5526 startActivity(dialIntent);
5527 } catch (ActivityNotFoundException exception) {
5528 // Display a snackbar.
5529 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
5532 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5534 } else { // Load a system chooser to select an app that can handle the URL.
5535 // Open an app that can handle the URL.
5536 Intent genericIntent = new Intent(Intent.ACTION_VIEW);
5538 // Add the URL to the intent.
5539 genericIntent.setData(Uri.parse(url));
5541 // List all apps that can handle the URL instead of just opening the first one.
5542 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
5544 // Open the app in a new task instead of as part of Privacy Browser.
5545 genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5547 // Start the app or display a snackbar if no app is available to handle the URL.
5549 startActivity(genericIntent);
5550 } catch (ActivityNotFoundException exception) {
5551 Snackbar.make(nestedScrollWebView, getString(R.string.unrecognized_url) + " " + url, Snackbar.LENGTH_SHORT).show();
5554 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5559 // Check requests against the block lists. The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
5561 public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest webResourceRequest) {
5563 String url = webResourceRequest.getUrl().toString();
5565 // Check to see if the resource request is for the main URL.
5566 if (url.equals(nestedScrollWebView.getCurrentUrl())) {
5567 // `return null` loads the resource request, which should never be blocked if it is the main URL.
5571 // 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.
5572 while (ultraPrivacy == null) {
5573 // The wait must be synchronized, which only lets one thread run on it at a time, or `java.lang.IllegalMonitorStateException` is thrown.
5574 synchronized (this) {
5576 // Check to see if the blocklists have been populated after 100 ms.
5578 } catch (InterruptedException exception) {
5584 // Create an empty web resource response to be used if the resource request is blocked.
5585 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
5587 // Reset the whitelist results tracker.
5588 String[] whitelistResultStringArray = null;
5590 // Initialize the third party request tracker.
5591 boolean isThirdPartyRequest = false;
5593 // Get the current URL. `.getUrl()` throws an error because operations on the WebView cannot be made from this thread.
5594 String currentBaseDomain = nestedScrollWebView.getCurrentDomainName();
5596 // Store a copy of the current domain for use in later requests.
5597 String currentDomain = currentBaseDomain;
5599 // Get the request host name.
5600 String requestBaseDomain = webResourceRequest.getUrl().getHost();
5602 // Only check for third-party requests if the current base domain is not empty and the request domain is not null.
5603 if (!currentBaseDomain.isEmpty() && (requestBaseDomain != null)) {
5604 // Determine the current base domain.
5605 while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
5606 // Remove the first subdomain.
5607 currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
5610 // Determine the request base domain.
5611 while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
5612 // Remove the first subdomain.
5613 requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
5616 // Update the third party request tracker.
5617 isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
5620 // Get the current WebView page position.
5621 int webViewPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5623 // Determine if the WebView is currently displayed.
5624 boolean webViewDisplayed = (webViewPagePosition == tabLayout.getSelectedTabPosition());
5626 // Block third-party requests if enabled.
5627 if (isThirdPartyRequest && nestedScrollWebView.getBlockAllThirdPartyRequests()) {
5628 // Add the result to the resource requests.
5629 nestedScrollWebView.addResourceRequest(new String[]{BlocklistHelper.REQUEST_THIRD_PARTY, url});
5631 // Increment the blocked requests counters.
5632 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5633 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS);
5635 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5636 if (webViewDisplayed) {
5637 // Updating the UI must be run from the UI thread.
5638 activity.runOnUiThread(() -> {
5639 // Update the menu item titles.
5640 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5642 // Update the options menu if it has been populated.
5643 if (optionsMenu != null) {
5644 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5645 optionsBlockAllThirdPartyRequestsMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " +
5646 getString(R.string.block_all_third_party_requests));
5651 // Return an empty web resource response.
5652 return emptyWebResourceResponse;
5655 // Check UltraList if it is enabled.
5656 if (nestedScrollWebView.getUltraListEnabled()) {
5657 // Check the URL against UltraList.
5658 String[] ultraListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraList);
5660 // Process the UltraList results.
5661 if (ultraListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched UltraList's blacklist.
5662 // Add the result to the resource requests.
5663 nestedScrollWebView.addResourceRequest(new String[] {ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]});
5665 // Increment the blocked requests counters.
5666 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5667 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRALIST);
5669 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5670 if (webViewDisplayed) {
5671 // Updating the UI must be run from the UI thread.
5672 activity.runOnUiThread(() -> {
5673 // Update the menu item titles.
5674 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5676 // Update the options menu if it has been populated.
5677 if (optionsMenu != null) {
5678 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5679 optionsUltraListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRALIST) + " - " + getString(R.string.ultralist));
5684 // The resource request was blocked. Return an empty web resource response.
5685 return emptyWebResourceResponse;
5686 } else if (ultraListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched UltraList's whitelist.
5687 // Add a whitelist entry to the resource requests array.
5688 nestedScrollWebView.addResourceRequest(new String[] {ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]});
5690 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
5695 // Check UltraPrivacy if it is enabled.
5696 if (nestedScrollWebView.getUltraPrivacyEnabled()) {
5697 // Check the URL against UltraPrivacy.
5698 String[] ultraPrivacyResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraPrivacy);
5700 // Process the UltraPrivacy results.
5701 if (ultraPrivacyResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched UltraPrivacy's blacklist.
5702 // Add the result to the resource requests.
5703 nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5704 ultraPrivacyResults[5]});
5706 // Increment the blocked requests counters.
5707 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5708 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRAPRIVACY);
5710 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5711 if (webViewDisplayed) {
5712 // Updating the UI must be run from the UI thread.
5713 activity.runOnUiThread(() -> {
5714 // Update the menu item titles.
5715 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5717 // Update the options menu if it has been populated.
5718 if (optionsMenu != null) {
5719 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5720 optionsUltraPrivacyMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRAPRIVACY) + " - " + getString(R.string.ultraprivacy));
5725 // The resource request was blocked. Return an empty web resource response.
5726 return emptyWebResourceResponse;
5727 } else if (ultraPrivacyResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched UltraPrivacy's whitelist.
5728 // Add a whitelist entry to the resource requests array.
5729 nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5730 ultraPrivacyResults[5]});
5732 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
5737 // Check EasyList if it is enabled.
5738 if (nestedScrollWebView.getEasyListEnabled()) {
5739 // Check the URL against EasyList.
5740 String[] easyListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyList);
5742 // Process the EasyList results.
5743 if (easyListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched EasyList's blacklist.
5744 // Add the result to the resource requests.
5745 nestedScrollWebView.addResourceRequest(new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]});
5747 // Increment the blocked requests counters.
5748 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5749 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASYLIST);
5751 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5752 if (webViewDisplayed) {
5753 // Updating the UI must be run from the UI thread.
5754 activity.runOnUiThread(() -> {
5755 // Update the menu item titles.
5756 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5758 // Update the options menu if it has been populated.
5759 if (optionsMenu != null) {
5760 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5761 optionsEasyListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASYLIST) + " - " + getString(R.string.easylist));
5766 // The resource request was blocked. Return an empty web resource response.
5767 return emptyWebResourceResponse;
5768 } else if (easyListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched EasyList's whitelist.
5769 // Update the whitelist result string array tracker.
5770 whitelistResultStringArray = new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]};
5774 // Check EasyPrivacy if it is enabled.
5775 if (nestedScrollWebView.getEasyPrivacyEnabled()) {
5776 // Check the URL against EasyPrivacy.
5777 String[] easyPrivacyResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyPrivacy);
5779 // Process the EasyPrivacy results.
5780 if (easyPrivacyResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched EasyPrivacy's blacklist.
5781 // Add the result to the resource requests.
5782 nestedScrollWebView.addResourceRequest(new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4],
5783 easyPrivacyResults[5]});
5785 // Increment the blocked requests counters.
5786 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5787 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASYPRIVACY);
5789 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5790 if (webViewDisplayed) {
5791 // Updating the UI must be run from the UI thread.
5792 activity.runOnUiThread(() -> {
5793 // Update the menu item titles.
5794 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5796 // Update the options menu if it has been populated.
5797 if (optionsMenu != null) {
5798 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5799 optionsEasyPrivacyMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASYPRIVACY) + " - " + getString(R.string.easyprivacy));
5804 // The resource request was blocked. Return an empty web resource response.
5805 return emptyWebResourceResponse;
5806 } else if (easyPrivacyResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched EasyPrivacy's whitelist.
5807 // Update the whitelist result string array tracker.
5808 whitelistResultStringArray = new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5]};
5812 // Check Fanboy’s Annoyance List if it is enabled.
5813 if (nestedScrollWebView.getFanboysAnnoyanceListEnabled()) {
5814 // Check the URL against Fanboy's Annoyance List.
5815 String[] fanboysAnnoyanceListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList);
5817 // Process the Fanboy's Annoyance List results.
5818 if (fanboysAnnoyanceListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched Fanboy's Annoyance List's blacklist.
5819 // Add the result to the resource requests.
5820 nestedScrollWebView.addResourceRequest(new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5821 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]});
5823 // Increment the blocked requests counters.
5824 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5825 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST);
5827 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5828 if (webViewDisplayed) {
5829 // Updating the UI must be run from the UI thread.
5830 activity.runOnUiThread(() -> {
5831 // Update the menu item titles.
5832 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5834 // Update the options menu if it has been populated.
5835 if (optionsMenu != null) {
5836 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5837 optionsFanboysAnnoyanceListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " +
5838 getString(R.string.fanboys_annoyance_list));
5843 // The resource request was blocked. Return an empty web resource response.
5844 return emptyWebResourceResponse;
5845 } else if (fanboysAnnoyanceListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)){ // The resource request matched Fanboy's Annoyance List's whitelist.
5846 // Update the whitelist result string array tracker.
5847 whitelistResultStringArray = new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5848 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]};
5850 } else if (nestedScrollWebView.getFanboysSocialBlockingListEnabled()) { // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
5851 // Check the URL against Fanboy's Annoyance List.
5852 String[] fanboysSocialListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysSocialList);
5854 // Process the Fanboy's Social Blocking List results.
5855 if (fanboysSocialListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched Fanboy's Social Blocking List's blacklist.
5856 // Add the result to the resource requests.
5857 nestedScrollWebView.addResourceRequest(new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5858 fanboysSocialListResults[4], fanboysSocialListResults[5]});
5860 // Increment the blocked requests counters.
5861 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5862 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST);
5864 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5865 if (webViewDisplayed) {
5866 // Updating the UI must be run from the UI thread.
5867 activity.runOnUiThread(() -> {
5868 // Update the menu item titles.
5869 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5871 // Update the options menu if it has been populated.
5872 if (optionsMenu != null) {
5873 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5874 optionsFanboysSocialBlockingListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " +
5875 getString(R.string.fanboys_social_blocking_list));
5880 // The resource request was blocked. Return an empty web resource response.
5881 return emptyWebResourceResponse;
5882 } else if (fanboysSocialListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched Fanboy's Social Blocking List's whitelist.
5883 // Update the whitelist result string array tracker.
5884 whitelistResultStringArray = new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5885 fanboysSocialListResults[4], fanboysSocialListResults[5]};
5889 // Add the request to the log because it hasn't been processed by any of the previous checks.
5890 if (whitelistResultStringArray != null) { // The request was processed by a whitelist.
5891 nestedScrollWebView.addResourceRequest(whitelistResultStringArray);
5892 } else { // The request didn't match any blocklist entry. Log it as a default request.
5893 nestedScrollWebView.addResourceRequest(new String[]{BlocklistHelper.REQUEST_DEFAULT, url});
5896 // The resource request has not been blocked. `return null` loads the requested resource.
5900 // Handle HTTP authentication requests.
5902 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
5903 // Store the handler.
5904 nestedScrollWebView.setHttpAuthHandler(handler);
5906 // Instantiate an HTTP authentication dialog.
5907 DialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm, nestedScrollWebView.getWebViewFragmentId());
5909 // Show the HTTP authentication dialog.
5910 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
5914 public void onPageStarted(WebView view, String url, Bitmap favicon) {
5915 // Get the app bar layout height. This can't be done in `applyAppSettings()` because the app bar is not yet populated there.
5916 // 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.
5917 if (appBarLayout.getHeight() > 0) appBarHeight = appBarLayout.getHeight();
5919 // Set the padding and layout settings according to the position of the app bar.
5920 if (bottomAppBar) { // The app bar is on the bottom.
5922 if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) { // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
5923 // Reset the WebView padding to fill the available space.
5924 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5925 } else { // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
5926 // Move the WebView above the app bar layout.
5927 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight);
5929 } else { // The app bar is on the top.
5930 // 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.
5931 if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) {
5932 // No padding is needed because it will automatically be placed below the app bar layout due to the scrolling layout behavior.
5933 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5935 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5936 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10, defaultProgressViewEndOffset);
5938 // The swipe refresh layout must be manually moved below the app bar layout.
5939 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0);
5941 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5942 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight);
5946 // Reset the list of resource requests.
5947 nestedScrollWebView.clearResourceRequests();
5949 // Reset the requests counters.
5950 nestedScrollWebView.resetRequestsCounters();
5952 // Get the current page position.
5953 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5955 // Update the URL text bar if the page is currently selected and the URL edit text is not currently being edited.
5956 if ((tabLayout.getSelectedTabPosition() == currentPagePosition) && !urlEditText.hasFocus()) {
5957 // Display the formatted URL text.
5958 urlEditText.setText(url);
5960 // Apply text highlighting to the URL text box.
5963 // Hide the keyboard.
5964 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
5967 // Reset the list of host IP addresses.
5968 nestedScrollWebView.setCurrentIpAddresses("");
5970 // Get a URI for the current URL.
5971 Uri currentUri = Uri.parse(url);
5973 // Get the IP addresses for the host.
5974 new GetHostIpAddresses(activity, getSupportFragmentManager(), nestedScrollWebView).execute(currentUri.getHost());
5976 // Replace Refresh with Stop if the options menu has been created. (The first WebView typically begins loading before the menu items are instantiated.)
5977 if (optionsMenu != null) {
5979 optionsRefreshMenuItem.setTitle(R.string.stop);
5981 // Get the app bar and theme preferences.
5982 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean(getString(R.string.display_additional_app_bar_icons_key), false);
5984 // Set the icon if it is displayed in the AppBar. Once the minimum API is >= 26, the blue and black icons can be combined with a tint list.
5985 if (displayAdditionalAppBarIcons) {
5986 optionsRefreshMenuItem.setIcon(R.drawable.close_blue);
5992 public void onPageFinished(WebView view, String url) {
5993 // Flush any cookies to persistent storage. The cookie manager has become very lazy about flushing cookies in recent versions.
5994 if (nestedScrollWebView.getAcceptCookies()) {
5995 CookieManager.getInstance().flush();
5998 // Update the Refresh menu item if the options menu has been created.
5999 if (optionsMenu != null) {
6000 // Reset the Refresh title.
6001 optionsRefreshMenuItem.setTitle(R.string.refresh);
6003 // Get the app bar and theme preferences.
6004 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean(getString(R.string.display_additional_app_bar_icons_key), false);
6006 // If the icon is displayed in the app bar, reset it according to the theme.
6007 if (displayAdditionalAppBarIcons) {
6009 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled);
6013 // Clear the cache, history, and logcat if Incognito Mode is enabled.
6014 if (incognitoModeEnabled) {
6015 // Clear the cache. `true` includes disk files.
6016 nestedScrollWebView.clearCache(true);
6018 // Clear the back/forward history.
6019 nestedScrollWebView.clearHistory();
6021 // Manually delete cache folders.
6023 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
6024 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
6025 String privateDataDirectoryString = getApplicationInfo().dataDir;
6027 // Delete the main cache directory.
6028 Runtime.getRuntime().exec("rm -rf " + privateDataDirectoryString + "/cache");
6030 // Delete the secondary `Service Worker` cache directory.
6031 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
6032 Runtime.getRuntime().exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
6033 } catch (IOException exception) {
6034 // Do nothing if an error is thrown.
6037 // Clear the logcat.
6039 // Clear the logcat. `-c` clears the logcat. `-b all` clears all the buffers (instead of just crash, main, and system).
6040 Runtime.getRuntime().exec("logcat -b all -c");
6041 } catch (IOException exception) {
6046 // Get the current page position.
6047 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
6049 // 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.
6050 String currentUrl = nestedScrollWebView.getUrl();
6052 // Get the current tab.
6053 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
6055 // Update the URL text bar if the page is currently selected and the user is not currently typing in the URL edit text.
6056 // Crash records show that, in some crazy way, it is possible for the current URL to be blank at this point.
6057 // Probably some sort of race condition when Privacy Browser is being resumed.
6058 if ((tabLayout.getSelectedTabPosition() == currentPagePosition) && !urlEditText.hasFocus() && (currentUrl != null)) {
6059 // Check to see if the URL is `about:blank`.
6060 if (currentUrl.equals("about:blank")) { // The WebView is blank.
6061 // Display the hint in the URL edit text.
6062 urlEditText.setText("");
6064 // Request focus for the URL text box.
6065 urlEditText.requestFocus();
6067 // Display the keyboard.
6068 inputMethodManager.showSoftInput(urlEditText, 0);
6070 // Apply the domain settings. This clears any settings from the previous domain.
6071 applyDomainSettings(nestedScrollWebView, "", true, false, false);
6073 // Only populate the title text view if the tab has been fully created.
6075 // Get the custom view from the tab.
6076 View tabView = tab.getCustomView();
6078 // Remove the incorrect warning below that the current tab view might be null.
6079 assert tabView != null;
6081 // Get the title text view from the tab.
6082 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
6084 // Set the title as the tab text.
6085 tabTitleTextView.setText(R.string.new_tab);
6087 } else { // The WebView has loaded a webpage.
6088 // Update the URL edit text if it is not currently being edited.
6089 if (!urlEditText.hasFocus()) {
6090 // 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.
6091 String sanitizedUrl = sanitizeUrl(currentUrl);
6093 // Display the final URL. Getting the URL from the WebView instead of using the one provided by `onPageFinished()` makes websites like YouTube function correctly.
6094 urlEditText.setText(sanitizedUrl);
6096 // Apply text highlighting to the URL.
6100 // Only populate the title text view if the tab has been fully created.
6102 // Get the custom view from the tab.
6103 View tabView = tab.getCustomView();
6105 // Remove the incorrect warning below that the current tab view might be null.
6106 assert tabView != null;
6108 // Get the title text view from the tab.
6109 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
6111 // Set the title as the tab text. Sometimes `onReceivedTitle()` is not called, especially when navigating history.
6112 tabTitleTextView.setText(nestedScrollWebView.getTitle());
6118 // Handle SSL Certificate errors. Suppress the lint warning that ignoring the error might be dangerous.
6119 @SuppressLint("WebViewClientOnReceivedSslError")
6121 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
6122 // Get the current website SSL certificate.
6123 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
6125 // Extract the individual pieces of information from the current website SSL certificate.
6126 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
6127 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
6128 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
6129 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
6130 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
6131 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
6132 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
6133 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
6135 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
6136 if (nestedScrollWebView.hasPinnedSslCertificate()) {
6137 // Get the pinned SSL certificate.
6138 Pair<String[], Date[]> pinnedSslCertificatePair = nestedScrollWebView.getPinnedSslCertificate();
6140 // Extract the arrays from the array list.
6141 String[] pinnedSslCertificateStringArray = pinnedSslCertificatePair.getFirst();
6142 Date[] pinnedSslCertificateDateArray = pinnedSslCertificatePair.getSecond();
6144 // Check if the current SSL certificate matches the pinned certificate.
6145 if (currentWebsiteIssuedToCName.equals(pinnedSslCertificateStringArray[0]) && currentWebsiteIssuedToOName.equals(pinnedSslCertificateStringArray[1]) &&
6146 currentWebsiteIssuedToUName.equals(pinnedSslCertificateStringArray[2]) && currentWebsiteIssuedByCName.equals(pinnedSslCertificateStringArray[3]) &&
6147 currentWebsiteIssuedByOName.equals(pinnedSslCertificateStringArray[4]) && currentWebsiteIssuedByUName.equals(pinnedSslCertificateStringArray[5]) &&
6148 currentWebsiteSslStartDate.equals(pinnedSslCertificateDateArray[0]) && currentWebsiteSslEndDate.equals(pinnedSslCertificateDateArray[1])) {
6150 // An SSL certificate is pinned and matches the current domain certificate. Proceed to the website without displaying an error.
6153 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
6154 // Store the SSL error handler.
6155 nestedScrollWebView.setSslErrorHandler(handler);
6157 // Instantiate an SSL certificate error alert dialog.
6158 DialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error, nestedScrollWebView.getWebViewFragmentId());
6160 // 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.
6162 // Show the SSL certificate error dialog.
6163 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
6164 } catch (Exception exception) {
6165 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
6166 pendingDialogsArrayList.add(new PendingDialog(sslCertificateErrorDialogFragment, getString(R.string.ssl_certificate_error)));
6172 // Check to see if the state is being restored.
6173 if (restoringState) { // The state is being restored.
6174 // Resume the nested scroll WebView JavaScript timers.
6175 nestedScrollWebView.resumeTimers();
6176 } else if (pageNumber == 0) { // The first page is being loaded.
6177 // Set this nested scroll WebView as the current WebView.
6178 currentWebView = nestedScrollWebView;
6180 // Initialize the URL to load string.
6181 String urlToLoadString;
6183 // Get the intent that started the app.
6184 Intent launchingIntent = getIntent();
6186 // Reset the intent. This prevents a duplicate tab from being created on restart.
6187 setIntent(new Intent());
6189 // Get the information from the intent.
6190 String launchingIntentAction = launchingIntent.getAction();
6191 Uri launchingIntentUriData = launchingIntent.getData();
6192 String launchingIntentStringExtra = launchingIntent.getStringExtra(Intent.EXTRA_TEXT);
6194 // Parse the launching intent URL.
6195 if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) { // The intent contains a search string.
6196 // Create an encoded URL string.
6197 String encodedUrlString;
6199 // Sanitize the search input and convert it to a search.
6201 encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
6202 } catch (UnsupportedEncodingException exception) {
6203 encodedUrlString = "";
6206 // Store the web search as the URL to load.
6207 urlToLoadString = searchURL + encodedUrlString;
6208 } else if (launchingIntentUriData != null) { // The launching intent contains a URL formatted as a URI.
6209 // Store the URI as a URL.
6210 urlToLoadString = launchingIntentUriData.toString();
6211 } else if (launchingIntentStringExtra != null) { // The launching intent contains text that might be a URL.
6213 urlToLoadString = launchingIntentStringExtra;
6214 } else if (!url.equals("")) { // The activity has been restarted.
6215 // Load the saved URL.
6216 urlToLoadString = url;
6217 } else { // The is no URL in the intent.
6218 // Store the homepage to be loaded.
6219 urlToLoadString = sharedPreferences.getString("homepage", getString(R.string.homepage_default_value));
6222 // Load the website if not waiting for the proxy.
6223 if (waitingForProxy) { // Store the URL to be loaded in the Nested Scroll WebView.
6224 nestedScrollWebView.setWaitingForProxyUrlString(urlToLoadString);
6225 } else { // Load the URL.
6226 loadUrl(nestedScrollWebView, urlToLoadString);
6229 // 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.
6230 // 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.
6231 setIntent(new Intent());
6232 } else { // This is not the first tab.
6234 loadUrl(nestedScrollWebView, url);
6236 // Set the focus and display the keyboard if the URL is blank.
6237 if (url.equals("")) {
6238 // Request focus for the URL text box.
6239 urlEditText.requestFocus();
6241 // Create a display keyboard handler.
6242 Handler displayKeyboardHandler = new Handler();
6244 // Create a display keyboard runnable.
6245 Runnable displayKeyboardRunnable = () -> {
6246 // Display the keyboard.
6247 inputMethodManager.showSoftInput(urlEditText, 0);
6250 // Display the keyboard after 100 milliseconds, which leaves enough time for the tab to transition.
6251 displayKeyboardHandler.postDelayed(displayKeyboardRunnable, 100);