2 * Copyright © 2015-2021 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 <https://www.stoutner.com/privacy-browser>.
8 * Privacy Browser is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
13 * Privacy Browser is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with Privacy Browser. If not, see <http://www.gnu.org/licenses/>.
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.WebResourceResponse;
83 import android.webkit.WebSettings;
84 import android.webkit.WebStorage;
85 import android.webkit.WebView;
86 import android.webkit.WebViewClient;
87 import android.webkit.WebViewDatabase;
88 import android.widget.ArrayAdapter;
89 import android.widget.CheckBox;
90 import android.widget.CursorAdapter;
91 import android.widget.EditText;
92 import android.widget.FrameLayout;
93 import android.widget.ImageView;
94 import android.widget.LinearLayout;
95 import android.widget.ListView;
96 import android.widget.ProgressBar;
97 import android.widget.RadioButton;
98 import android.widget.RelativeLayout;
99 import android.widget.TextView;
101 import androidx.activity.result.ActivityResultCallback;
102 import androidx.activity.result.ActivityResultLauncher;
103 import androidx.activity.result.contract.ActivityResultContracts;
104 import androidx.annotation.NonNull;
105 import androidx.appcompat.app.ActionBar;
106 import androidx.appcompat.app.ActionBarDrawerToggle;
107 import androidx.appcompat.app.AppCompatActivity;
108 import androidx.appcompat.app.AppCompatDelegate;
109 import androidx.appcompat.widget.Toolbar;
110 import androidx.coordinatorlayout.widget.CoordinatorLayout;
111 import androidx.core.content.res.ResourcesCompat;
112 import androidx.core.view.GravityCompat;
113 import androidx.drawerlayout.widget.DrawerLayout;
114 import androidx.fragment.app.DialogFragment;
115 import androidx.fragment.app.Fragment;
116 import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
117 import androidx.viewpager.widget.ViewPager;
118 import androidx.webkit.WebSettingsCompat;
119 import androidx.webkit.WebViewFeature;
121 import com.google.android.material.appbar.AppBarLayout;
122 import com.google.android.material.floatingactionbutton.FloatingActionButton;
123 import com.google.android.material.navigation.NavigationView;
124 import com.google.android.material.snackbar.Snackbar;
125 import com.google.android.material.tabs.TabLayout;
127 import com.stoutner.privacybrowser.R;
128 import com.stoutner.privacybrowser.adapters.WebViewPagerAdapter;
129 import com.stoutner.privacybrowser.asynctasks.GetHostIpAddresses;
130 import com.stoutner.privacybrowser.asynctasks.PopulateBlocklists;
131 import com.stoutner.privacybrowser.asynctasks.PrepareSaveDialog;
132 import com.stoutner.privacybrowser.asynctasks.SaveUrl;
133 import com.stoutner.privacybrowser.asynctasks.SaveWebpageImage;
134 import com.stoutner.privacybrowser.dataclasses.PendingDialog;
135 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
136 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
137 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
138 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
139 import com.stoutner.privacybrowser.dialogs.FontSizeDialog;
140 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
141 import com.stoutner.privacybrowser.dialogs.OpenDialog;
142 import com.stoutner.privacybrowser.dialogs.ProxyNotInstalledDialog;
143 import com.stoutner.privacybrowser.dialogs.PinnedMismatchDialog;
144 import com.stoutner.privacybrowser.dialogs.SaveDialog;
145 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
146 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
147 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
148 import com.stoutner.privacybrowser.dialogs.WaitingForProxyDialog;
149 import com.stoutner.privacybrowser.fragments.WebViewTabFragment;
150 import com.stoutner.privacybrowser.helpers.BlocklistHelper;
151 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
152 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
153 import com.stoutner.privacybrowser.helpers.ProxyHelper;
154 import com.stoutner.privacybrowser.views.NestedScrollWebView;
156 import java.io.ByteArrayInputStream;
157 import java.io.ByteArrayOutputStream;
159 import java.io.FileInputStream;
160 import java.io.FileOutputStream;
161 import java.io.IOException;
162 import java.io.InputStream;
163 import java.io.OutputStream;
164 import java.io.UnsupportedEncodingException;
166 import java.net.MalformedURLException;
168 import java.net.URLDecoder;
169 import java.net.URLEncoder;
171 import java.text.NumberFormat;
173 import java.util.ArrayList;
174 import java.util.Date;
175 import java.util.HashMap;
176 import java.util.HashSet;
177 import java.util.List;
178 import java.util.Map;
179 import java.util.Objects;
180 import java.util.Set;
181 import java.util.concurrent.ExecutorService;
182 import java.util.concurrent.Executors;
184 public class MainWebViewActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener,
185 EditBookmarkFolderDialog.EditBookmarkFolderListener, FontSizeDialog.UpdateFontSizeListener, NavigationView.OnNavigationItemSelectedListener, OpenDialog.OpenListener,
186 PinnedMismatchDialog.PinnedMismatchListener, PopulateBlocklists.PopulateBlocklistsListener, SaveDialog.SaveListener, UrlHistoryDialog.NavigateHistoryListener,
187 WebViewTabFragment.NewTabListener {
189 // Define the public static variables.
190 public static ExecutorService executorService = Executors.newFixedThreadPool(4);
191 public static String orbotStatus = "unknown";
192 public static ArrayList<PendingDialog> pendingDialogsArrayList = new ArrayList<>();
193 public static String proxyMode = ProxyHelper.NONE;
195 // Declare the public static variables.
196 public static String currentBookmarksFolder;
197 public static boolean restartFromBookmarksActivity;
198 public static WebViewPagerAdapter webViewPagerAdapter;
200 // Declare the public static views.
201 public static AppBarLayout appBarLayout;
203 // The user agent constants are public static so they can be accessed from `SettingsFragment`, `DomainsActivity`, and `DomainSettingsFragment`.
204 public final static int UNRECOGNIZED_USER_AGENT = -1;
205 public final static int SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1;
206 public final static int SETTINGS_CUSTOM_USER_AGENT = 12;
207 public final static int DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0;
208 public final static int DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2;
209 public final static int DOMAINS_CUSTOM_USER_AGENT = 13;
211 // Define the start activity for result request codes. The public static entry is accessed from `OpenDialog()`.
212 private final int BROWSE_FILE_UPLOAD_REQUEST_CODE = 0;
213 public final static int BROWSE_OPEN_REQUEST_CODE = 1;
215 // Define the saved instance state constants.
216 private final String SAVED_STATE_ARRAY_LIST = "saved_state_array_list";
217 private final String SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST = "saved_nested_scroll_webview_state_array_list";
218 private final String SAVED_TAB_POSITION = "saved_tab_position";
219 private final String PROXY_MODE = "proxy_mode";
221 // Define the saved instance state variables.
222 private ArrayList<Bundle> savedStateArrayList;
223 private ArrayList<Bundle> savedNestedScrollWebViewStateArrayList;
224 private int savedTabPosition;
225 private String savedProxyMode;
227 // Define the class variables.
228 @SuppressWarnings("rawtypes")
229 AsyncTask populateBlocklists;
231 // The current WebView is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
232 // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, `applyProxy()`, and `applyDomainSettings()`.
233 private NestedScrollWebView currentWebView;
235 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
236 private final Map<String, String> customHeaders = new HashMap<>();
238 // The search URL is set in `applyAppSettings()` and used in `onNewIntent()`, `loadUrlFromTextBox()`, `initializeApp()`, and `initializeWebView()`.
239 private String searchURL;
241 // The blocklists are populated in `finishedPopulatingBlocklists()` and accessed from `initializeWebView()`.
242 private ArrayList<List<String[]>> easyList;
243 private ArrayList<List<String[]>> easyPrivacy;
244 private ArrayList<List<String[]>> fanboysAnnoyanceList;
245 private ArrayList<List<String[]>> fanboysSocialList;
246 private ArrayList<List<String[]>> ultraList;
247 private ArrayList<List<String[]>> ultraPrivacy;
249 // The action bar drawer toggle is initialized in `onCreate()` and used in `onResume()`.
250 private ActionBarDrawerToggle actionBarDrawerToggle;
252 // The color spans are used in `onCreate()` and `highlightUrlText()`.
253 private ForegroundColorSpan redColorSpan;
254 private ForegroundColorSpan initialGrayColorSpan;
255 private ForegroundColorSpan finalGrayColorSpan;
257 // `bookmarksCursor` is used in `onDestroy()`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
258 private Cursor bookmarksCursor;
260 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
261 private CursorAdapter bookmarksCursorAdapter;
263 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
264 private String oldFolderNameString;
266 // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
267 private ValueCallback<Uri[]> fileChooserCallback;
269 // The default progress view offsets are set in `onCreate()` and used in `initializeWebView()`.
270 private int appBarHeight;
271 private int defaultProgressViewStartOffset;
272 private int defaultProgressViewEndOffset;
274 // The URL sanitizers are set in `applyAppSettings()` and used in `sanitizeUrl()`.
275 private boolean sanitizeGoogleAnalytics;
276 private boolean sanitizeFacebookClickIds;
277 private boolean sanitizeTwitterAmpRedirects;
279 // Declare the class variables
280 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
281 private boolean bottomAppBar;
282 private boolean displayingFullScreenVideo;
283 private boolean downloadWithExternalApp;
284 private boolean fullScreenBrowsingModeEnabled;
285 private boolean hideAppBar;
286 private boolean incognitoModeEnabled;
287 private boolean inFullScreenBrowsingMode;
288 private boolean loadingNewIntent;
289 private BroadcastReceiver orbotStatusBroadcastReceiver;
290 private ProxyHelper proxyHelper;
291 private boolean reapplyAppSettingsOnRestart;
292 private boolean reapplyDomainSettingsOnRestart;
293 private boolean scrollAppBar;
294 private boolean waitingForProxy;
295 private String webViewDefaultUserAgent;
297 // Define the class variables.
298 private ObjectAnimator objectAnimator = new ObjectAnimator();
299 private String saveUrlString = "";
301 // Declare the class views.
302 private FrameLayout rootFrameLayout;
303 private DrawerLayout drawerLayout;
304 private CoordinatorLayout coordinatorLayout;
305 private Toolbar toolbar;
306 private RelativeLayout urlRelativeLayout;
307 private EditText urlEditText;
308 private ActionBar actionBar;
309 private LinearLayout findOnPageLinearLayout;
310 private LinearLayout tabsLinearLayout;
311 private TabLayout tabLayout;
312 private SwipeRefreshLayout swipeRefreshLayout;
313 private ViewPager webViewPager;
314 private FrameLayout fullScreenVideoFrameLayout;
316 // Declare the class menus.
317 private Menu optionsMenu;
319 // Declare the class menu items.
320 private MenuItem navigationBackMenuItem;
321 private MenuItem navigationForwardMenuItem;
322 private MenuItem navigationHistoryMenuItem;
323 private MenuItem navigationRequestsMenuItem;
324 private MenuItem optionsPrivacyMenuItem;
325 private MenuItem optionsRefreshMenuItem;
326 private MenuItem optionsCookiesMenuItem;
327 private MenuItem optionsDomStorageMenuItem;
328 private MenuItem optionsSaveFormDataMenuItem;
329 private MenuItem optionsClearDataMenuItem;
330 private MenuItem optionsClearCookiesMenuItem;
331 private MenuItem optionsClearDomStorageMenuItem;
332 private MenuItem optionsClearFormDataMenuItem;
333 private MenuItem optionsBlocklistsMenuItem;
334 private MenuItem optionsEasyListMenuItem;
335 private MenuItem optionsEasyPrivacyMenuItem;
336 private MenuItem optionsFanboysAnnoyanceListMenuItem;
337 private MenuItem optionsFanboysSocialBlockingListMenuItem;
338 private MenuItem optionsUltraListMenuItem;
339 private MenuItem optionsUltraPrivacyMenuItem;
340 private MenuItem optionsBlockAllThirdPartyRequestsMenuItem;
341 private MenuItem optionsProxyMenuItem;
342 private MenuItem optionsProxyNoneMenuItem;
343 private MenuItem optionsProxyTorMenuItem;
344 private MenuItem optionsProxyI2pMenuItem;
345 private MenuItem optionsProxyCustomMenuItem;
346 private MenuItem optionsUserAgentMenuItem;
347 private MenuItem optionsUserAgentPrivacyBrowserMenuItem;
348 private MenuItem optionsUserAgentWebViewDefaultMenuItem;
349 private MenuItem optionsUserAgentFirefoxOnAndroidMenuItem;
350 private MenuItem optionsUserAgentChromeOnAndroidMenuItem;
351 private MenuItem optionsUserAgentSafariOnIosMenuItem;
352 private MenuItem optionsUserAgentFirefoxOnLinuxMenuItem;
353 private MenuItem optionsUserAgentChromiumOnLinuxMenuItem;
354 private MenuItem optionsUserAgentFirefoxOnWindowsMenuItem;
355 private MenuItem optionsUserAgentChromeOnWindowsMenuItem;
356 private MenuItem optionsUserAgentEdgeOnWindowsMenuItem;
357 private MenuItem optionsUserAgentInternetExplorerOnWindowsMenuItem;
358 private MenuItem optionsUserAgentSafariOnMacosMenuItem;
359 private MenuItem optionsUserAgentCustomMenuItem;
360 private MenuItem optionsSwipeToRefreshMenuItem;
361 private MenuItem optionsWideViewportMenuItem;
362 private MenuItem optionsDisplayImagesMenuItem;
363 private MenuItem optionsDarkWebViewMenuItem;
364 private MenuItem optionsFontSizeMenuItem;
365 private MenuItem optionsAddOrEditDomainMenuItem;
367 // This variable won't be needed once the class is migrated to Kotlin, as can be seen in LogcatActivity or AboutVersionFragment.
368 private Activity resultLauncherActivityHandle;
370 // Define the save URL activity result launcher. It must be defined before `onCreate()` is run or the app will crash.
371 private final ActivityResultLauncher<String> saveUrlActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.CreateDocument(),
372 new ActivityResultCallback<Uri>() {
374 public void onActivityResult(Uri fileUri) {
375 // Only save the URL if the file URI is not null, which happens if the user exited the file picker by pressing back.
376 if (fileUri != null) {
377 new SaveUrl(getApplicationContext(), resultLauncherActivityHandle, fileUri, currentWebView.getSettings().getUserAgentString(), currentWebView.getAcceptCookies()).execute(saveUrlString);
380 // Reset the save URL string.
385 // Define the save webpage archive activity result launcher. It must be defined before `onCreate()` is run or the app will crash.
386 private final ActivityResultLauncher<String> saveWebpageArchiveActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.CreateDocument(),
387 new ActivityResultCallback<Uri>() {
389 public void onActivityResult(Uri fileUri) {
390 // Only save the webpage archive if the file URI is not null, which happens if the user exited the file picker by pressing back.
391 if (fileUri != null) {
393 // Create a temporary MHT file.
394 File temporaryMhtFile = File.createTempFile("temporary_mht_file", ".mht", getCacheDir());
396 // Save the temporary MHT file.
397 currentWebView.saveWebArchive(temporaryMhtFile.toString(), false, callbackValue -> {
398 if (callbackValue != null) { // The temporary MHT file was saved successfully.
400 // Create a temporary MHT file input stream.
401 FileInputStream temporaryMhtFileInputStream = new FileInputStream(temporaryMhtFile);
403 // Get an output stream for the save webpage file path.
404 OutputStream mhtOutputStream = getContentResolver().openOutputStream(fileUri);
406 // Create a transfer byte array.
407 byte[] transferByteArray = new byte[1024];
409 // Create an integer to track the number of bytes read.
412 // Copy the temporary MHT file input stream to the MHT output stream.
413 while ((bytesRead = temporaryMhtFileInputStream.read(transferByteArray)) > 0) {
414 mhtOutputStream.write(transferByteArray, 0, bytesRead);
417 // Close the streams.
418 mhtOutputStream.close();
419 temporaryMhtFileInputStream.close();
421 // Initialize the file name string from the file URI last path segment.
422 String fileNameString = fileUri.getLastPathSegment();
424 // Query the exact file name if the API >= 26.
425 if (Build.VERSION.SDK_INT >= 26) {
426 // Get a cursor from the content resolver.
427 Cursor contentResolverCursor = resultLauncherActivityHandle.getContentResolver().query(fileUri, null, null, null);
429 // Move to the fist row.
430 contentResolverCursor.moveToFirst();
432 // Get the file name from the cursor.
433 fileNameString = contentResolverCursor.getString(contentResolverCursor.getColumnIndexOrThrow(OpenableColumns.DISPLAY_NAME));
436 contentResolverCursor.close();
439 // Display a snackbar.
440 Snackbar.make(currentWebView, getString(R.string.file_saved) + " " + fileNameString, Snackbar.LENGTH_SHORT).show();
441 } catch (Exception exception) {
442 // Display a snackbar with the exception.
443 Snackbar.make(currentWebView, getString(R.string.error_saving_file) + " " + exception.toString(), Snackbar.LENGTH_INDEFINITE).show();
445 // Delete the temporary MHT file.
446 //noinspection ResultOfMethodCallIgnored
447 temporaryMhtFile.delete();
449 } else { // There was an unspecified error while saving the temporary MHT file.
450 // Display an error snackbar.
451 Snackbar.make(currentWebView, getString(R.string.error_saving_file), Snackbar.LENGTH_INDEFINITE).show();
454 } catch (IOException ioException) {
455 // Display a snackbar with the IO exception.
456 Snackbar.make(currentWebView, getString(R.string.error_saving_file) + " " + ioException.toString(), Snackbar.LENGTH_INDEFINITE).show();
462 // Define the save webpage image activity result launcher. It must be defined before `onCreate()` is run or the app will crash.
463 private final ActivityResultLauncher<String> saveWebpageImageActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.CreateDocument(),
464 new ActivityResultCallback<Uri>() {
466 public void onActivityResult(Uri fileUri) {
467 // Only save the webpage image if the file URI is not null, which happens if the user exited the file picker by pressing back.
468 if (fileUri != null) {
469 // Save the webpage image.
470 new SaveWebpageImage(resultLauncherActivityHandle, fileUri, currentWebView).execute();
475 // Remove the warning about needing to override `performClick()` when using an `OnTouchListener` with WebView.
476 @SuppressLint("ClickableViewAccessibility")
478 protected void onCreate(Bundle savedInstanceState) {
479 // Run the default commands.
480 super.onCreate(savedInstanceState);
482 // Populate the result launcher activity. This will no longer be needed once the activity has transitioned to Kotlin.
483 resultLauncherActivityHandle = this;
485 // Check to see if the activity has been restarted.
486 if (savedInstanceState != null) {
487 // Store the saved instance state variables.
488 savedStateArrayList = savedInstanceState.getParcelableArrayList(SAVED_STATE_ARRAY_LIST);
489 savedNestedScrollWebViewStateArrayList = savedInstanceState.getParcelableArrayList(SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST);
490 savedTabPosition = savedInstanceState.getInt(SAVED_TAB_POSITION);
491 savedProxyMode = savedInstanceState.getString(PROXY_MODE);
494 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
495 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
497 // Get a handle for the shared preferences.
498 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
500 // Get the preferences.
501 String appTheme = sharedPreferences.getString("app_theme", getString(R.string.app_theme_default_value));
502 boolean allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false);
503 bottomAppBar = sharedPreferences.getBoolean(getString(R.string.bottom_app_bar_key), false);
505 // Get the theme entry values string array.
506 String[] appThemeEntryValuesStringArray = getResources().getStringArray(R.array.app_theme_entry_values);
508 // 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.
509 if (appTheme.equals(appThemeEntryValuesStringArray[1])) { // The light theme is selected.
510 // Apply the light theme.
511 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
512 } else if (appTheme.equals(appThemeEntryValuesStringArray[2])) { // The dark theme is selected.
513 // Apply the dark theme.
514 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
515 } else { // The system default theme is selected.
516 if (Build.VERSION.SDK_INT >= 28) { // The system default theme is supported.
517 // Follow the system default theme.
518 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
519 } else { // The system default theme is not supported.
520 // Follow the battery saver mode.
521 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY);
525 // Disable screenshots if not allowed.
526 if (!allowScreenshots) {
527 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
530 // 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.
531 if (Build.VERSION.SDK_INT >= 21) {
532 WebView.enableSlowWholeDocumentDraw();
536 setTheme(R.style.PrivacyBrowser);
538 // Set the content view.
540 setContentView(R.layout.main_framelayout_bottom_appbar);
542 setContentView(R.layout.main_framelayout_top_appbar);
545 // Get handles for the views.
546 rootFrameLayout = findViewById(R.id.root_framelayout);
547 drawerLayout = findViewById(R.id.drawerlayout);
548 coordinatorLayout = findViewById(R.id.coordinatorlayout);
549 appBarLayout = findViewById(R.id.appbar_layout);
550 toolbar = findViewById(R.id.toolbar);
551 findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
552 tabsLinearLayout = findViewById(R.id.tabs_linearlayout);
553 tabLayout = findViewById(R.id.tablayout);
554 swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
555 webViewPager = findViewById(R.id.webviewpager);
556 NavigationView navigationView = findViewById(R.id.navigationview);
557 fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
559 // Get a handle for the navigation menu.
560 Menu navigationMenu = navigationView.getMenu();
562 // Get handles for the navigation menu items.
563 navigationBackMenuItem = navigationMenu.findItem(R.id.back);
564 navigationForwardMenuItem = navigationMenu.findItem(R.id.forward);
565 navigationHistoryMenuItem = navigationMenu.findItem(R.id.history);
566 navigationRequestsMenuItem = navigationMenu.findItem(R.id.requests);
568 // Listen for touches on the navigation menu.
569 navigationView.setNavigationItemSelectedListener(this);
571 // Get a handle for the app compat delegate.
572 AppCompatDelegate appCompatDelegate = getDelegate();
574 // Set the support action bar.
575 appCompatDelegate.setSupportActionBar(toolbar);
577 // Get a handle for the action bar.
578 actionBar = appCompatDelegate.getSupportActionBar();
580 // Remove the incorrect lint warning below that the action bar might be null.
581 assert actionBar != null;
583 // Add the custom layout, which shows the URL text bar.
584 actionBar.setCustomView(R.layout.url_app_bar);
585 actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
587 // Get handles for the views in the URL app bar.
588 urlRelativeLayout = findViewById(R.id.url_relativelayout);
589 urlEditText = findViewById(R.id.url_edittext);
591 // Create the hamburger icon at the start of the AppBar.
592 actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
594 // Initially disable the sliding drawers. They will be enabled once the blocklists are loaded.
595 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
597 // Initialize the web view pager adapter.
598 webViewPagerAdapter = new WebViewPagerAdapter(getSupportFragmentManager());
600 // Set the pager adapter on the web view pager.
601 webViewPager.setAdapter(webViewPagerAdapter);
603 // Store up to 100 tabs in memory.
604 webViewPager.setOffscreenPageLimit(100);
606 // Instantiate the proxy helper.
607 proxyHelper = new ProxyHelper();
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 // Only display the dark WebView menu item if API >= 21.
982 optionsDarkWebViewMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
984 // Get the shared preferences.
985 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
987 // Get the dark theme and app bar preferences.
988 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean(getString(R.string.display_additional_app_bar_icons_key), false);
990 // 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.
991 if (displayAdditionalAppBarIcons) {
992 optionsRefreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
993 bookmarksMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
994 optionsCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
995 } else { //Do not display the additional icons.
996 optionsRefreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
997 bookmarksMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
998 optionsCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1001 // Replace Refresh with Stop if a URL is already loading.
1002 if (currentWebView != null && currentWebView.getProgress() != 100) {
1004 optionsRefreshMenuItem.setTitle(R.string.stop);
1006 // Set the icon if it is displayed in the app bar.
1007 if (displayAdditionalAppBarIcons) {
1008 // Get the current theme status.
1009 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
1011 // Set the icon according to the current theme status.
1012 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
1013 optionsRefreshMenuItem.setIcon(R.drawable.close_blue_day);
1015 optionsRefreshMenuItem.setIcon(R.drawable.close_blue_night);
1025 public boolean onPrepareOptionsMenu(Menu menu) {
1026 // Get a handle for the cookie manager.
1027 CookieManager cookieManager = CookieManager.getInstance();
1029 // Initialize the current user agent string and the font size.
1030 String currentUserAgent = getString(R.string.user_agent_privacy_browser);
1033 // 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.
1034 if (currentWebView != null) {
1035 // Set the add or edit domain text.
1036 if (currentWebView.getDomainSettingsApplied()) {
1037 optionsAddOrEditDomainMenuItem.setTitle(R.string.edit_domain_settings);
1039 optionsAddOrEditDomainMenuItem.setTitle(R.string.add_domain_settings);
1042 // Get the current user agent from the WebView.
1043 currentUserAgent = currentWebView.getSettings().getUserAgentString();
1045 // Get the current font size from the
1046 fontSize = currentWebView.getSettings().getTextZoom();
1048 // Set the status of the menu item checkboxes.
1049 optionsDomStorageMenuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1050 optionsSaveFormDataMenuItem.setChecked(currentWebView.getSettings().getSaveFormData()); // Form data can be removed once the minimum API >= 26.
1051 optionsEasyListMenuItem.setChecked(currentWebView.getEasyListEnabled());
1052 optionsEasyPrivacyMenuItem.setChecked(currentWebView.getEasyPrivacyEnabled());
1053 optionsFanboysAnnoyanceListMenuItem.setChecked(currentWebView.getFanboysAnnoyanceListEnabled());
1054 optionsFanboysSocialBlockingListMenuItem.setChecked(currentWebView.getFanboysSocialBlockingListEnabled());
1055 optionsUltraListMenuItem.setChecked(currentWebView.getUltraListEnabled());
1056 optionsUltraPrivacyMenuItem.setChecked(currentWebView.getUltraPrivacyEnabled());
1057 optionsBlockAllThirdPartyRequestsMenuItem.setChecked(currentWebView.getBlockAllThirdPartyRequests());
1058 optionsSwipeToRefreshMenuItem.setChecked(currentWebView.getSwipeToRefresh());
1059 optionsWideViewportMenuItem.setChecked(currentWebView.getSettings().getUseWideViewPort());
1060 optionsDisplayImagesMenuItem.setChecked(currentWebView.getSettings().getLoadsImagesAutomatically());
1062 // Initialize the display names for the blocklists with the number of blocked requests.
1063 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
1064 optionsEasyListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASYLIST) + " - " + getString(R.string.easylist));
1065 optionsEasyPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASYPRIVACY) + " - " + getString(R.string.easyprivacy));
1066 optionsFanboysAnnoyanceListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " + getString(R.string.fanboys_annoyance_list));
1067 optionsFanboysSocialBlockingListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " + getString(R.string.fanboys_social_blocking_list));
1068 optionsUltraListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRALIST) + " - " + getString(R.string.ultralist));
1069 optionsUltraPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRAPRIVACY) + " - " + getString(R.string.ultraprivacy));
1070 optionsBlockAllThirdPartyRequestsMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " + getString(R.string.block_all_third_party_requests));
1072 // Enable DOM Storage if JavaScript is enabled.
1073 optionsDomStorageMenuItem.setEnabled(currentWebView.getSettings().getJavaScriptEnabled());
1075 // Set the checkbox status for dark WebView if the WebView supports it.
1076 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
1077 optionsDarkWebViewMenuItem.setChecked(WebSettingsCompat.getForceDark(currentWebView.getSettings()) == WebSettingsCompat.FORCE_DARK_ON);
1081 // Set the cookies menu item checked status.
1082 optionsCookiesMenuItem.setChecked(cookieManager.acceptCookie());
1084 // Enable Clear Cookies if there are any.
1085 optionsClearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1087 // 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`.
1088 String privateDataDirectoryString = getApplicationInfo().dataDir;
1090 // Get a count of the number of files in the Local Storage directory.
1091 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1092 int localStorageDirectoryNumberOfFiles = 0;
1093 if (localStorageDirectory.exists()) {
1094 // `Objects.requireNonNull` removes a lint warning that `localStorageDirectory.list` might produce a null pointed exception if it is dereferenced.
1095 localStorageDirectoryNumberOfFiles = Objects.requireNonNull(localStorageDirectory.list()).length;
1098 // Get a count of the number of files in the IndexedDB directory.
1099 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1100 int indexedDBDirectoryNumberOfFiles = 0;
1101 if (indexedDBDirectory.exists()) {
1102 // `Objects.requireNonNull` removes a lint warning that `indexedDBDirectory.list` might produce a null pointed exception if it is dereferenced.
1103 indexedDBDirectoryNumberOfFiles = Objects.requireNonNull(indexedDBDirectory.list()).length;
1106 // Enable Clear DOM Storage if there is any.
1107 optionsClearDomStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1109 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
1110 if (Build.VERSION.SDK_INT < 26) {
1111 // Get the WebView database.
1112 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1114 // Enable the clear form data menu item if there is anything to clear.
1115 optionsClearFormDataMenuItem.setEnabled(webViewDatabase.hasFormData());
1118 // Enable Clear Data if any of the submenu items are enabled.
1119 optionsClearDataMenuItem.setEnabled(optionsClearCookiesMenuItem.isEnabled() || optionsClearDomStorageMenuItem.isEnabled() || optionsClearFormDataMenuItem.isEnabled());
1121 // Disable Fanboy's Social Blocking List menu item if Fanboy's Annoyance List is checked.
1122 optionsFanboysSocialBlockingListMenuItem.setEnabled(!optionsFanboysAnnoyanceListMenuItem.isChecked());
1124 // Set the proxy title and check the applied proxy.
1125 switch (proxyMode) {
1126 case ProxyHelper.NONE:
1127 // Set the proxy title.
1128 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_none));
1130 // Check the proxy None radio button.
1131 optionsProxyNoneMenuItem.setChecked(true);
1134 case ProxyHelper.TOR:
1135 // Set the proxy title.
1136 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_tor));
1138 // Check the proxy Tor radio button.
1139 optionsProxyTorMenuItem.setChecked(true);
1142 case ProxyHelper.I2P:
1143 // Set the proxy title.
1144 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_i2p));
1146 // Check the proxy I2P radio button.
1147 optionsProxyI2pMenuItem.setChecked(true);
1150 case ProxyHelper.CUSTOM:
1151 // Set the proxy title.
1152 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_custom));
1154 // Check the proxy Custom radio button.
1155 optionsProxyCustomMenuItem.setChecked(true);
1159 // Select the current user agent menu item. A switch statement cannot be used because the user agents are not compile time constants.
1160 if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) { // Privacy Browser.
1161 // Update the user agent menu item title.
1162 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_privacy_browser));
1164 // Select the Privacy Browser radio box.
1165 optionsUserAgentPrivacyBrowserMenuItem.setChecked(true);
1166 } else if (currentUserAgent.equals(webViewDefaultUserAgent)) { // WebView Default.
1167 // Update the user agent menu item title.
1168 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_webview_default));
1170 // Select the WebView Default radio box.
1171 optionsUserAgentWebViewDefaultMenuItem.setChecked(true);
1172 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) { // Firefox on Android.
1173 // Update the user agent menu item title.
1174 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_android));
1176 // Select the Firefox on Android radio box.
1177 optionsUserAgentFirefoxOnAndroidMenuItem.setChecked(true);
1178 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) { // Chrome on Android.
1179 // Update the user agent menu item title.
1180 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_android));
1182 // Select the Chrome on Android radio box.
1183 optionsUserAgentChromeOnAndroidMenuItem.setChecked(true);
1184 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) { // Safari on iOS.
1185 // Update the user agent menu item title.
1186 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_ios));
1188 // Select the Safari on iOS radio box.
1189 optionsUserAgentSafariOnIosMenuItem.setChecked(true);
1190 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) { // Firefox on Linux.
1191 // Update the user agent menu item title.
1192 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_linux));
1194 // Select the Firefox on Linux radio box.
1195 optionsUserAgentFirefoxOnLinuxMenuItem.setChecked(true);
1196 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) { // Chromium on Linux.
1197 // Update the user agent menu item title.
1198 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chromium_on_linux));
1200 // Select the Chromium on Linux radio box.
1201 optionsUserAgentChromiumOnLinuxMenuItem.setChecked(true);
1202 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) { // Firefox on Windows.
1203 // Update the user agent menu item title.
1204 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_windows));
1206 // Select the Firefox on Windows radio box.
1207 optionsUserAgentFirefoxOnWindowsMenuItem.setChecked(true);
1208 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) { // Chrome on Windows.
1209 // Update the user agent menu item title.
1210 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_windows));
1212 // Select the Chrome on Windows radio box.
1213 optionsUserAgentChromeOnWindowsMenuItem.setChecked(true);
1214 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) { // Edge on Windows.
1215 // Update the user agent menu item title.
1216 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_edge_on_windows));
1218 // Select the Edge on Windows radio box.
1219 optionsUserAgentEdgeOnWindowsMenuItem.setChecked(true);
1220 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) { // Internet Explorer on Windows.
1221 // Update the user agent menu item title.
1222 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_internet_explorer_on_windows));
1224 // Select the Internet on Windows radio box.
1225 optionsUserAgentInternetExplorerOnWindowsMenuItem.setChecked(true);
1226 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) { // Safari on macOS.
1227 // Update the user agent menu item title.
1228 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_macos));
1230 // Select the Safari on macOS radio box.
1231 optionsUserAgentSafariOnMacosMenuItem.setChecked(true);
1232 } else { // Custom user agent.
1233 // Update the user agent menu item title.
1234 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_custom));
1236 // Select the Custom radio box.
1237 optionsUserAgentCustomMenuItem.setChecked(true);
1240 // Set the font size title.
1241 optionsFontSizeMenuItem.setTitle(getString(R.string.font_size) + " - " + fontSize + "%");
1243 // Run all the other default commands.
1244 super.onPrepareOptionsMenu(menu);
1246 // Display the menu.
1251 public boolean onOptionsItemSelected(MenuItem menuItem) {
1252 // Get a handle for the shared preferences.
1253 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1255 // Get a handle for the cookie manager.
1256 CookieManager cookieManager = CookieManager.getInstance();
1258 // Get the selected menu item ID.
1259 int menuItemId = menuItem.getItemId();
1261 // Run the commands that correlate to the selected menu item.
1262 if (menuItemId == R.id.javascript) { // JavaScript.
1263 // Toggle the JavaScript status.
1264 currentWebView.getSettings().setJavaScriptEnabled(!currentWebView.getSettings().getJavaScriptEnabled());
1266 // Update the privacy icon.
1267 updatePrivacyIcons(true);
1269 // Display a `Snackbar`.
1270 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScrip is enabled.
1271 Snackbar.make(webViewPager, R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1272 } else if (cookieManager.acceptCookie()) { // JavaScript is disabled, but first-party cookies are enabled.
1273 Snackbar.make(webViewPager, R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1274 } else { // Privacy mode.
1275 Snackbar.make(webViewPager, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1278 // Reload the current WebView.
1279 currentWebView.reload();
1281 // Consume the event.
1283 } else if (menuItemId == R.id.refresh) { // Refresh.
1284 // Run the command that correlates to the current status of the menu item.
1285 if (menuItem.getTitle().equals(getString(R.string.refresh))) { // The refresh button was pushed.
1286 // Reload the current WebView.
1287 currentWebView.reload();
1288 } else { // The stop button was pushed.
1289 // Stop the loading of the WebView.
1290 currentWebView.stopLoading();
1293 // Consume the event.
1295 } else if (menuItemId == R.id.bookmarks) { // Bookmarks.
1296 // Open the bookmarks drawer.
1297 drawerLayout.openDrawer(GravityCompat.END);
1299 // Consume the event.
1301 } else if (menuItemId == R.id.cookies) { // Cookies.
1302 // Switch the first-party cookie status.
1303 cookieManager.setAcceptCookie(!cookieManager.acceptCookie());
1305 // Store the cookie status.
1306 currentWebView.setAcceptCookies(cookieManager.acceptCookie());
1308 // Update the menu checkbox.
1309 menuItem.setChecked(cookieManager.acceptCookie());
1311 // Update the privacy icon.
1312 updatePrivacyIcons(true);
1314 // Display a snackbar.
1315 if (cookieManager.acceptCookie()) { // Cookies are enabled.
1316 Snackbar.make(webViewPager, R.string.cookies_enabled, Snackbar.LENGTH_SHORT).show();
1317 } else if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is still enabled.
1318 Snackbar.make(webViewPager, R.string.cookies_disabled, Snackbar.LENGTH_SHORT).show();
1319 } else { // Privacy mode.
1320 Snackbar.make(webViewPager, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1323 // Reload the current WebView.
1324 currentWebView.reload();
1326 // Consume the event.
1328 } else if (menuItemId == R.id.dom_storage) { // DOM storage.
1329 // Toggle the status of domStorageEnabled.
1330 currentWebView.getSettings().setDomStorageEnabled(!currentWebView.getSettings().getDomStorageEnabled());
1332 // Update the menu checkbox.
1333 menuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1335 // Update the privacy icon.
1336 updatePrivacyIcons(true);
1338 // Display a snackbar.
1339 if (currentWebView.getSettings().getDomStorageEnabled()) {
1340 Snackbar.make(webViewPager, R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1342 Snackbar.make(webViewPager, R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1345 // Reload the current WebView.
1346 currentWebView.reload();
1348 // Consume the event.
1350 } else if (menuItemId == R.id.save_form_data) { // Form data. This can be removed once the minimum API >= 26.
1351 // Switch the status of saveFormDataEnabled.
1352 currentWebView.getSettings().setSaveFormData(!currentWebView.getSettings().getSaveFormData());
1354 // Update the menu checkbox.
1355 menuItem.setChecked(currentWebView.getSettings().getSaveFormData());
1357 // Display a snackbar.
1358 if (currentWebView.getSettings().getSaveFormData()) {
1359 Snackbar.make(webViewPager, R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1361 Snackbar.make(webViewPager, R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1364 // Update the privacy icon.
1365 updatePrivacyIcons(true);
1367 // Reload the current WebView.
1368 currentWebView.reload();
1370 // Consume the event.
1372 } else if (menuItemId == R.id.clear_cookies) { // Clear cookies.
1373 // Create a snackbar.
1374 Snackbar.make(webViewPager, R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1375 .setAction(R.string.undo, v -> {
1376 // Do nothing because everything will be handled by `onDismissed()` below.
1378 .addCallback(new Snackbar.Callback() {
1380 public void onDismissed(Snackbar snackbar, int event) {
1381 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1382 // Delete the cookies, which command varies by SDK.
1383 if (Build.VERSION.SDK_INT < 21) {
1384 cookieManager.removeAllCookie();
1386 cookieManager.removeAllCookies(null);
1393 // Consume the event.
1395 } else if (menuItemId == R.id.clear_dom_storage) { // Clear DOM storage.
1396 // Create a snackbar.
1397 Snackbar.make(webViewPager, R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1398 .setAction(R.string.undo, v -> {
1399 // Do nothing because everything will be handled by `onDismissed()` below.
1401 .addCallback(new Snackbar.Callback() {
1403 public void onDismissed(Snackbar snackbar, int event) {
1404 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1405 // Delete the DOM Storage.
1406 WebStorage webStorage = WebStorage.getInstance();
1407 webStorage.deleteAllData();
1409 // Initialize a handler to manually delete the DOM storage files and directories.
1410 Handler deleteDomStorageHandler = new Handler();
1412 // Setup a runnable to manually delete the DOM storage files and directories.
1413 Runnable deleteDomStorageRunnable = () -> {
1415 // Get a handle for the runtime.
1416 Runtime runtime = Runtime.getRuntime();
1418 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
1419 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
1420 String privateDataDirectoryString = getApplicationInfo().dataDir;
1422 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1423 Process deleteLocalStorageProcess = runtime.exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1425 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1426 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1427 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1428 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1429 Process deleteDatabasesProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1431 // Wait for the processes to finish.
1432 deleteLocalStorageProcess.waitFor();
1433 deleteIndexProcess.waitFor();
1434 deleteQuotaManagerProcess.waitFor();
1435 deleteQuotaManagerJournalProcess.waitFor();
1436 deleteDatabasesProcess.waitFor();
1437 } catch (Exception exception) {
1438 // Do nothing if an error is thrown.
1442 // Manually delete the DOM storage files after 200 milliseconds.
1443 deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200);
1449 // Consume the event.
1451 } else if (menuItemId == R.id.clear_form_data) { // Clear form data. This can be remove once the minimum API >= 26.
1452 // Create a snackbar.
1453 Snackbar.make(webViewPager, R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1454 .setAction(R.string.undo, v -> {
1455 // Do nothing because everything will be handled by `onDismissed()` below.
1457 .addCallback(new Snackbar.Callback() {
1459 public void onDismissed(Snackbar snackbar, int event) {
1460 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1461 // Get a handle for the webView database.
1462 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1464 // Delete the form data.
1465 webViewDatabase.clearFormData();
1471 // Consume the event.
1473 } else if (menuItemId == R.id.easylist) { // EasyList.
1474 // Toggle the EasyList status.
1475 currentWebView.setEasyListEnabled(!currentWebView.getEasyListEnabled());
1477 // Update the menu checkbox.
1478 menuItem.setChecked(currentWebView.getEasyListEnabled());
1480 // Reload the current WebView.
1481 currentWebView.reload();
1483 // Consume the event.
1485 } else if (menuItemId == R.id.easyprivacy) { // EasyPrivacy.
1486 // Toggle the EasyPrivacy status.
1487 currentWebView.setEasyPrivacyEnabled(!currentWebView.getEasyPrivacyEnabled());
1489 // Update the menu checkbox.
1490 menuItem.setChecked(currentWebView.getEasyPrivacyEnabled());
1492 // Reload the current WebView.
1493 currentWebView.reload();
1495 // Consume the event.
1497 } else if (menuItemId == R.id.fanboys_annoyance_list) { // Fanboy's Annoyance List.
1498 // Toggle Fanboy's Annoyance List status.
1499 currentWebView.setFanboysAnnoyanceListEnabled(!currentWebView.getFanboysAnnoyanceListEnabled());
1501 // Update the menu checkbox.
1502 menuItem.setChecked(currentWebView.getFanboysAnnoyanceListEnabled());
1504 // Update the status of Fanboy's Social Blocking List.
1505 optionsFanboysSocialBlockingListMenuItem.setEnabled(!currentWebView.getFanboysAnnoyanceListEnabled());
1507 // Reload the current WebView.
1508 currentWebView.reload();
1510 // Consume the event.
1512 } else if (menuItemId == R.id.fanboys_social_blocking_list) { // Fanboy's Social Blocking List.
1513 // Toggle Fanboy's Social Blocking List status.
1514 currentWebView.setFanboysSocialBlockingListEnabled(!currentWebView.getFanboysSocialBlockingListEnabled());
1516 // Update the menu checkbox.
1517 menuItem.setChecked(currentWebView.getFanboysSocialBlockingListEnabled());
1519 // Reload the current WebView.
1520 currentWebView.reload();
1522 // Consume the event.
1524 } else if (menuItemId == R.id.ultralist) { // UltraList.
1525 // Toggle the UltraList status.
1526 currentWebView.setUltraListEnabled(!currentWebView.getUltraListEnabled());
1528 // Update the menu checkbox.
1529 menuItem.setChecked(currentWebView.getUltraListEnabled());
1531 // Reload the current WebView.
1532 currentWebView.reload();
1534 // Consume the event.
1536 } else if (menuItemId == R.id.ultraprivacy) { // UltraPrivacy.
1537 // Toggle the UltraPrivacy status.
1538 currentWebView.setUltraPrivacyEnabled(!currentWebView.getUltraPrivacyEnabled());
1540 // Update the menu checkbox.
1541 menuItem.setChecked(currentWebView.getUltraPrivacyEnabled());
1543 // Reload the current WebView.
1544 currentWebView.reload();
1546 // Consume the event.
1548 } else if (menuItemId == R.id.block_all_third_party_requests) { // Block all third-party requests.
1549 //Toggle the third-party requests blocker status.
1550 currentWebView.setBlockAllThirdPartyRequests(!currentWebView.getBlockAllThirdPartyRequests());
1552 // Update the menu checkbox.
1553 menuItem.setChecked(currentWebView.getBlockAllThirdPartyRequests());
1555 // Reload the current WebView.
1556 currentWebView.reload();
1558 // Consume the event.
1560 } else if (menuItemId == R.id.proxy_none) { // Proxy - None.
1561 // Update the proxy mode.
1562 proxyMode = ProxyHelper.NONE;
1564 // Apply the proxy mode.
1567 // Consume the event.
1569 } else if (menuItemId == R.id.proxy_tor) { // Proxy - Tor.
1570 // Update the proxy mode.
1571 proxyMode = ProxyHelper.TOR;
1573 // Apply the proxy mode.
1576 // Consume the event.
1578 } else if (menuItemId == R.id.proxy_i2p) { // Proxy - I2P.
1579 // Update the proxy mode.
1580 proxyMode = ProxyHelper.I2P;
1582 // Apply the proxy mode.
1585 // Consume the event.
1587 } else if (menuItemId == R.id.proxy_custom) { // Proxy - Custom.
1588 // Update the proxy mode.
1589 proxyMode = ProxyHelper.CUSTOM;
1591 // Apply the proxy mode.
1594 // Consume the event.
1596 } else if (menuItemId == R.id.user_agent_privacy_browser) { // User Agent - Privacy Browser.
1597 // Update the user agent.
1598 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
1600 // Reload the current WebView.
1601 currentWebView.reload();
1603 // Consume the event.
1605 } else if (menuItemId == R.id.user_agent_webview_default) { // User Agent - WebView Default.
1606 // Update the user agent.
1607 currentWebView.getSettings().setUserAgentString("");
1609 // Reload the current WebView.
1610 currentWebView.reload();
1612 // Consume the event.
1614 } else if (menuItemId == R.id.user_agent_firefox_on_android) { // User Agent - Firefox on Android.
1615 // Update the user agent.
1616 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
1618 // Reload the current WebView.
1619 currentWebView.reload();
1621 // Consume the event.
1623 } else if (menuItemId == R.id.user_agent_chrome_on_android) { // User Agent - Chrome on Android.
1624 // Update the user agent.
1625 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
1627 // Reload the current WebView.
1628 currentWebView.reload();
1630 // Consume the event.
1632 } else if (menuItemId == R.id.user_agent_safari_on_ios) { // User Agent - Safari on iOS.
1633 // Update the user agent.
1634 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
1636 // Reload the current WebView.
1637 currentWebView.reload();
1639 // Consume the event.
1641 } else if (menuItemId == R.id.user_agent_firefox_on_linux) { // User Agent - Firefox on Linux.
1642 // Update the user agent.
1643 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
1645 // Reload the current WebView.
1646 currentWebView.reload();
1648 // Consume the event.
1650 } else if (menuItemId == R.id.user_agent_chromium_on_linux) { // User Agent - Chromium on Linux.
1651 // Update the user agent.
1652 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
1654 // Reload the current WebView.
1655 currentWebView.reload();
1657 // Consume the event.
1659 } else if (menuItemId == R.id.user_agent_firefox_on_windows) { // User Agent - Firefox on Windows.
1660 // Update the user agent.
1661 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
1663 // Reload the current WebView.
1664 currentWebView.reload();
1666 // Consume the event.
1668 } else if (menuItemId == R.id.user_agent_chrome_on_windows) { // User Agent - Chrome on Windows.
1669 // Update the user agent.
1670 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
1672 // Reload the current WebView.
1673 currentWebView.reload();
1675 // Consume the event.
1677 } else if (menuItemId == R.id.user_agent_edge_on_windows) { // User Agent - Edge on Windows.
1678 // Update the user agent.
1679 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
1681 // Reload the current WebView.
1682 currentWebView.reload();
1684 // Consume the event.
1686 } else if (menuItemId == R.id.user_agent_internet_explorer_on_windows) { // User Agent - Internet Explorer on Windows.
1687 // Update the user agent.
1688 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
1690 // Reload the current WebView.
1691 currentWebView.reload();
1693 // Consume the event.
1695 } else if (menuItemId == R.id.user_agent_safari_on_macos) { // User Agent - Safari on macOS.
1696 // Update the user agent.
1697 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
1699 // Reload the current WebView.
1700 currentWebView.reload();
1702 // Consume the event.
1704 } else if (menuItemId == R.id.user_agent_custom) { // User Agent - Custom.
1705 // Update the user agent.
1706 currentWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
1708 // Reload the current WebView.
1709 currentWebView.reload();
1711 // Consume the event.
1713 } else if (menuItemId == R.id.font_size) { // Font size.
1714 // Instantiate the font size dialog.
1715 DialogFragment fontSizeDialogFragment = FontSizeDialog.displayDialog(currentWebView.getSettings().getTextZoom());
1717 // Show the font size dialog.
1718 fontSizeDialogFragment.show(getSupportFragmentManager(), getString(R.string.font_size));
1720 // Consume the event.
1722 } else if (menuItemId == R.id.swipe_to_refresh) { // Swipe to refresh.
1723 // Toggle the stored status of swipe to refresh.
1724 currentWebView.setSwipeToRefresh(!currentWebView.getSwipeToRefresh());
1726 // Update the swipe refresh layout.
1727 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
1728 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
1729 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
1730 } else { // Swipe to refresh is disabled.
1731 // Disable the swipe refresh layout.
1732 swipeRefreshLayout.setEnabled(false);
1735 // Consume the event.
1737 } else if (menuItemId == R.id.wide_viewport) { // Wide viewport.
1738 // Toggle the viewport.
1739 currentWebView.getSettings().setUseWideViewPort(!currentWebView.getSettings().getUseWideViewPort());
1741 // Consume the event.
1743 } else if (menuItemId == R.id.display_images) { // Display images.
1744 // Toggle the displaying of images.
1745 if (currentWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1746 // Disable loading of images.
1747 currentWebView.getSettings().setLoadsImagesAutomatically(false);
1749 // Reload the website to remove existing images.
1750 currentWebView.reload();
1751 } else { // Images are not currently loaded automatically.
1752 // Enable loading of images. Missing images will be loaded without the need for a reload.
1753 currentWebView.getSettings().setLoadsImagesAutomatically(true);
1756 // Consume the event.
1758 } else if (menuItemId == R.id.dark_webview) { // Dark WebView.
1759 // Check to see if dark WebView is supported by this WebView.
1760 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
1761 // Toggle the dark WebView setting.
1762 if (WebSettingsCompat.getForceDark(currentWebView.getSettings()) == WebSettingsCompat.FORCE_DARK_ON) { // Dark WebView is currently enabled.
1763 // Turn off dark WebView.
1764 WebSettingsCompat.setForceDark(currentWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
1765 } else { // Dark WebView is currently disabled.
1766 // Turn on dark WebView.
1767 WebSettingsCompat.setForceDark(currentWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
1771 // Consume the event.
1773 } else if (menuItemId == R.id.find_on_page) { // Find on page.
1774 // Get a handle for the views.
1775 Toolbar toolbar = findViewById(R.id.toolbar);
1776 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
1777 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
1779 // Set the minimum height of the find on page linear layout to match the toolbar.
1780 findOnPageLinearLayout.setMinimumHeight(toolbar.getHeight());
1782 // Hide the toolbar.
1783 toolbar.setVisibility(View.GONE);
1785 // Show the find on page linear layout.
1786 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1788 // Display the keyboard. The app must wait 200 ms before running the command to work around a bug in Android.
1789 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1790 findOnPageEditText.postDelayed(() -> {
1791 // Set the focus on the find on page edit text.
1792 findOnPageEditText.requestFocus();
1794 // Get a handle for the input method manager.
1795 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1797 // Remove the lint warning below that the input method manager might be null.
1798 assert inputMethodManager != null;
1800 // Display the keyboard. `0` sets no input flags.
1801 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1804 // Consume the event.
1806 } else if (menuItemId == R.id.print) { // Print.
1807 // Get a print manager instance.
1808 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1810 // Remove the lint error below that print manager might be null.
1811 assert printManager != null;
1813 // Create a print document adapter from the current WebView.
1814 PrintDocumentAdapter printDocumentAdapter = currentWebView.createPrintDocumentAdapter();
1816 // Print the document.
1817 printManager.print(getString(R.string.privacy_browser_webpage), printDocumentAdapter, null);
1819 // Consume the event.
1821 } else if (menuItemId == R.id.save_url) { // Save URL.
1822 // Check the download preference.
1823 if (downloadWithExternalApp) { // Download with an external app.
1824 downloadUrlWithExternalApp(currentWebView.getCurrentUrl());
1825 } else { // Handle the download inside of Privacy Browser.
1826 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
1827 new PrepareSaveDialog(this, this, getSupportFragmentManager(), currentWebView.getSettings().getUserAgentString(),
1828 currentWebView.getAcceptCookies()).execute(currentWebView.getCurrentUrl());
1831 // Consume the event.
1833 } else if (menuItemId == R.id.save_archive) {
1834 // Open the file picker with a default file name built from the current domain name.
1835 saveWebpageArchiveActivityResultLauncher.launch(currentWebView.getCurrentDomainName() + ".mht");
1837 // Consume the event.
1839 } else if (menuItemId == R.id.save_image) { // Save image.
1840 // Open the file picker with a default file name built from the current domain name.
1841 saveWebpageImageActivityResultLauncher.launch(currentWebView.getCurrentDomainName() + ".png");
1843 // Consume the event.
1845 } else if (menuItemId == R.id.add_to_homescreen) { // Add to homescreen.
1846 // Instantiate the create home screen shortcut dialog.
1847 DialogFragment createHomeScreenShortcutDialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView.getTitle(), currentWebView.getUrl(),
1848 currentWebView.getFavoriteOrDefaultIcon());
1850 // Show the create home screen shortcut dialog.
1851 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
1853 // Consume the event.
1855 } else if (menuItemId == R.id.view_source) { // View source.
1856 // Create an intent to launch the view source activity.
1857 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
1859 // Add the variables to the intent.
1860 viewSourceIntent.putExtra(ViewSourceActivityKt.CURRENT_URL, currentWebView.getUrl());
1861 viewSourceIntent.putExtra(ViewSourceActivityKt.USER_AGENT, currentWebView.getSettings().getUserAgentString());
1864 startActivity(viewSourceIntent);
1866 // Consume the event.
1868 } else if (menuItemId == R.id.share_url) { // Share URL.
1869 // Setup the share string.
1870 String shareString = currentWebView.getTitle() + " – " + currentWebView.getUrl();
1872 // Create the share intent.
1873 Intent shareIntent = new Intent(Intent.ACTION_SEND);
1875 // Add the share string to the intent.
1876 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1878 // Set the MIME type.
1879 shareIntent.setType("text/plain");
1881 // Set the intent to open in a new task.
1882 shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1885 startActivity(Intent.createChooser(shareIntent, getString(R.string.share_url)));
1887 // Consume the event.
1889 } else if (menuItemId == R.id.open_with_app) { // Open with app.
1890 // Open the URL with an outside app.
1891 openWithApp(currentWebView.getUrl());
1893 // Consume the event.
1895 } else if (menuItemId == R.id.open_with_browser) { // Open with browser.
1896 // Open the URL with an outside browser.
1897 openWithBrowser(currentWebView.getUrl());
1899 // Consume the event.
1901 } else if (menuItemId == R.id.add_or_edit_domain) { // Add or edit domain.
1902 // Check if domain settings currently exist.
1903 if (currentWebView.getDomainSettingsApplied()) { // Edit the current domain settings.
1904 // Reapply the domain settings on returning to `MainWebViewActivity`.
1905 reapplyDomainSettingsOnRestart = true;
1907 // Create an intent to launch the domains activity.
1908 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1910 // Add the extra information to the intent.
1911 domainsIntent.putExtra("load_domain", currentWebView.getDomainSettingsDatabaseId());
1912 domainsIntent.putExtra("close_on_back", true);
1913 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1914 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1916 // Get the current certificate.
1917 SslCertificate sslCertificate = currentWebView.getCertificate();
1919 // Check to see if the SSL certificate is populated.
1920 if (sslCertificate != null) {
1921 // Extract the certificate to strings.
1922 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1923 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1924 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1925 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1926 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1927 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1928 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1929 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1931 // Add the certificate to the intent.
1932 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1933 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1934 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1935 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1936 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1937 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1938 domainsIntent.putExtra("ssl_start_date", startDateLong);
1939 domainsIntent.putExtra("ssl_end_date", endDateLong);
1943 startActivity(domainsIntent);
1944 } else { // Add a new domain.
1945 // Apply the new domain settings on returning to `MainWebViewActivity`.
1946 reapplyDomainSettingsOnRestart = true;
1948 // Get the current domain
1949 Uri currentUri = Uri.parse(currentWebView.getUrl());
1950 String currentDomain = currentUri.getHost();
1952 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1953 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1955 // Create the domain and store the database ID.
1956 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1958 // Create an intent to launch the domains activity.
1959 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1961 // Add the extra information to the intent.
1962 domainsIntent.putExtra("load_domain", newDomainDatabaseId);
1963 domainsIntent.putExtra("close_on_back", true);
1964 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1965 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1967 // Get the current certificate.
1968 SslCertificate sslCertificate = currentWebView.getCertificate();
1970 // Check to see if the SSL certificate is populated.
1971 if (sslCertificate != null) {
1972 // Extract the certificate to strings.
1973 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1974 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1975 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1976 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1977 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1978 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1979 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1980 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1982 // Add the certificate to the intent.
1983 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1984 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1985 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1986 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1987 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1988 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1989 domainsIntent.putExtra("ssl_start_date", startDateLong);
1990 domainsIntent.putExtra("ssl_end_date", endDateLong);
1994 startActivity(domainsIntent);
1997 // Consume the event.
1999 } else { // There is no match with the options menu. Pass the event up to the parent method.
2000 // Don't consume the event.
2001 return super.onOptionsItemSelected(menuItem);
2005 // removeAllCookies is deprecated, but it is required for API < 21.
2007 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2008 // Get a handle for the shared preferences.
2009 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2011 // Get the menu item ID.
2012 int menuItemId = menuItem.getItemId();
2014 // Run the commands that correspond to the selected menu item.
2015 if (menuItemId == R.id.clear_and_exit) { // Clear and exit.
2016 // Clear and exit Privacy Browser.
2018 } else if (menuItemId == R.id.home) { // Home.
2019 // Load the homepage.
2020 loadUrl(currentWebView, sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
2021 } else if (menuItemId == R.id.back) { // Back.
2022 // Check if the WebView can go back.
2023 if (currentWebView.canGoBack()) {
2024 // Get the current web back forward list.
2025 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
2027 // Get the previous entry URL.
2028 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
2030 // Apply the domain settings.
2031 applyDomainSettings(currentWebView, previousUrl, false, false, false);
2033 // Load the previous website in the history.
2034 currentWebView.goBack();
2036 } else if (menuItemId == R.id.forward) { // Forward.
2037 // Check if the WebView can go forward.
2038 if (currentWebView.canGoForward()) {
2039 // Get the current web back forward list.
2040 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
2042 // Get the next entry URL.
2043 String nextUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() + 1).getUrl();
2045 // Apply the domain settings.
2046 applyDomainSettings(currentWebView, nextUrl, false, false, false);
2048 // Load the next website in the history.
2049 currentWebView.goForward();
2051 } else if (menuItemId == R.id.history) { // History.
2052 // Instantiate the URL history dialog.
2053 DialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(currentWebView.getWebViewFragmentId());
2055 // Show the URL history dialog.
2056 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2057 } else if (menuItemId == R.id.open) { // Open.
2058 // Instantiate the open file dialog.
2059 DialogFragment openDialogFragment = new OpenDialog();
2061 // Show the open file dialog.
2062 openDialogFragment.show(getSupportFragmentManager(), getString(R.string.open));
2063 } else if (menuItemId == R.id.requests) { // Requests.
2064 // Populate the resource requests.
2065 RequestsActivity.resourceRequests = currentWebView.getResourceRequests();
2067 // Create an intent to launch the Requests activity.
2068 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2070 // Add the block third-party requests status to the intent.
2071 requestsIntent.putExtra("block_all_third_party_requests", currentWebView.getBlockAllThirdPartyRequests());
2074 startActivity(requestsIntent);
2075 } else if (menuItemId == R.id.downloads) { // Downloads.
2076 // Try the default system download manager.
2078 // Launch the default system Download Manager.
2079 Intent defaultDownloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2081 // Launch as a new task so that the download manager and Privacy Browser show as separate windows in the recent tasks list.
2082 defaultDownloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2085 startActivity(defaultDownloadManagerIntent);
2086 } catch (Exception defaultDownloadManagerException) {
2087 // Try a generic file manager.
2089 // Create a generic file manager intent.
2090 Intent genericFileManagerIntent = new Intent(Intent.ACTION_VIEW);
2092 // Open the download directory.
2093 genericFileManagerIntent.setDataAndType(Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()), DocumentsContract.Document.MIME_TYPE_DIR);
2095 // Launch as a new task so that the file manager and Privacy Browser show as separate windows in the recent tasks list.
2096 genericFileManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2099 startActivity(genericFileManagerIntent);
2100 } catch (Exception genericFileManagerException) {
2101 // Try an alternate file manager.
2103 // Create an alternate file manager intent.
2104 Intent alternateFileManagerIntent = new Intent(Intent.ACTION_VIEW);
2106 // Open the download directory.
2107 alternateFileManagerIntent.setDataAndType(Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()), "resource/folder");
2109 // Launch as a new task so that the file manager and Privacy Browser show as separate windows in the recent tasks list.
2110 alternateFileManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2112 // Open the alternate file manager.
2113 startActivity(alternateFileManagerIntent);
2114 } catch (Exception alternateFileManagerException) {
2115 // Display a snackbar.
2116 Snackbar.make(currentWebView, R.string.no_file_manager_detected, Snackbar.LENGTH_INDEFINITE).show();
2120 } else if (menuItemId == R.id.domains) { // Domains.
2121 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2122 reapplyDomainSettingsOnRestart = true;
2124 // Launch the domains activity.
2125 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2127 // Add the extra information to the intent.
2128 domainsIntent.putExtra("current_url", currentWebView.getUrl());
2129 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
2131 // Get the current certificate.
2132 SslCertificate sslCertificate = currentWebView.getCertificate();
2134 // Check to see if the SSL certificate is populated.
2135 if (sslCertificate != null) {
2136 // Extract the certificate to strings.
2137 String issuedToCName = sslCertificate.getIssuedTo().getCName();
2138 String issuedToOName = sslCertificate.getIssuedTo().getOName();
2139 String issuedToUName = sslCertificate.getIssuedTo().getUName();
2140 String issuedByCName = sslCertificate.getIssuedBy().getCName();
2141 String issuedByOName = sslCertificate.getIssuedBy().getOName();
2142 String issuedByUName = sslCertificate.getIssuedBy().getUName();
2143 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
2144 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
2146 // Add the certificate to the intent.
2147 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
2148 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
2149 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
2150 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
2151 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
2152 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
2153 domainsIntent.putExtra("ssl_start_date", startDateLong);
2154 domainsIntent.putExtra("ssl_end_date", endDateLong);
2158 startActivity(domainsIntent);
2159 } else if (menuItemId == R.id.settings) { // Settings.
2160 // Set the flag to reapply app settings on restart when returning from Settings.
2161 reapplyAppSettingsOnRestart = true;
2163 // Set the flag to reapply the domain settings on restart when returning from Settings.
2164 reapplyDomainSettingsOnRestart = true;
2166 // Launch the settings activity.
2167 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2168 startActivity(settingsIntent);
2169 } else if (menuItemId == R.id.import_export) { // Import/Export.
2170 // Create an intent to launch the import/export activity.
2171 Intent importExportIntent = new Intent(this, ImportExportActivity.class);
2174 startActivity(importExportIntent);
2175 } else if (menuItemId == R.id.logcat) { // Logcat.
2176 // Create an intent to launch the logcat activity.
2177 Intent logcatIntent = new Intent(this, LogcatActivity.class);
2180 startActivity(logcatIntent);
2181 } else if (menuItemId == R.id.guide) { // Guide.
2182 // Create an intent to launch the guide activity.
2183 Intent guideIntent = new Intent(this, GuideActivity.class);
2186 startActivity(guideIntent);
2187 } else if (menuItemId == R.id.about) { // About
2188 // Create an intent to launch the about activity.
2189 Intent aboutIntent = new Intent(this, AboutActivity.class);
2191 // Create a string array for the blocklist versions.
2192 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],
2193 ultraList.get(0).get(0)[0], ultraPrivacy.get(0).get(0)[0]};
2195 // Add the blocklist versions to the intent.
2196 aboutIntent.putExtra(AboutActivity.BLOCKLIST_VERSIONS, blocklistVersions);
2199 startActivity(aboutIntent);
2202 // Close the navigation drawer.
2203 drawerLayout.closeDrawer(GravityCompat.START);
2208 public void onPostCreate(Bundle savedInstanceState) {
2209 // Run the default commands.
2210 super.onPostCreate(savedInstanceState);
2212 // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished. This creates the navigation drawer icon.
2213 actionBarDrawerToggle.syncState();
2217 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2218 // Get the hit test result.
2219 final WebView.HitTestResult hitTestResult = currentWebView.getHitTestResult();
2221 // Define the URL strings.
2222 final String imageUrl;
2223 final String linkUrl;
2225 // Get handles for the system managers.
2226 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2228 // Remove the lint errors below that the clipboard manager might be null.
2229 assert clipboardManager != null;
2231 // Process the link according to the type.
2232 switch (hitTestResult.getType()) {
2233 // `SRC_ANCHOR_TYPE` is a link.
2234 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2235 // Get the target URL.
2236 linkUrl = hitTestResult.getExtra();
2238 // Set the target URL as the title of the `ContextMenu`.
2239 menu.setHeaderTitle(linkUrl);
2241 // Add an Open in New Tab entry.
2242 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2243 // Load the link URL in a new tab and move to it.
2244 addNewTab(linkUrl, true);
2246 // Consume the event.
2250 // Add an Open in Background entry.
2251 menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
2252 // Load the link URL in a new tab but do not move to it.
2253 addNewTab(linkUrl, false);
2255 // Consume the event.
2259 // Add an Open with App entry.
2260 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2261 openWithApp(linkUrl);
2263 // Consume the event.
2267 // Add an Open with Browser entry.
2268 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2269 openWithBrowser(linkUrl);
2271 // Consume the event.
2275 // Add a Copy URL entry.
2276 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2277 // Save the link URL in a `ClipData`.
2278 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2280 // Set the `ClipData` as the clipboard's primary clip.
2281 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2283 // Consume the event.
2287 // Add a Save URL entry.
2288 menu.add(R.string.save_url).setOnMenuItemClickListener((MenuItem item) -> {
2289 // Check the download preference.
2290 if (downloadWithExternalApp) { // Download with an external app.
2291 downloadUrlWithExternalApp(linkUrl);
2292 } else { // Handle the download inside of Privacy Browser.
2293 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2294 new PrepareSaveDialog(this, this, getSupportFragmentManager(), currentWebView.getSettings().getUserAgentString(),
2295 currentWebView.getAcceptCookies()).execute(linkUrl);
2298 // Consume the event.
2302 // Add an empty Cancel entry, which by default closes the context menu.
2303 menu.add(R.string.cancel);
2306 // `IMAGE_TYPE` is an image.
2307 case WebView.HitTestResult.IMAGE_TYPE:
2308 // Get the image URL.
2309 imageUrl = hitTestResult.getExtra();
2311 // Remove the incorrect lint warning below that the image URL might be null.
2312 assert imageUrl != null;
2314 // Set the context menu title.
2315 if (imageUrl.startsWith("data:")) { // The image data is contained in within the URL, making it exceedingly long.
2316 // Truncate the image URL before making it the title.
2317 menu.setHeaderTitle(imageUrl.substring(0, 100));
2318 } else { // The image URL does not contain the full image data.
2319 // Set the image URL as the title of the context menu.
2320 menu.setHeaderTitle(imageUrl);
2323 // Add an Open in New Tab entry.
2324 menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2325 // Load the image in a new tab.
2326 addNewTab(imageUrl, true);
2328 // Consume the event.
2332 // Add an Open with App entry.
2333 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2334 // Open the image URL with an external app.
2335 openWithApp(imageUrl);
2337 // Consume the event.
2341 // Add an Open with Browser entry.
2342 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2343 // Open the image URL with an external browser.
2344 openWithBrowser(imageUrl);
2346 // Consume the event.
2350 // Add a View Image entry.
2351 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2352 // Load the image in the current tab.
2353 loadUrl(currentWebView, imageUrl);
2355 // Consume the event.
2359 // Add a Save Image entry.
2360 menu.add(R.string.save_image).setOnMenuItemClickListener((MenuItem item) -> {
2361 // Check the download preference.
2362 if (downloadWithExternalApp) { // Download with an external app.
2363 downloadUrlWithExternalApp(imageUrl);
2364 } else { // Handle the download inside of Privacy Browser.
2365 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2366 new PrepareSaveDialog(this, this, getSupportFragmentManager(), currentWebView.getSettings().getUserAgentString(),
2367 currentWebView.getAcceptCookies()).execute(imageUrl);
2370 // Consume the event.
2374 // Add a Copy URL entry.
2375 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2376 // Save the image URL in a clip data.
2377 ClipData imageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2379 // Set the clip data as the clipboard's primary clip.
2380 clipboardManager.setPrimaryClip(imageTypeClipData);
2382 // Consume the event.
2386 // Add an empty Cancel entry, which by default closes the context menu.
2387 menu.add(R.string.cancel);
2390 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2391 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2392 // Get the image URL.
2393 imageUrl = hitTestResult.getExtra();
2395 // Instantiate a handler.
2396 Handler handler = new Handler();
2398 // Get a message from the handler.
2399 Message message = handler.obtainMessage();
2401 // Request the image details from the last touched node be returned in the message.
2402 currentWebView.requestFocusNodeHref(message);
2404 // Get the link URL from the message data.
2405 linkUrl = message.getData().getString("url");
2407 // Set the link URL as the title of the context menu.
2408 menu.setHeaderTitle(linkUrl);
2410 // Add an Open in New Tab entry.
2411 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2412 // Load the link URL in a new tab and move to it.
2413 addNewTab(linkUrl, true);
2415 // Consume the event.
2419 // Add an Open in Background entry.
2420 menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
2421 // Lod the link URL in a new tab but do not move to it.
2422 addNewTab(linkUrl, false);
2424 // Consume the event.
2428 // Add an Open Image in New Tab entry.
2429 menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2430 // Load the image in a new tab and move to it.
2431 addNewTab(imageUrl, true);
2433 // Consume the event.
2437 // Add an Open with App entry.
2438 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2439 // Open the link URL with an external app.
2440 openWithApp(linkUrl);
2442 // Consume the event.
2446 // Add an Open with Browser entry.
2447 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2448 // Open the link URL with an external browser.
2449 openWithBrowser(linkUrl);
2451 // Consume the event.
2455 // Add a View Image entry.
2456 menu.add(R.string.view_image).setOnMenuItemClickListener((MenuItem item) -> {
2457 // View the image in the current tab.
2458 loadUrl(currentWebView, imageUrl);
2460 // Consume the event.
2464 // Add a Save Image entry.
2465 menu.add(R.string.save_image).setOnMenuItemClickListener((MenuItem item) -> {
2466 // Check the download preference.
2467 if (downloadWithExternalApp) { // Download with an external app.
2468 downloadUrlWithExternalApp(imageUrl);
2469 } else { // Handle the download inside of Privacy Browser.
2470 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2471 new PrepareSaveDialog(this, this, getSupportFragmentManager(), currentWebView.getSettings().getUserAgentString(),
2472 currentWebView.getAcceptCookies()).execute(imageUrl);
2475 // Consume the event.
2479 // Add a Copy URL entry.
2480 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2481 // Save the link URL in a clip data.
2482 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2484 // Set the clip data as the clipboard's primary clip.
2485 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2487 // Consume the event.
2491 // Add a Save URL entry.
2492 menu.add(R.string.save_url).setOnMenuItemClickListener((MenuItem item) -> {
2493 // Check the download preference.
2494 if (downloadWithExternalApp) { // Download with an external app.
2495 downloadUrlWithExternalApp(linkUrl);
2496 } else { // Handle the download inside of Privacy Browser.
2497 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2498 new PrepareSaveDialog(this, this, getSupportFragmentManager(), currentWebView.getSettings().getUserAgentString(),
2499 currentWebView.getAcceptCookies()).execute(linkUrl);
2502 // Consume the event.
2506 // Add an empty Cancel entry, which by default closes the context menu.
2507 menu.add(R.string.cancel);
2510 case WebView.HitTestResult.EMAIL_TYPE:
2511 // Get the target URL.
2512 linkUrl = hitTestResult.getExtra();
2514 // Set the target URL as the title of the `ContextMenu`.
2515 menu.setHeaderTitle(linkUrl);
2517 // Add a Write Email entry.
2518 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2519 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2520 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2522 // Parse the url and set it as the data for the `Intent`.
2523 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2525 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2526 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2530 startActivity(emailIntent);
2531 } catch (ActivityNotFoundException exception) {
2532 // Display a snackbar.
2533 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
2536 // Consume the event.
2540 // Add a Copy Email Address entry.
2541 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2542 // Save the email address in a `ClipData`.
2543 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2545 // Set the `ClipData` as the clipboard's primary clip.
2546 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2548 // Consume the event.
2552 // Add an empty Cancel entry, which by default closes the context menu.
2553 menu.add(R.string.cancel);
2559 public void onCreateBookmark(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2560 // Get a handle for the bookmarks list view.
2561 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2564 Dialog dialog = dialogFragment.getDialog();
2566 // Remove the incorrect lint warning below that the dialog might be null.
2567 assert dialog != null;
2569 // Get the views from the dialog fragment.
2570 EditText createBookmarkNameEditText = dialog.findViewById(R.id.create_bookmark_name_edittext);
2571 EditText createBookmarkUrlEditText = dialog.findViewById(R.id.create_bookmark_url_edittext);
2573 // Extract the strings from the edit texts.
2574 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2575 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2577 // Create a favorite icon byte array output stream.
2578 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2580 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2581 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2583 // Convert the favorite icon byte array stream to a byte array.
2584 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2586 // Display the new bookmark below the current items in the (0 indexed) list.
2587 int newBookmarkDisplayOrder = bookmarksListView.getCount();
2589 // Create the bookmark.
2590 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2592 // Update the bookmarks cursor with the current contents of this folder.
2593 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2595 // Update the list view.
2596 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2598 // Scroll to the new bookmark.
2599 bookmarksListView.setSelection(newBookmarkDisplayOrder);
2603 public void onCreateBookmarkFolder(DialogFragment dialogFragment, @NonNull Bitmap favoriteIconBitmap) {
2604 // Get a handle for the bookmarks list view.
2605 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2608 Dialog dialog = dialogFragment.getDialog();
2610 // Remove the incorrect lint warning below that the dialog might be null.
2611 assert dialog != null;
2613 // Get handles for the views in the dialog fragment.
2614 EditText folderNameEditText = dialog.findViewById(R.id.folder_name_edittext);
2615 RadioButton defaultIconRadioButton = dialog.findViewById(R.id.default_icon_radiobutton);
2616 ImageView defaultIconImageView = dialog.findViewById(R.id.default_icon_imageview);
2618 // Get new folder name string.
2619 String folderNameString = folderNameEditText.getText().toString();
2621 // Create a folder icon bitmap.
2622 Bitmap folderIconBitmap;
2624 // Set the folder icon bitmap according to the dialog.
2625 if (defaultIconRadioButton.isChecked()) { // Use the default folder icon.
2626 // Get the default folder icon drawable.
2627 Drawable folderIconDrawable = defaultIconImageView.getDrawable();
2629 // Convert the folder icon drawable to a bitmap drawable.
2630 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2632 // Convert the folder icon bitmap drawable to a bitmap.
2633 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2634 } else { // Use the WebView favorite icon.
2635 // Copy the favorite icon bitmap to the folder icon bitmap.
2636 folderIconBitmap = favoriteIconBitmap;
2639 // Create a folder icon byte array output stream.
2640 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2642 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2643 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2645 // Convert the folder icon byte array stream to a byte array.
2646 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2648 // Move all the bookmarks down one in the display order.
2649 for (int i = 0; i < bookmarksListView.getCount(); i++) {
2650 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2651 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2654 // Create the folder, which will be placed at the top of the `ListView`.
2655 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2657 // Update the bookmarks cursor with the current contents of this folder.
2658 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2660 // Update the `ListView`.
2661 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2663 // Scroll to the new folder.
2664 bookmarksListView.setSelection(0);
2668 public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId, @NonNull Bitmap favoriteIconBitmap) {
2669 // Remove the incorrect lint warning below that the dialog fragment might be null.
2670 assert dialogFragment != null;
2673 Dialog dialog = dialogFragment.getDialog();
2675 // Remove the incorrect lint warning below that the dialog might be null.
2676 assert dialog != null;
2678 // Get handles for the views from the dialog.
2679 RadioButton currentFolderIconRadioButton = dialog.findViewById(R.id.current_icon_radiobutton);
2680 RadioButton defaultFolderIconRadioButton = dialog.findViewById(R.id.default_icon_radiobutton);
2681 ImageView defaultFolderIconImageView = dialog.findViewById(R.id.default_icon_imageview);
2682 EditText editFolderNameEditText = dialog.findViewById(R.id.folder_name_edittext);
2684 // Get the new folder name.
2685 String newFolderNameString = editFolderNameEditText.getText().toString();
2687 // Check if the favorite icon has changed.
2688 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
2689 // Update the name in the database.
2690 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2691 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
2692 // Create the new folder icon Bitmap.
2693 Bitmap folderIconBitmap;
2695 // Populate the new folder icon bitmap.
2696 if (defaultFolderIconRadioButton.isChecked()) {
2697 // Get the default folder icon drawable.
2698 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2700 // Convert the folder icon drawable to a bitmap drawable.
2701 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2703 // Convert the folder icon bitmap drawable to a bitmap.
2704 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2705 } else { // Use the `WebView` favorite icon.
2706 // Copy the favorite icon bitmap to the folder icon bitmap.
2707 folderIconBitmap = favoriteIconBitmap;
2710 // Create a folder icon byte array output stream.
2711 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2713 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2714 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2716 // Convert the folder icon byte array stream to a byte array.
2717 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2719 // Update the folder icon in the database.
2720 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, newFolderIconByteArray);
2721 } else { // The folder icon and the name have changed.
2722 // Get the new folder icon bitmap.
2723 Bitmap folderIconBitmap;
2724 if (defaultFolderIconRadioButton.isChecked()) {
2725 // Get the default folder icon drawable.
2726 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2728 // Convert the folder icon drawable to a bitmap drawable.
2729 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2731 // Convert the folder icon bitmap drawable to a bitmap.
2732 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2733 } else { // Use the `WebView` favorite icon.
2734 // Copy the favorite icon bitmap to the folder icon bitmap.
2735 folderIconBitmap = favoriteIconBitmap;
2738 // Create a folder icon byte array output stream.
2739 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2741 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2742 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2744 // Convert the folder icon byte array stream to a byte array.
2745 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2747 // Update the folder name and icon in the database.
2748 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, newFolderIconByteArray);
2751 // Update the bookmarks cursor with the current contents of this folder.
2752 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2754 // Update the `ListView`.
2755 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2758 // Override `onBackPressed()` to handle the navigation drawer and and the WebViews.
2760 public void onBackPressed() {
2761 // Check the different options for processing `back`.
2762 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
2763 // Close the navigation drawer.
2764 drawerLayout.closeDrawer(GravityCompat.START);
2765 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
2766 // close the bookmarks drawer.
2767 drawerLayout.closeDrawer(GravityCompat.END);
2768 } else if (displayingFullScreenVideo) { // A full screen video is shown.
2769 // Exit the full screen video.
2770 exitFullScreenVideo();
2771 } else if (currentWebView.canGoBack()) { // There is at least one item in the current WebView history.
2772 // Get the current web back forward list.
2773 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
2775 // Get the previous entry URL.
2776 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
2778 // Apply the domain settings.
2779 applyDomainSettings(currentWebView, previousUrl, false, false, false);
2782 currentWebView.goBack();
2783 } else if (tabLayout.getTabCount() > 1) { // There are at least two tabs.
2784 // Close the current tab.
2786 } else { // There isn't anything to do in Privacy Browser.
2787 // Close Privacy Browser. `finishAndRemoveTask()` also removes Privacy Browser from the recent app list.
2788 if (Build.VERSION.SDK_INT >= 21) {
2789 finishAndRemoveTask();
2794 // Manually kill Privacy Browser. Otherwise, it is glitchy when restarted.
2799 // Process the results of a file browse.
2801 public void onActivityResult(int requestCode, int resultCode, Intent returnedIntent) {
2802 // Run the default commands.
2803 super.onActivityResult(requestCode, resultCode, returnedIntent);
2805 // Run the commands that correlate to the specified request code.
2806 switch (requestCode) {
2807 case BROWSE_FILE_UPLOAD_REQUEST_CODE:
2808 // File uploads only work on API >= 21.
2809 if (Build.VERSION.SDK_INT >= 21) {
2810 // Pass the file to the WebView.
2811 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, returnedIntent));
2815 case BROWSE_OPEN_REQUEST_CODE:
2816 // Don't do anything if the user pressed back from the file picker.
2817 if (resultCode == Activity.RESULT_OK) {
2818 // Get a handle for the open dialog fragment.
2819 DialogFragment openDialogFragment = (DialogFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.open));
2821 // Only update the file name if the dialog still exists.
2822 if (openDialogFragment != null) {
2823 // Get a handle for the open dialog.
2824 Dialog openDialog = openDialogFragment.getDialog();
2826 // Remove the incorrect lint warning below that the dialog might be null.
2827 assert openDialog != null;
2829 // Get a handle for the file name edit text.
2830 EditText fileNameEditText = openDialog.findViewById(R.id.file_name_edittext);
2832 // Get the file name URI from the intent.
2833 Uri fileNameUri = returnedIntent.getData();
2835 // Get the file name string from the URI.
2836 String fileNameString = fileNameUri.toString();
2838 // Set the file name text.
2839 fileNameEditText.setText(fileNameString);
2841 // Move the cursor to the end of the file name edit text.
2842 fileNameEditText.setSelection(fileNameString.length());
2849 private void loadUrlFromTextBox() {
2850 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
2851 String unformattedUrlString = urlEditText.getText().toString().trim();
2853 // Initialize the formatted URL string.
2856 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
2857 if (unformattedUrlString.startsWith("content://")) { // This is a Content URL.
2858 // Load the entire content URL.
2859 url = unformattedUrlString;
2860 } else if (Patterns.WEB_URL.matcher(unformattedUrlString).matches() || unformattedUrlString.startsWith("http://") || unformattedUrlString.startsWith("https://") ||
2861 unformattedUrlString.startsWith("file://")) { // This is a standard URL.
2862 // Add `https://` at the beginning if there is no protocol. Otherwise the app will segfault.
2863 if (!unformattedUrlString.startsWith("http") && !unformattedUrlString.startsWith("file://") && !unformattedUrlString.startsWith("content://")) {
2864 unformattedUrlString = "https://" + unformattedUrlString;
2867 // Initialize `unformattedUrl`.
2868 URL unformattedUrl = null;
2870 // Convert `unformattedUrlString` to a `URL`, then to a `URI`, and then back to a `String`, which sanitizes the input and adds in any missing components.
2872 unformattedUrl = new URL(unformattedUrlString);
2873 } catch (MalformedURLException e) {
2874 e.printStackTrace();
2877 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2878 String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2879 String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2880 String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2881 String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2882 String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2885 Uri.Builder uri = new Uri.Builder();
2886 uri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2888 // Decode the URI as a UTF-8 string in.
2890 url = URLDecoder.decode(uri.build().toString(), "UTF-8");
2891 } catch (UnsupportedEncodingException exception) {
2892 // Do nothing. The formatted URL string will remain blank.
2894 } else if (!unformattedUrlString.isEmpty()){ // This is not a URL, but rather a search string.
2895 // Create an encoded URL String.
2896 String encodedUrlString;
2898 // Sanitize the search input.
2900 encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2901 } catch (UnsupportedEncodingException exception) {
2902 encodedUrlString = "";
2905 // Add the base search URL.
2906 url = searchURL + encodedUrlString;
2909 // 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.
2910 urlEditText.clearFocus();
2913 loadUrl(currentWebView, url);
2916 private void loadUrl(NestedScrollWebView nestedScrollWebView, String url) {
2917 // Sanitize the URL.
2918 url = sanitizeUrl(url);
2920 // Apply the domain settings and load the URL.
2921 applyDomainSettings(nestedScrollWebView, url, true, false, true);
2924 public void findPreviousOnPage(View view) {
2925 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
2926 currentWebView.findNext(false);
2929 public void findNextOnPage(View view) {
2930 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2931 currentWebView.findNext(true);
2934 public void closeFindOnPage(View view) {
2935 // Get a handle for the views.
2936 Toolbar toolbar = findViewById(R.id.toolbar);
2937 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
2938 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
2940 // Delete the contents of `find_on_page_edittext`.
2941 findOnPageEditText.setText(null);
2943 // Clear the highlighted phrases if the WebView is not null.
2944 if (currentWebView != null) {
2945 currentWebView.clearMatches();
2948 // Hide the find on page linear layout.
2949 findOnPageLinearLayout.setVisibility(View.GONE);
2951 // Show the toolbar.
2952 toolbar.setVisibility(View.VISIBLE);
2954 // Get a handle for the input method manager.
2955 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
2957 // Remove the lint warning below that the input method manager might be null.
2958 assert inputMethodManager != null;
2960 // Hide the keyboard.
2961 inputMethodManager.hideSoftInputFromWindow(toolbar.getWindowToken(), 0);
2965 public void onApplyNewFontSize(DialogFragment dialogFragment) {
2966 // Remove the incorrect lint warning below that the dialog fragment might be null.
2967 assert dialogFragment != null;
2970 Dialog dialog = dialogFragment.getDialog();
2972 // Remove the incorrect lint warning below tha the dialog might be null.
2973 assert dialog != null;
2975 // Get a handle for the font size edit text.
2976 EditText fontSizeEditText = dialog.findViewById(R.id.font_size_edittext);
2978 // Initialize the new font size variable with the current font size.
2979 int newFontSize = currentWebView.getSettings().getTextZoom();
2981 // Get the font size from the edit text.
2983 newFontSize = Integer.parseInt(fontSizeEditText.getText().toString());
2984 } catch (Exception exception) {
2985 // If the edit text does not contain a valid font size do nothing.
2988 // Apply the new font size.
2989 currentWebView.getSettings().setTextZoom(newFontSize);
2993 public void onOpen(DialogFragment dialogFragment) {
2995 Dialog dialog = dialogFragment.getDialog();
2997 // Remove the incorrect lint warning below that the dialog might be null.
2998 assert dialog != null;
3000 // Get handles for the views.
3001 EditText fileNameEditText = dialog.findViewById(R.id.file_name_edittext);
3002 CheckBox mhtCheckBox = dialog.findViewById(R.id.mht_checkbox);
3004 // Get the file path string.
3005 String openFilePath = fileNameEditText.getText().toString();
3007 // Apply the domain settings. This resets the favorite icon and removes any domain settings.
3008 applyDomainSettings(currentWebView, openFilePath, true, false, false);
3010 // Open the file according to the type.
3011 if (mhtCheckBox.isChecked()) { // Force opening of an MHT file.
3013 // Get the MHT file input stream.
3014 InputStream mhtFileInputStream = getContentResolver().openInputStream(Uri.parse(openFilePath));
3016 // Create a temporary MHT file.
3017 File temporaryMhtFile = File.createTempFile("temporary_mht_file", ".mht", getCacheDir());
3019 // Get a file output stream for the temporary MHT file.
3020 FileOutputStream temporaryMhtFileOutputStream = new FileOutputStream(temporaryMhtFile);
3022 // Create a transfer byte array.
3023 byte[] transferByteArray = new byte[1024];
3025 // Create an integer to track the number of bytes read.
3028 // Copy the temporary MHT file input stream to the MHT output stream.
3029 while ((bytesRead = mhtFileInputStream.read(transferByteArray)) > 0) {
3030 temporaryMhtFileOutputStream.write(transferByteArray, 0, bytesRead);
3033 // Flush the temporary MHT file output stream.
3034 temporaryMhtFileOutputStream.flush();
3036 // Close the streams.
3037 temporaryMhtFileOutputStream.close();
3038 mhtFileInputStream.close();
3040 // Load the temporary MHT file.
3041 currentWebView.loadUrl(temporaryMhtFile.toString());
3042 } catch (Exception exception) {
3043 // Display a snackbar.
3044 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception.toString(), Snackbar.LENGTH_INDEFINITE).show();
3046 } else { // Let the WebView handle opening of the file.
3048 currentWebView.loadUrl(openFilePath);
3052 private void downloadUrlWithExternalApp(String url) {
3053 // Create a download intent. Not specifying the action type will display the maximum number of options.
3054 Intent downloadIntent = new Intent();
3056 // Set the URI and the mime type.
3057 downloadIntent.setDataAndType(Uri.parse(url), "text/html");
3059 // Flag the intent to open in a new task.
3060 downloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3062 // Show the chooser.
3063 startActivity(Intent.createChooser(downloadIntent, getString(R.string.download_with_external_app)));
3066 public void onSaveUrl(@NonNull String originalUrlString, @NonNull String fileNameString, @NonNull DialogFragment dialogFragment) {
3067 // Store the URL. This will be used in the save URL activity result launcher.
3068 if (originalUrlString.startsWith("data:")) {
3069 // Save the original URL.
3070 saveUrlString = originalUrlString;
3073 Dialog dialog = dialogFragment.getDialog();
3075 // Remove the incorrect lint warning below that the dialog might be null.
3076 assert dialog != null;
3078 // Get a handle for the dialog URL edit text.
3079 EditText dialogUrlEditText = dialog.findViewById(R.id.url_edittext);
3081 // Get the URL from the edit text, which may have been modified.
3082 saveUrlString = dialogUrlEditText.getText().toString();
3085 // Open the file picker.
3086 saveUrlActivityResultLauncher.launch(fileNameString);
3089 // Remove the warning that `OnTouchListener()` needs to override `performClick()`, as the only purpose of setting the `OnTouchListener()` is to make it do nothing.
3090 @SuppressLint("ClickableViewAccessibility")
3091 private void initializeApp() {
3092 // Get a handle for the input method.
3093 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
3095 // Remove the lint warning below that the input method manager might be null.
3096 assert inputMethodManager != null;
3098 // Initialize the gray foreground color spans for highlighting the URLs. The deprecated `getResources()` must be used until API >= 23.
3099 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
3100 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
3102 // Get the current theme status.
3103 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
3105 // Set the red color span according to the theme.
3106 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
3107 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
3109 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_900));
3112 // Remove the formatting from the URL edit text when the user is editing the text.
3113 urlEditText.setOnFocusChangeListener((View v, boolean hasFocus) -> {
3114 if (hasFocus) { // The user is editing the URL text box.
3115 // Remove the highlighting.
3116 urlEditText.getText().removeSpan(redColorSpan);
3117 urlEditText.getText().removeSpan(initialGrayColorSpan);
3118 urlEditText.getText().removeSpan(finalGrayColorSpan);
3119 } else { // The user has stopped editing the URL text box.
3120 // Move to the beginning of the string.
3121 urlEditText.setSelection(0);
3123 // Reapply the highlighting.
3128 // Set the go button on the keyboard to load the URL in `urlTextBox`.
3129 urlEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
3130 // If the event is a key-down event on the `enter` button, load the URL.
3131 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
3132 // Load the URL into the mainWebView and consume the event.
3133 loadUrlFromTextBox();
3135 // If the enter key was pressed, consume the event.
3138 // If any other key was pressed, do not consume the event.
3143 // Create an Orbot status broadcast receiver.
3144 orbotStatusBroadcastReceiver = new BroadcastReceiver() {
3146 public void onReceive(Context context, Intent intent) {
3147 // Store the content of the status message in `orbotStatus`.
3148 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
3150 // If Privacy Browser is waiting on the proxy, load the website now that Orbot is connected.
3151 if ((orbotStatus != null) && orbotStatus.equals(ProxyHelper.ORBOT_STATUS_ON) && waitingForProxy) {
3152 // Reset the waiting for proxy status.
3153 waitingForProxy = false;
3155 // Get a list of the current fragments.
3156 List<Fragment> fragmentList = getSupportFragmentManager().getFragments();
3158 // Check each fragment to see if it is a waiting for proxy dialog. Sometimes more than one is displayed.
3159 for (int i = 0; i < fragmentList.size(); i++) {
3160 // Get the fragment tag.
3161 String fragmentTag = fragmentList.get(i).getTag();
3163 // Check to see if it is the waiting for proxy dialog.
3164 if ((fragmentTag!= null) && fragmentTag.equals(getString(R.string.waiting_for_proxy_dialog))) {
3165 // Dismiss the waiting for proxy dialog.
3166 ((DialogFragment) fragmentList.get(i)).dismiss();
3170 // Reload existing URLs and load any URLs that are waiting for the proxy.
3171 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3172 // Get the WebView tab fragment.
3173 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3175 // Get the fragment view.
3176 View fragmentView = webViewTabFragment.getView();
3178 // Only process the WebViews if they exist.
3179 if (fragmentView != null) {
3180 // Get the nested scroll WebView from the tab fragment.
3181 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3183 // Get the waiting for proxy URL string.
3184 String waitingForProxyUrlString = nestedScrollWebView.getWaitingForProxyUrlString();
3186 // Load the pending URL if it exists.
3187 if (!waitingForProxyUrlString.isEmpty()) { // A URL is waiting to be loaded.
3189 loadUrl(nestedScrollWebView, waitingForProxyUrlString);
3191 // Reset the waiting for proxy URL string.
3192 nestedScrollWebView.setWaitingForProxyUrlString("");
3193 } else { // No URL is waiting to be loaded.
3194 // Reload the existing URL.
3195 nestedScrollWebView.reload();
3203 // Register the Orbot status broadcast receiver on `this` context.
3204 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
3206 // Get handles for views that need to be modified.
3207 LinearLayout bookmarksHeaderLinearLayout = findViewById(R.id.bookmarks_header_linearlayout);
3208 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
3209 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
3210 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
3211 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
3212 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
3214 // Update the web view pager every time a tab is modified.
3215 webViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
3217 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
3222 public void onPageSelected(int position) {
3223 // Close the find on page bar if it is open.
3224 closeFindOnPage(null);
3226 // Set the current WebView.
3227 setCurrentWebView(position);
3229 // 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.
3230 if (tabLayout.getSelectedTabPosition() != position) {
3231 // Wait until the new tab has been created.
3232 tabLayout.post(() -> {
3233 // Get a handle for the tab.
3234 TabLayout.Tab tab = tabLayout.getTabAt(position);
3236 // Assert that the tab is not null.
3246 public void onPageScrollStateChanged(int state) {
3251 // Display the View SSL Certificate dialog when the currently selected tab is reselected.
3252 tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
3254 public void onTabSelected(TabLayout.Tab tab) {
3255 // Select the same page in the view pager.
3256 webViewPager.setCurrentItem(tab.getPosition());
3260 public void onTabUnselected(TabLayout.Tab tab) {
3265 public void onTabReselected(TabLayout.Tab tab) {
3266 // Instantiate the View SSL Certificate dialog.
3267 DialogFragment viewSslCertificateDialogFragment = ViewSslCertificateDialog.displayDialog(currentWebView.getWebViewFragmentId(), currentWebView.getFavoriteOrDefaultIcon());
3269 // Display the View SSL Certificate dialog.
3270 viewSslCertificateDialogFragment.show(getSupportFragmentManager(), getString(R.string.view_ssl_certificate));
3274 // Set a touch listener on the bookmarks header linear layout so that touches don't pass through to the button underneath.
3275 bookmarksHeaderLinearLayout.setOnTouchListener((view, motionEvent) -> {
3276 // Consume the touch.
3280 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
3281 launchBookmarksActivityFab.setOnClickListener(v -> {
3282 // Get a copy of the favorite icon bitmap.
3283 Bitmap favoriteIconBitmap = currentWebView.getFavoriteOrDefaultIcon();
3285 // Create a favorite icon byte array output stream.
3286 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3288 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
3289 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
3291 // Convert the favorite icon byte array stream to a byte array.
3292 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
3294 // Create an intent to launch the bookmarks activity.
3295 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
3297 // Add the extra information to the intent.
3298 bookmarksIntent.putExtra("current_url", currentWebView.getUrl());
3299 bookmarksIntent.putExtra("current_title", currentWebView.getTitle());
3300 bookmarksIntent.putExtra("current_folder", currentBookmarksFolder);
3301 bookmarksIntent.putExtra("favorite_icon_byte_array", favoriteIconByteArray);
3304 startActivity(bookmarksIntent);
3307 // Set the create new bookmark folder FAB to display an alert dialog.
3308 createBookmarkFolderFab.setOnClickListener(v -> {
3309 // Create a create bookmark folder dialog.
3310 DialogFragment createBookmarkFolderDialog = CreateBookmarkFolderDialog.createBookmarkFolder(currentWebView.getFavoriteOrDefaultIcon());
3312 // Show the create bookmark folder dialog.
3313 createBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.create_folder));
3316 // Set the create new bookmark FAB to display an alert dialog.
3317 createBookmarkFab.setOnClickListener(view -> {
3318 // Instantiate the create bookmark dialog.
3319 DialogFragment createBookmarkDialog = CreateBookmarkDialog.createBookmark(currentWebView.getUrl(), currentWebView.getTitle(), currentWebView.getFavoriteOrDefaultIcon());
3321 // Display the create bookmark dialog.
3322 createBookmarkDialog.show(getSupportFragmentManager(), getString(R.string.create_bookmark));
3325 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
3326 findOnPageEditText.addTextChangedListener(new TextWatcher() {
3328 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
3333 public void onTextChanged(CharSequence s, int start, int before, int count) {
3338 public void afterTextChanged(Editable s) {
3339 // 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.
3340 if (currentWebView != null) {
3341 currentWebView.findAllAsync(findOnPageEditText.getText().toString());
3346 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
3347 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
3348 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
3349 // Hide the soft keyboard.
3350 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
3352 // Consume the event.
3354 } else { // A different key was pressed.
3355 // Do not consume the event.
3360 // Implement swipe to refresh.
3361 swipeRefreshLayout.setOnRefreshListener(() -> {
3362 // Reload the website.
3363 currentWebView.reload();
3366 // Store the default progress view offsets for use later in `initializeWebView()`.
3367 defaultProgressViewStartOffset = swipeRefreshLayout.getProgressViewStartOffset();
3368 defaultProgressViewEndOffset = swipeRefreshLayout.getProgressViewEndOffset();
3370 // Set the refresh color scheme according to the theme.
3371 swipeRefreshLayout.setColorSchemeResources(R.color.blue_text);
3373 // Initialize a color background typed value.
3374 TypedValue colorBackgroundTypedValue = new TypedValue();
3376 // Get the color background from the theme.
3377 getTheme().resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true);
3379 // Get the color background int from the typed value.
3380 int colorBackgroundInt = colorBackgroundTypedValue.data;
3382 // Set the swipe refresh background color.
3383 swipeRefreshLayout.setProgressBackgroundColorSchemeColor(colorBackgroundInt);
3385 // The drawer titles identify the drawer layouts in accessibility mode.
3386 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
3387 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
3389 // Initialize the bookmarks database helper. The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
3390 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
3392 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
3393 currentBookmarksFolder = "";
3395 // Load the home folder, which is `""` in the database.
3396 loadBookmarksFolder();
3398 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
3399 // Convert the id from long to int to match the format of the bookmarks database.
3400 int databaseId = (int) id;
3402 // Get the bookmark cursor for this ID.
3403 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseId);
3405 // Move the bookmark cursor to the first row.
3406 bookmarkCursor.moveToFirst();
3408 // Act upon the bookmark according to the type.
3409 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
3410 // Store the new folder name in `currentBookmarksFolder`.
3411 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME));
3413 // Load the new folder.
3414 loadBookmarksFolder();
3415 } else { // The selected bookmark is not a folder.
3416 // Load the bookmark URL.
3417 loadUrl(currentWebView, bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_URL)));
3419 // Close the bookmarks drawer.
3420 drawerLayout.closeDrawer(GravityCompat.END);
3423 // Close the `Cursor`.
3424 bookmarkCursor.close();
3427 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
3428 // Convert the database ID from `long` to `int`.
3429 int databaseId = (int) id;
3431 // Find out if the selected bookmark is a folder.
3432 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
3434 // Check to see if the bookmark is a folder.
3435 if (isFolder) { // The bookmark is a folder.
3436 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
3437 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME));
3439 // Instantiate the edit folder bookmark dialog.
3440 DialogFragment editBookmarkFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId, currentWebView.getFavoriteOrDefaultIcon());
3442 // Show the edit folder bookmark dialog.
3443 editBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.edit_folder));
3444 } else { // The bookmark is not a folder.
3445 // Get the bookmark cursor for this ID.
3446 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseId);
3448 // Move the bookmark cursor to the first row.
3449 bookmarkCursor.moveToFirst();
3451 // Load the bookmark in a new tab but do not switch to the tab or close the drawer.
3452 addNewTab(bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_URL)), false);
3454 // Display a snackbar.
3455 Snackbar.make(currentWebView, R.string.bookmark_opened_in_background, Snackbar.LENGTH_SHORT).show();
3458 // Consume the event.
3462 // The drawer listener is used to update the navigation menu.
3463 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
3465 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
3469 public void onDrawerOpened(@NonNull View drawerView) {
3473 public void onDrawerClosed(@NonNull View drawerView) {
3474 // Reset the drawer icon when the drawer is closed. Otherwise, it is an arrow if the drawer is open when the app is restarted.
3475 actionBarDrawerToggle.syncState();
3479 public void onDrawerStateChanged(int newState) {
3480 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // A drawer is opening or closing.
3481 // Update the navigation menu items if the WebView is not null.
3482 if (currentWebView != null) {
3483 navigationBackMenuItem.setEnabled(currentWebView.canGoBack());
3484 navigationForwardMenuItem.setEnabled(currentWebView.canGoForward());
3485 navigationHistoryMenuItem.setEnabled((currentWebView.canGoBack() || currentWebView.canGoForward()));
3486 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
3488 // Hide the keyboard (if displayed).
3489 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
3492 // 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.
3493 urlEditText.clearFocus();
3495 // 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.
3496 if (currentWebView != null) {
3497 // Clearing the focus from the WebView removes any text selection markers and context menus, which otherwise draw above the open drawers.
3498 currentWebView.clearFocus();
3504 // 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).
3505 customHeaders.put("X-Requested-With", "");
3507 // Inflate a bare WebView to get the default user agent. It is not used to render content on the screen.
3508 @SuppressLint("InflateParams") View webViewLayout = getLayoutInflater().inflate(R.layout.bare_webview, null, false);
3510 // Get a handle for the WebView.
3511 WebView bareWebView = webViewLayout.findViewById(R.id.bare_webview);
3513 // Store the default user agent.
3514 webViewDefaultUserAgent = bareWebView.getSettings().getUserAgentString();
3516 // Destroy the bare WebView.
3517 bareWebView.destroy();
3520 private void applyAppSettings() {
3521 // Get a handle for the shared preferences.
3522 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3524 // Store the values from the shared preferences in variables.
3525 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3526 sanitizeGoogleAnalytics = sharedPreferences.getBoolean("google_analytics", true);
3527 sanitizeFacebookClickIds = sharedPreferences.getBoolean("facebook_click_ids", true);
3528 sanitizeTwitterAmpRedirects = sharedPreferences.getBoolean("twitter_amp_redirects", true);
3529 proxyMode = sharedPreferences.getString("proxy", getString(R.string.proxy_default_value));
3530 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3531 downloadWithExternalApp = sharedPreferences.getBoolean(getString(R.string.download_with_external_app_key), false);
3532 hideAppBar = sharedPreferences.getBoolean("hide_app_bar", true);
3533 scrollAppBar = sharedPreferences.getBoolean(getString(R.string.scroll_app_bar_key), true);
3535 // Apply the saved proxy mode if the app has been restarted.
3536 if (savedProxyMode != null) {
3537 // Apply the saved proxy mode.
3538 proxyMode = savedProxyMode;
3540 // Reset the saved proxy mode.
3541 savedProxyMode = null;
3544 // Get the search string.
3545 String searchString = sharedPreferences.getString("search", getString(R.string.search_default_value));
3547 // Set the search string.
3548 if (searchString.equals("Custom URL")) { // A custom search string is used.
3549 searchURL = sharedPreferences.getString("search_custom_url", getString(R.string.search_custom_url_default_value));
3550 } else { // A custom search string is not used.
3551 searchURL = searchString;
3557 // Adjust the layout and scrolling parameters if the app bar is at the top of the screen.
3558 if (!bottomAppBar) {
3559 // Get the current layout parameters. Using coordinator layout parameters allows the `setBehavior()` command and using app bar layout parameters allows the `setScrollFlags()` command.
3560 CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
3561 AppBarLayout.LayoutParams toolbarLayoutParams = (AppBarLayout.LayoutParams) toolbar.getLayoutParams();
3562 AppBarLayout.LayoutParams findOnPageLayoutParams = (AppBarLayout.LayoutParams) findOnPageLinearLayout.getLayoutParams();
3563 AppBarLayout.LayoutParams tabsLayoutParams = (AppBarLayout.LayoutParams) tabsLinearLayout.getLayoutParams();
3565 // Add the scrolling behavior to the layout parameters.
3567 // Enable scrolling of the app bar.
3568 swipeRefreshLayoutParams.setBehavior(new AppBarLayout.ScrollingViewBehavior());
3569 toolbarLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3570 findOnPageLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3571 tabsLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3573 // Disable scrolling of the app bar.
3574 swipeRefreshLayoutParams.setBehavior(null);
3575 toolbarLayoutParams.setScrollFlags(0);
3576 findOnPageLayoutParams.setScrollFlags(0);
3577 tabsLayoutParams.setScrollFlags(0);
3579 // Expand the app bar if it is currently collapsed.
3580 appBarLayout.setExpanded(true);
3583 // Set the app bar scrolling for each WebView.
3584 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3585 // Get the WebView tab fragment.
3586 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3588 // Get the fragment view.
3589 View fragmentView = webViewTabFragment.getView();
3591 // Only modify the WebViews if they exist.
3592 if (fragmentView != null) {
3593 // Get the nested scroll WebView from the tab fragment.
3594 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3596 // Set the app bar scrolling.
3597 nestedScrollWebView.setNestedScrollingEnabled(scrollAppBar);
3602 // Update the full screen browsing mode settings.
3603 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
3604 // Update the visibility of the app bar, which might have changed in the settings.
3606 // Hide the tab linear layout.
3607 tabsLinearLayout.setVisibility(View.GONE);
3609 // Hide the action bar.
3612 // Show the tab linear layout.
3613 tabsLinearLayout.setVisibility(View.VISIBLE);
3615 // Show the action bar.
3619 /* Hide the system bars.
3620 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3621 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
3622 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3623 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3625 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
3626 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3627 } else { // Privacy Browser is not in full screen browsing mode.
3628 // 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.
3629 inFullScreenBrowsingMode = false;
3631 // Show the tab linear layout.
3632 tabsLinearLayout.setVisibility(View.VISIBLE);
3634 // Show the action bar.
3637 // Remove the `SYSTEM_UI` flags from the root frame layout.
3638 rootFrameLayout.setSystemUiVisibility(0);
3643 public void navigateHistory(@NonNull String url, int steps) {
3644 // Apply the domain settings.
3645 applyDomainSettings(currentWebView, url, false, false, false);
3647 // Load the history entry.
3648 currentWebView.goBackOrForward(steps);
3652 public void pinnedErrorGoBack() {
3653 // Get the current web back forward list.
3654 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
3656 // Get the previous entry URL.
3657 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
3659 // Apply the domain settings.
3660 applyDomainSettings(currentWebView, previousUrl, false, false, false);
3663 currentWebView.goBack();
3666 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
3667 @SuppressLint("SetJavaScriptEnabled")
3668 private void applyDomainSettings(NestedScrollWebView nestedScrollWebView, String url, boolean resetTab, boolean reloadWebsite, boolean loadUrl) {
3669 // Store the current URL.
3670 nestedScrollWebView.setCurrentUrl(url);
3672 // Parse the URL into a URI.
3673 Uri uri = Uri.parse(url);
3675 // Extract the domain from `uri`.
3676 String newHostName = uri.getHost();
3678 // Strings don't like to be null.
3679 if (newHostName == null) {
3683 // 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.
3684 if (!nestedScrollWebView.getCurrentDomainName().equals(newHostName) || newHostName.equals("")) {
3685 // Set the new host name as the current domain name.
3686 nestedScrollWebView.setCurrentDomainName(newHostName);
3688 // Reset the ignoring of pinned domain information.
3689 nestedScrollWebView.setIgnorePinnedDomainInformation(false);
3691 // Clear any pinned SSL certificate or IP addresses.
3692 nestedScrollWebView.clearPinnedSslCertificate();
3693 nestedScrollWebView.setPinnedIpAddresses("");
3695 // Reset the favorite icon if specified.
3697 // Initialize the favorite icon.
3698 nestedScrollWebView.initializeFavoriteIcon();
3700 // Get the current page position.
3701 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
3703 // Get the corresponding tab.
3704 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
3706 // Update the tab if it isn't null, which sometimes happens when restarting from the background.
3708 // Get the tab custom view.
3709 View tabCustomView = tab.getCustomView();
3711 // Remove the warning below that the tab custom view might be null.
3712 assert tabCustomView != null;
3714 // Get the tab views.
3715 ImageView tabFavoriteIconImageView = tabCustomView.findViewById(R.id.favorite_icon_imageview);
3716 TextView tabTitleTextView = tabCustomView.findViewById(R.id.title_textview);
3718 // Set the default favorite icon as the favorite icon for this tab.
3719 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(nestedScrollWebView.getFavoriteOrDefaultIcon(), 64, 64, true));
3721 // Set the loading title text.
3722 tabTitleTextView.setText(R.string.loading);
3726 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3727 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3729 // Get a full cursor from `domainsDatabaseHelper`.
3730 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3732 // Initialize `domainSettingsSet`.
3733 Set<String> domainSettingsSet = new HashSet<>();
3735 // Get the domain name column index.
3736 int domainNameColumnIndex = domainNameCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.DOMAIN_NAME);
3738 // Populate `domainSettingsSet`.
3739 for (int i = 0; i < domainNameCursor.getCount(); i++) {
3740 // Move the domains cursor to the current row.
3741 domainNameCursor.moveToPosition(i);
3743 // Store the domain name in the domain settings set.
3744 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3747 // Close `domainNameCursor.
3748 domainNameCursor.close();
3750 // Initialize the domain name in database variable.
3751 String domainNameInDatabase = null;
3753 // Check the hostname against the domain settings set.
3754 if (domainSettingsSet.contains(newHostName)) { // The hostname is contained in the domain settings set.
3755 // Record the domain name in the database.
3756 domainNameInDatabase = newHostName;
3758 // Set the domain settings applied tracker to true.
3759 nestedScrollWebView.setDomainSettingsApplied(true);
3760 } else { // The hostname is not contained in the domain settings set.
3761 // Set the domain settings applied tracker to false.
3762 nestedScrollWebView.setDomainSettingsApplied(false);
3765 // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3766 while (!nestedScrollWebView.getDomainSettingsApplied() && newHostName.contains(".")) { // Stop checking if domain settings are already applied or there are no more `.` in the host name.
3767 if (domainSettingsSet.contains("*." + newHostName)) { // Check the host name prepended by `*.`.
3768 // Set the domain settings applied tracker to true.
3769 nestedScrollWebView.setDomainSettingsApplied(true);
3771 // Store the applied domain names as it appears in the database.
3772 domainNameInDatabase = "*." + newHostName;
3775 // Strip out the lowest subdomain of of the host name.
3776 newHostName = newHostName.substring(newHostName.indexOf(".") + 1);
3780 // Get a handle for the shared preferences.
3781 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3783 // Store the general preference information.
3784 String defaultFontSizeString = sharedPreferences.getString("font_size", getString(R.string.font_size_default_value));
3785 String defaultUserAgentName = sharedPreferences.getString("user_agent", getString(R.string.user_agent_default_value));
3786 boolean defaultSwipeToRefresh = sharedPreferences.getBoolean("swipe_to_refresh", true);
3787 String webViewTheme = sharedPreferences.getString("webview_theme", getString(R.string.webview_theme_default_value));
3788 boolean wideViewport = sharedPreferences.getBoolean("wide_viewport", true);
3789 boolean displayWebpageImages = sharedPreferences.getBoolean("display_webpage_images", true);
3791 // Get the WebView theme entry values string array.
3792 String[] webViewThemeEntryValuesStringArray = getResources().getStringArray(R.array.webview_theme_entry_values);
3794 // Get a handle for the cookie manager.
3795 CookieManager cookieManager = CookieManager.getInstance();
3797 // Initialize the user agent array adapter and string array.
3798 ArrayAdapter<CharSequence> userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item);
3799 String[] userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
3801 if (nestedScrollWebView.getDomainSettingsApplied()) { // The url has custom domain settings.
3802 // Get a cursor for the current host and move it to the first position.
3803 Cursor currentDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3804 currentDomainSettingsCursor.moveToFirst();
3806 // Get the settings from the cursor.
3807 nestedScrollWebView.setDomainSettingsDatabaseId(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper._ID)));
3808 nestedScrollWebView.getSettings().setJavaScriptEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3809 nestedScrollWebView.setAcceptCookies(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.COOKIES)) == 1);
3810 nestedScrollWebView.getSettings().setDomStorageEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3811 // Form data can be removed once the minimum API >= 26.
3812 boolean saveFormData = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3813 nestedScrollWebView.setEasyListEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3814 nestedScrollWebView.setEasyPrivacyEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3815 nestedScrollWebView.setFanboysAnnoyanceListEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3816 nestedScrollWebView.setFanboysSocialBlockingListEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(
3817 DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3818 nestedScrollWebView.setUltraListEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ULTRALIST)) == 1);
3819 nestedScrollWebView.setUltraPrivacyEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_ULTRAPRIVACY)) == 1);
3820 nestedScrollWebView.setBlockAllThirdPartyRequests(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
3821 String userAgentName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.USER_AGENT));
3822 int fontSize = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.FONT_SIZE));
3823 int swipeToRefreshInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
3824 int webViewThemeInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.WEBVIEW_THEME));
3825 int wideViewportInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.WIDE_VIEWPORT));
3826 int displayWebpageImagesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.DISPLAY_IMAGES));
3827 boolean pinnedSslCertificate = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3828 String pinnedSslIssuedToCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3829 String pinnedSslIssuedToOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3830 String pinnedSslIssuedToUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3831 String pinnedSslIssuedByCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3832 String pinnedSslIssuedByOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3833 String pinnedSslIssuedByUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3834 Date pinnedSslStartDate = new Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_START_DATE)));
3835 Date pinnedSslEndDate = new Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_END_DATE)));
3836 boolean pinnedIpAddresses = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.PINNED_IP_ADDRESSES)) == 1);
3837 String pinnedHostIpAddresses = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.IP_ADDRESSES));
3839 // Close the current host domain settings cursor.
3840 currentDomainSettingsCursor.close();
3842 // If there is a pinned SSL certificate, store it in the WebView.
3843 if (pinnedSslCertificate) {
3844 nestedScrollWebView.setPinnedSslCertificate(pinnedSslIssuedToCName, pinnedSslIssuedToOName, pinnedSslIssuedToUName, pinnedSslIssuedByCName, pinnedSslIssuedByOName, pinnedSslIssuedByUName,
3845 pinnedSslStartDate, pinnedSslEndDate);
3848 // If there is a pinned IP address, store it in the WebView.
3849 if (pinnedIpAddresses) {
3850 nestedScrollWebView.setPinnedIpAddresses(pinnedHostIpAddresses);
3853 // Apply the cookie domain settings.
3854 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptCookies());
3856 // Apply the form data setting if the API < 26.
3857 if (Build.VERSION.SDK_INT < 26) {
3858 nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
3861 // Apply the font size.
3862 try { // Try the specified font size to see if it is valid.
3863 if (fontSize == 0) { // Apply the default font size.
3864 // Try to set the font size from the value in the app settings.
3865 nestedScrollWebView.getSettings().setTextZoom(Integer.parseInt(defaultFontSizeString));
3866 } else { // Apply the font size from domain settings.
3867 nestedScrollWebView.getSettings().setTextZoom(fontSize);
3869 } catch (Exception exception) { // The specified font size is invalid
3870 // Set the font size to be 100%
3871 nestedScrollWebView.getSettings().setTextZoom(100);
3874 // Set the user agent.
3875 if (userAgentName.equals(getString(R.string.system_default_user_agent))) { // Use the system default user agent.
3876 // Get the array position of the default user agent name.
3877 int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3879 // Set the user agent according to the system default.
3880 switch (defaultUserAgentArrayPosition) {
3881 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
3882 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3883 nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
3886 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3887 // Set the user agent to `""`, which uses the default value.
3888 nestedScrollWebView.getSettings().setUserAgentString("");
3891 case SETTINGS_CUSTOM_USER_AGENT:
3892 // Set the default custom user agent.
3893 nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
3897 // Get the user agent string from the user agent data array
3898 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
3900 } else { // Set the user agent according to the stored name.
3901 // Get the array position of the user agent name.
3902 int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
3904 switch (userAgentArrayPosition) {
3905 case UNRECOGNIZED_USER_AGENT: // The user agent name contains a custom user agent.
3906 nestedScrollWebView.getSettings().setUserAgentString(userAgentName);
3909 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3910 // Set the user agent to `""`, which uses the default value.
3911 nestedScrollWebView.getSettings().setUserAgentString("");
3915 // Get the user agent string from the user agent data array.
3916 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3920 // Set swipe to refresh.
3921 switch (swipeToRefreshInt) {
3922 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
3923 // Store the swipe to refresh status in the nested scroll WebView.
3924 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
3926 // Update the swipe refresh layout.
3927 if (defaultSwipeToRefresh) { // Swipe to refresh is enabled.
3928 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
3929 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
3930 } else { // Swipe to refresh is disabled.
3931 // Disable the swipe refresh layout.
3932 swipeRefreshLayout.setEnabled(false);
3936 case DomainsDatabaseHelper.ENABLED:
3937 // Store the swipe to refresh status in the nested scroll WebView.
3938 nestedScrollWebView.setSwipeToRefresh(true);
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);
3944 case DomainsDatabaseHelper.DISABLED:
3945 // Store the swipe to refresh status in the nested scroll WebView.
3946 nestedScrollWebView.setSwipeToRefresh(false);
3948 // Disable swipe to refresh.
3949 swipeRefreshLayout.setEnabled(false);
3952 // Check to see if WebView themes are supported.
3953 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
3954 // Set the WebView theme.
3955 switch (webViewThemeInt) {
3956 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
3957 // Set the WebView theme. A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
3958 if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) { // The light theme is selected.
3959 // Turn off the WebView dark mode.
3960 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
3961 } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) { // The dark theme is selected.
3962 // Turn on the WebView dark mode.
3963 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
3964 } else { // The system default theme is selected.
3965 // Get the current system theme status.
3966 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
3968 // Set the WebView theme according to the current system theme status.
3969 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) { // The system is in day mode.
3970 // Turn off the WebView dark mode.
3971 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
3972 } else { // The system is in night mode.
3973 // Turn on the WebView dark mode.
3974 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
3979 case DomainsDatabaseHelper.LIGHT_THEME:
3980 // Turn off the WebView dark mode.
3981 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
3984 case DomainsDatabaseHelper.DARK_THEME:
3985 // Turn on the WebView dark mode.
3986 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
3991 // Set the viewport.
3992 switch (wideViewportInt) {
3993 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
3994 nestedScrollWebView.getSettings().setUseWideViewPort(wideViewport);
3997 case DomainsDatabaseHelper.ENABLED:
3998 nestedScrollWebView.getSettings().setUseWideViewPort(true);
4001 case DomainsDatabaseHelper.DISABLED:
4002 nestedScrollWebView.getSettings().setUseWideViewPort(false);
4006 // Set the loading of webpage images.
4007 switch (displayWebpageImagesInt) {
4008 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4009 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
4012 case DomainsDatabaseHelper.ENABLED:
4013 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(true);
4016 case DomainsDatabaseHelper.DISABLED:
4017 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(false);
4021 // Get the current theme status.
4022 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4024 // Set a background on the URL relative layout to indicate that custom domain settings are being used.
4025 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4026 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.url_bar_background_light_green, null));
4028 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.url_bar_background_dark_blue, null));
4030 } else { // The new URL does not have custom domain settings. Load the defaults.
4031 // Store the values from the shared preferences.
4032 nestedScrollWebView.getSettings().setJavaScriptEnabled(sharedPreferences.getBoolean("javascript", false));
4033 nestedScrollWebView.setAcceptCookies(sharedPreferences.getBoolean(getString(R.string.cookies_key), false));
4034 nestedScrollWebView.getSettings().setDomStorageEnabled(sharedPreferences.getBoolean("dom_storage", false));
4035 boolean saveFormData = sharedPreferences.getBoolean("save_form_data", false); // Form data can be removed once the minimum API >= 26.
4036 nestedScrollWebView.setEasyListEnabled(sharedPreferences.getBoolean("easylist", true));
4037 nestedScrollWebView.setEasyPrivacyEnabled(sharedPreferences.getBoolean("easyprivacy", true));
4038 nestedScrollWebView.setFanboysAnnoyanceListEnabled(sharedPreferences.getBoolean("fanboys_annoyance_list", true));
4039 nestedScrollWebView.setFanboysSocialBlockingListEnabled(sharedPreferences.getBoolean("fanboys_social_blocking_list", true));
4040 nestedScrollWebView.setUltraListEnabled(sharedPreferences.getBoolean("ultralist", true));
4041 nestedScrollWebView.setUltraPrivacyEnabled(sharedPreferences.getBoolean("ultraprivacy", true));
4042 nestedScrollWebView.setBlockAllThirdPartyRequests(sharedPreferences.getBoolean("block_all_third_party_requests", false));
4044 // Apply the default cookie setting.
4045 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptCookies());
4047 // Apply the default font size setting.
4049 // Try to set the font size from the value in the app settings.
4050 nestedScrollWebView.getSettings().setTextZoom(Integer.parseInt(defaultFontSizeString));
4051 } catch (Exception exception) {
4052 // If the app settings value is invalid, set the font size to 100%.
4053 nestedScrollWebView.getSettings().setTextZoom(100);
4056 // Apply the form data setting if the API < 26.
4057 if (Build.VERSION.SDK_INT < 26) {
4058 nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
4061 // Store the swipe to refresh status in the nested scroll WebView.
4062 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
4064 // Update the swipe refresh layout.
4065 if (defaultSwipeToRefresh) { // Swipe to refresh is enabled.
4066 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
4067 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
4068 } else { // Swipe to refresh is disabled.
4069 // Disable the swipe refresh layout.
4070 swipeRefreshLayout.setEnabled(false);
4073 // Reset the pinned variables.
4074 nestedScrollWebView.setDomainSettingsDatabaseId(-1);
4076 // Get the array position of the user agent name.
4077 int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
4079 // Set the user agent.
4080 switch (userAgentArrayPosition) {
4081 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
4082 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
4083 nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
4086 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4087 // Set the user agent to `""`, which uses the default value.
4088 nestedScrollWebView.getSettings().setUserAgentString("");
4091 case SETTINGS_CUSTOM_USER_AGENT:
4092 // Set the default custom user agent.
4093 nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
4097 // Get the user agent string from the user agent data array
4098 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4101 // Apply the WebView theme if supported by the installed WebView.
4102 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
4103 // Set the WebView theme. A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
4104 if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) { // The light theme is selected.
4105 // Turn off the WebView dark mode.
4106 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4107 } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) { // The dark theme is selected.
4108 // Turn on the WebView dark mode.
4109 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4110 } else { // The system default theme is selected.
4111 // Get the current system theme status.
4112 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4114 // Set the WebView theme according to the current system theme status.
4115 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) { // The system is in day mode.
4116 // Turn off the WebView dark mode.
4117 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4118 } else { // The system is in night mode.
4119 // Turn on the WebView dark mode.
4120 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4125 // Set the viewport.
4126 nestedScrollWebView.getSettings().setUseWideViewPort(wideViewport);
4128 // Set the loading of webpage images.
4129 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
4131 // Set a transparent background on the URL relative layout.
4132 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.color.transparent, null));
4135 // Close the domains database helper.
4136 domainsDatabaseHelper.close();
4138 // Update the privacy icons.
4139 updatePrivacyIcons(true);
4142 // Reload the website if returning from the Domains activity.
4143 if (reloadWebsite) {
4144 nestedScrollWebView.reload();
4147 // 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.
4149 nestedScrollWebView.loadUrl(url, customHeaders);
4153 private void applyProxy(boolean reloadWebViews) {
4154 // Set the proxy according to the mode.
4155 proxyHelper.setProxy(getApplicationContext(), appBarLayout, proxyMode);
4157 // Reset the waiting for proxy tracker.
4158 waitingForProxy = false;
4160 // Get the current theme status.
4161 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4163 // Update the user interface and reload the WebViews if requested.
4164 switch (proxyMode) {
4165 case ProxyHelper.NONE:
4166 // Initialize a color background typed value.
4167 TypedValue colorBackgroundTypedValue = new TypedValue();
4169 // Get the color background from the theme.
4170 getTheme().resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true);
4172 // Get the color background int from the typed value.
4173 int colorBackgroundInt = colorBackgroundTypedValue.data;
4175 // Set the default app bar layout background.
4176 appBarLayout.setBackgroundColor(colorBackgroundInt);
4179 case ProxyHelper.TOR:
4180 // Set the app bar background to indicate proxying through Orbot is enabled.
4181 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4182 appBarLayout.setBackgroundResource(R.color.blue_50);
4184 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4187 // Check to see if Orbot is installed.
4189 // Get the package manager.
4190 PackageManager packageManager = getPackageManager();
4192 // 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.
4193 packageManager.getPackageInfo("org.torproject.android", 0);
4195 // Check to see if the proxy is ready.
4196 if (!orbotStatus.equals(ProxyHelper.ORBOT_STATUS_ON)) { // Orbot is not ready.
4197 // Set the waiting for proxy status.
4198 waitingForProxy = true;
4200 // Show the waiting for proxy dialog if it isn't already displayed.
4201 if (getSupportFragmentManager().findFragmentByTag(getString(R.string.waiting_for_proxy_dialog)) == null) {
4202 // Get a handle for the waiting for proxy alert dialog.
4203 DialogFragment waitingForProxyDialogFragment = new WaitingForProxyDialog();
4205 // Try to show the dialog. Sometimes the window is not yet active if returning from Settings.
4207 // Show the waiting for proxy alert dialog.
4208 waitingForProxyDialogFragment.show(getSupportFragmentManager(), getString(R.string.waiting_for_proxy_dialog));
4209 } catch (Exception waitingForTorException) {
4210 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
4211 pendingDialogsArrayList.add(new PendingDialog(waitingForProxyDialogFragment, getString(R.string.waiting_for_proxy_dialog)));
4215 } catch (PackageManager.NameNotFoundException exception) { // Orbot is not installed.
4216 // Show the Orbot not installed dialog if it is not already displayed.
4217 if (getSupportFragmentManager().findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
4218 // Get a handle for the Orbot not installed alert dialog.
4219 DialogFragment orbotNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode);
4221 // Try to show the dialog. Sometimes the window is not yet active if returning from Settings.
4223 // Display the Orbot not installed alert dialog.
4224 orbotNotInstalledDialogFragment.show(getSupportFragmentManager(), getString(R.string.proxy_not_installed_dialog));
4225 } catch (Exception orbotNotInstalledException) {
4226 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
4227 pendingDialogsArrayList.add(new PendingDialog(orbotNotInstalledDialogFragment, getString(R.string.proxy_not_installed_dialog)));
4233 case ProxyHelper.I2P:
4234 // Set the app bar background to indicate proxying through Orbot is enabled.
4235 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4236 appBarLayout.setBackgroundResource(R.color.blue_50);
4238 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4241 // Check to see if I2P is installed.
4243 // Get the package manager.
4244 PackageManager packageManager = getPackageManager();
4246 // 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.
4247 packageManager.getPackageInfo("net.i2p.android.router", 0);
4248 } catch (PackageManager.NameNotFoundException exception) { // I2P is not installed.
4249 // Sow the I2P not installed dialog if it is not already displayed.
4250 if (getSupportFragmentManager().findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
4251 // Get a handle for the waiting for proxy alert dialog.
4252 DialogFragment i2pNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode);
4254 // Try to show the dialog. Sometimes the window is not yet active if returning from Settings.
4256 // Display the I2P not installed alert dialog.
4257 i2pNotInstalledDialogFragment.show(getSupportFragmentManager(), getString(R.string.proxy_not_installed_dialog));
4258 } catch (Exception i2pNotInstalledException) {
4259 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
4260 pendingDialogsArrayList.add(new PendingDialog(i2pNotInstalledDialogFragment, getString(R.string.proxy_not_installed_dialog)));
4266 case ProxyHelper.CUSTOM:
4267 // Set the app bar background to indicate proxying through Orbot is enabled.
4268 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4269 appBarLayout.setBackgroundResource(R.color.blue_50);
4271 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4276 // Reload the WebViews if requested and not waiting for the proxy.
4277 if (reloadWebViews && !waitingForProxy) {
4278 // Reload the WebViews.
4279 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4280 // Get the WebView tab fragment.
4281 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4283 // Get the fragment view.
4284 View fragmentView = webViewTabFragment.getView();
4286 // Only reload the WebViews if they exist.
4287 if (fragmentView != null) {
4288 // Get the nested scroll WebView from the tab fragment.
4289 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4291 // Reload the WebView.
4292 nestedScrollWebView.reload();
4298 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
4299 // Only update the privacy icons if the options menu and the current WebView have already been populated.
4300 if ((optionsMenu != null) && (currentWebView != null)) {
4301 // Update the privacy icon.
4302 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is enabled.
4303 optionsPrivacyMenuItem.setIcon(R.drawable.javascript_enabled);
4304 } else if (currentWebView.getAcceptCookies()) { // JavaScript is disabled but cookies are enabled.
4305 optionsPrivacyMenuItem.setIcon(R.drawable.warning);
4306 } else { // All the dangerous features are disabled.
4307 optionsPrivacyMenuItem.setIcon(R.drawable.privacy_mode);
4310 // Get the current theme status.
4311 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4313 // Update the cookies icon.
4314 if (currentWebView.getAcceptCookies()) { // Cookies are enabled.
4315 optionsCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
4316 } else { // Cookies are disabled.
4317 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4318 optionsCookiesMenuItem.setIcon(R.drawable.cookies_disabled_day);
4320 optionsCookiesMenuItem.setIcon(R.drawable.cookies_disabled_night);
4324 // Update the refresh icon.
4325 if (optionsRefreshMenuItem.getTitle() == getString(R.string.refresh)) { // The refresh icon is displayed.
4326 // Set the icon according to the theme.
4327 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4328 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled_day);
4330 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled_night);
4332 } else { // The stop icon is displayed.
4333 // Set the icon according to the theme.
4334 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4335 optionsRefreshMenuItem.setIcon(R.drawable.close_blue_day);
4337 optionsRefreshMenuItem.setIcon(R.drawable.close_blue_night);
4341 // `invalidateOptionsMenu()` calls `onPrepareOptionsMenu()` and redraws the icons in the app bar.
4342 if (runInvalidateOptionsMenu) {
4343 invalidateOptionsMenu();
4348 private void highlightUrlText() {
4349 // Only highlight the URL text if the box is not currently selected.
4350 if (!urlEditText.hasFocus()) {
4351 // Get the URL string.
4352 String urlString = urlEditText.getText().toString();
4354 // Highlight the URL according to the protocol.
4355 if (urlString.startsWith("file://") || urlString.startsWith("content://")) { // This is a file or content URL.
4356 // De-emphasize everything before the file name.
4357 urlEditText.getText().setSpan(initialGrayColorSpan, 0, urlString.lastIndexOf("/") + 1,Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4358 } else { // This is a web URL.
4359 // Get the index of the `/` immediately after the domain name.
4360 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
4362 // Create a base URL string.
4365 // Get the base URL.
4366 if (endOfDomainName > 0) { // There is at least one character after the base URL.
4367 // Get the base URL.
4368 baseUrl = urlString.substring(0, endOfDomainName);
4369 } else { // There are no characters after the base URL.
4370 // Set the base URL to be the entire URL string.
4371 baseUrl = urlString;
4374 // Get the index of the last `.` in the domain.
4375 int lastDotIndex = baseUrl.lastIndexOf(".");
4377 // Get the index of the penultimate `.` in the domain.
4378 int penultimateDotIndex = baseUrl.lastIndexOf(".", lastDotIndex - 1);
4380 // Markup the beginning of the URL.
4381 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
4382 urlEditText.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4384 // De-emphasize subdomains.
4385 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
4386 urlEditText.getText().setSpan(initialGrayColorSpan, 7, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4388 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
4389 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
4390 // De-emphasize the protocol and the additional subdomains.
4391 urlEditText.getText().setSpan(initialGrayColorSpan, 0, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4392 } else { // There is only one subdomain in the domain name.
4393 // De-emphasize only the protocol.
4394 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4398 // De-emphasize the text after the domain name.
4399 if (endOfDomainName > 0) {
4400 urlEditText.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4406 private void loadBookmarksFolder() {
4407 // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
4408 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
4410 // Populate the bookmarks cursor adapter.
4411 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
4413 public View newView(Context context, Cursor cursor, ViewGroup parent) {
4414 // Inflate the individual item layout.
4415 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
4419 public void bindView(View view, Context context, Cursor cursor) {
4420 // Get handles for the views.
4421 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
4422 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
4424 // Get the favorite icon byte array from the cursor.
4425 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.FAVORITE_ICON));
4427 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
4428 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
4430 // Display the bitmap in `bookmarkFavoriteIcon`.
4431 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
4433 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
4434 String bookmarkNameString = cursor.getString(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME));
4435 bookmarkNameTextView.setText(bookmarkNameString);
4437 // Make the font bold for folders.
4438 if (cursor.getInt(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
4439 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
4440 } else { // Reset the font to default for normal bookmarks.
4441 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
4446 // Get a handle for the bookmarks list view.
4447 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
4449 // Populate the list view with the adapter.
4450 bookmarksListView.setAdapter(bookmarksCursorAdapter);
4452 // Get a handle for the bookmarks title text view.
4453 TextView bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
4455 // Set the bookmarks drawer title.
4456 if (currentBookmarksFolder.isEmpty()) {
4457 bookmarksTitleTextView.setText(R.string.bookmarks);
4459 bookmarksTitleTextView.setText(currentBookmarksFolder);
4463 private void openWithApp(String url) {
4464 // Create an open with app intent with `ACTION_VIEW`.
4465 Intent openWithAppIntent = new Intent(Intent.ACTION_VIEW);
4467 // Set the URI but not the MIME type. This should open all available apps.
4468 openWithAppIntent.setData(Uri.parse(url));
4470 // Flag the intent to open in a new task.
4471 openWithAppIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4475 // Show the chooser.
4476 startActivity(openWithAppIntent);
4477 } catch (ActivityNotFoundException exception) { // There are no apps available to open the URL.
4478 // Show a snackbar with the error.
4479 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
4483 private void openWithBrowser(String url) {
4484 // Create an open with browser intent with `ACTION_VIEW`.
4485 Intent openWithBrowserIntent = new Intent(Intent.ACTION_VIEW);
4487 // Set the URI and the MIME type. `"text/html"` should load browser options.
4488 openWithBrowserIntent.setDataAndType(Uri.parse(url), "text/html");
4490 // Flag the intent to open in a new task.
4491 openWithBrowserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4495 // Show the chooser.
4496 startActivity(openWithBrowserIntent);
4497 } catch (ActivityNotFoundException exception) { // There are no browsers available to open the URL.
4498 // Show a snackbar with the error.
4499 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
4503 private String sanitizeUrl(String url) {
4504 // Sanitize Google Analytics.
4505 if (sanitizeGoogleAnalytics) {
4507 if (url.contains("?utm_")) {
4508 url = url.substring(0, url.indexOf("?utm_"));
4512 if (url.contains("&utm_")) {
4513 url = url.substring(0, url.indexOf("&utm_"));
4517 // Sanitize Facebook Click IDs.
4518 if (sanitizeFacebookClickIds) {
4519 // Remove `?fbclid=`.
4520 if (url.contains("?fbclid=")) {
4521 url = url.substring(0, url.indexOf("?fbclid="));
4524 // Remove `&fbclid=`.
4525 if (url.contains("&fbclid=")) {
4526 url = url.substring(0, url.indexOf("&fbclid="));
4529 // Remove `?fbadid=`.
4530 if (url.contains("?fbadid=")) {
4531 url = url.substring(0, url.indexOf("?fbadid="));
4534 // Remove `&fbadid=`.
4535 if (url.contains("&fbadid=")) {
4536 url = url.substring(0, url.indexOf("&fbadid="));
4540 // Sanitize Twitter AMP redirects.
4541 if (sanitizeTwitterAmpRedirects) {
4543 if (url.contains("?amp=1")) {
4544 url = url.substring(0, url.indexOf("?amp=1"));
4548 // Return the sanitized URL.
4552 public void finishedPopulatingBlocklists(ArrayList<ArrayList<List<String[]>>> combinedBlocklists) {
4553 // Store the blocklists.
4554 easyList = combinedBlocklists.get(0);
4555 easyPrivacy = combinedBlocklists.get(1);
4556 fanboysAnnoyanceList = combinedBlocklists.get(2);
4557 fanboysSocialList = combinedBlocklists.get(3);
4558 ultraList = combinedBlocklists.get(4);
4559 ultraPrivacy = combinedBlocklists.get(5);
4561 // Check to see if the activity has been restarted with a saved state.
4562 if ((savedStateArrayList == null) || (savedStateArrayList.size() == 0)) { // The activity has not been restarted or it was restarted on start to force the night theme.
4563 // Add the first tab.
4564 addNewTab("", true);
4565 } else { // The activity has been restarted.
4566 // Restore each tab. Once the minimum API >= 24, a `forEach()` command can be used.
4567 for (int i = 0; i < savedStateArrayList.size(); i++) {
4569 tabLayout.addTab(tabLayout.newTab());
4572 TabLayout.Tab newTab = tabLayout.getTabAt(i);
4574 // Remove the lint warning below that the current tab might be null.
4575 assert newTab != null;
4577 // Set a custom view on the new tab.
4578 newTab.setCustomView(R.layout.tab_custom_view);
4580 // Add the new page.
4581 webViewPagerAdapter.restorePage(savedStateArrayList.get(i), savedNestedScrollWebViewStateArrayList.get(i));
4584 // Reset the saved state variables.
4585 savedStateArrayList = null;
4586 savedNestedScrollWebViewStateArrayList = null;
4588 // Restore the selected tab position.
4589 if (savedTabPosition == 0) { // The first tab is selected.
4590 // Set the first page as the current WebView.
4591 setCurrentWebView(0);
4592 } else { // the first tab is not selected.
4593 // Move to the selected tab.
4594 webViewPager.setCurrentItem(savedTabPosition);
4597 // Get the intent that started the app.
4598 Intent intent = getIntent();
4600 // Reset the intent. This prevents a duplicate tab from being created on restart.
4601 setIntent(new Intent());
4603 // Get the information from the intent.
4604 String intentAction = intent.getAction();
4605 Uri intentUriData = intent.getData();
4606 String intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT);
4608 // Determine if this is a web search.
4609 boolean isWebSearch = ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH));
4611 // 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.
4612 if (intentUriData != null || intentStringExtra != null || isWebSearch) {
4613 // Get the shared preferences.
4614 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4616 // Create a URL string.
4619 // If the intent action is a web search, perform the search.
4620 if (isWebSearch) { // The intent is a web search.
4621 // Create an encoded URL string.
4622 String encodedUrlString;
4624 // Sanitize the search input and convert it to a search.
4626 encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
4627 } catch (UnsupportedEncodingException exception) {
4628 encodedUrlString = "";
4631 // Add the base search URL.
4632 url = searchURL + encodedUrlString;
4633 } else if (intentUriData != null) { // The intent contains a URL formatted as a URI.
4634 // Set the intent data as the URL.
4635 url = intentUriData.toString();
4636 } else { // The intent contains a string, which might be a URL.
4637 // Set the intent string as the URL.
4638 url = intentStringExtra;
4641 // Add a new tab if specified in the preferences.
4642 if (sharedPreferences.getBoolean("open_intents_in_new_tab", true)) { // Load the URL in a new tab.
4643 // Set the loading new intent flag.
4644 loadingNewIntent = true;
4647 addNewTab(url, true);
4648 } else { // Load the URL in the current tab.
4650 loadUrl(currentWebView, url);
4656 public void addTab(View view) {
4657 // Add a new tab with a blank URL.
4658 addNewTab("", true);
4661 private void addNewTab(String url, boolean moveToTab) {
4662 // Clear the focus from the URL edit text, so that it will be populated with the information from the new tab.
4663 urlEditText.clearFocus();
4665 // Get the new page number. The page numbers are 0 indexed, so the new page number will match the current count.
4666 int newTabNumber = tabLayout.getTabCount();
4669 tabLayout.addTab(tabLayout.newTab());
4672 TabLayout.Tab newTab = tabLayout.getTabAt(newTabNumber);
4674 // Remove the lint warning below that the current tab might be null.
4675 assert newTab != null;
4677 // Set a custom view on the new tab.
4678 newTab.setCustomView(R.layout.tab_custom_view);
4680 // Add the new WebView page.
4681 webViewPagerAdapter.addPage(newTabNumber, webViewPager, url, moveToTab);
4683 // Show the app bar if it is at the bottom of the screen and the new tab is taking focus.
4684 if (bottomAppBar && moveToTab && (appBarLayout.getTranslationY() != 0)) {
4685 // Animate the bottom app bar onto the screen.
4686 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0);
4689 objectAnimator.start();
4693 public void closeTab(View view) {
4694 // Run the command according to the number of tabs.
4695 if (tabLayout.getTabCount() > 1) { // There is more than one tab open.
4696 // Close the current tab.
4698 } else { // There is only one tab open.
4703 private void closeCurrentTab() {
4704 // Get the current tab number.
4705 int currentTabNumber = tabLayout.getSelectedTabPosition();
4707 // Delete the current tab.
4708 tabLayout.removeTabAt(currentTabNumber);
4710 // 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,
4711 // meaning that the current WebView must be reset. Otherwise it will happen automatically as the selected tab number changes.
4712 if (webViewPagerAdapter.deletePage(currentTabNumber, webViewPager)) {
4713 setCurrentWebView(currentTabNumber);
4717 private void exitFullScreenVideo() {
4718 // Re-enable the screen timeout.
4719 fullScreenVideoFrameLayout.setKeepScreenOn(false);
4721 // Unset the full screen video flag.
4722 displayingFullScreenVideo = false;
4724 // Remove all the views from the full screen video frame layout.
4725 fullScreenVideoFrameLayout.removeAllViews();
4727 // Hide the full screen video frame layout.
4728 fullScreenVideoFrameLayout.setVisibility(View.GONE);
4730 // Enable the sliding drawers.
4731 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
4733 // Show the coordinator layout.
4734 coordinatorLayout.setVisibility(View.VISIBLE);
4736 // Apply the appropriate full screen mode flags.
4737 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
4738 // Hide the app bar if specified.
4740 // Hide the tab linear layout.
4741 tabsLinearLayout.setVisibility(View.GONE);
4743 // Hide the action bar.
4747 /* Hide the system bars.
4748 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4749 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4750 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4751 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4753 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
4754 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
4755 } else { // Switch to normal viewing mode.
4756 // Remove the `SYSTEM_UI` flags from the root frame layout.
4757 rootFrameLayout.setSystemUiVisibility(0);
4761 private void clearAndExit() {
4762 // Get a handle for the shared preferences.
4763 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4765 // Close the bookmarks cursor and database.
4766 bookmarksCursor.close();
4767 bookmarksDatabaseHelper.close();
4769 // Get the status of the clear everything preference.
4770 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
4772 // Get a handle for the runtime.
4773 Runtime runtime = Runtime.getRuntime();
4775 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
4776 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
4777 String privateDataDirectoryString = getApplicationInfo().dataDir;
4780 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
4781 // The command to remove cookies changed slightly in API 21.
4782 if (Build.VERSION.SDK_INT >= 21) {
4783 CookieManager.getInstance().removeAllCookies(null);
4785 CookieManager.getInstance().removeAllCookie();
4788 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4790 // Two commands must be used because `Runtime.exec()` does not like `*`.
4791 Process deleteCookiesProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
4792 Process deleteCookiesJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
4794 // Wait until the processes have finished.
4795 deleteCookiesProcess.waitFor();
4796 deleteCookiesJournalProcess.waitFor();
4797 } catch (Exception exception) {
4798 // Do nothing if an error is thrown.
4802 // Clear DOM storage.
4803 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
4804 // Ask `WebStorage` to clear the DOM storage.
4805 WebStorage webStorage = WebStorage.getInstance();
4806 webStorage.deleteAllData();
4808 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4810 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4811 Process deleteLocalStorageProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
4813 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
4814 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
4815 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
4816 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
4817 Process deleteDatabaseProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
4819 // Wait until the processes have finished.
4820 deleteLocalStorageProcess.waitFor();
4821 deleteIndexProcess.waitFor();
4822 deleteQuotaManagerProcess.waitFor();
4823 deleteQuotaManagerJournalProcess.waitFor();
4824 deleteDatabaseProcess.waitFor();
4825 } catch (Exception exception) {
4826 // Do nothing if an error is thrown.
4830 // Clear form data if the API < 26.
4831 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
4832 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
4833 webViewDatabase.clearFormData();
4835 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4837 // A string array must be used because the database contains a space and `Runtime.exec` will not otherwise escape the string correctly.
4838 Process deleteWebDataProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
4839 Process deleteWebDataJournalProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
4841 // Wait until the processes have finished.
4842 deleteWebDataProcess.waitFor();
4843 deleteWebDataJournalProcess.waitFor();
4844 } catch (Exception exception) {
4845 // Do nothing if an error is thrown.
4849 // Clear the logcat.
4850 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_logcat_key), true)) {
4852 // Clear the logcat. `-c` clears the logcat. `-b all` clears all the buffers (instead of just crash, main, and system).
4853 Process process = Runtime.getRuntime().exec("logcat -b all -c");
4855 // Wait for the process to finish.
4857 } catch (IOException|InterruptedException exception) {
4863 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
4864 // Clear the cache from each WebView.
4865 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4866 // Get the WebView tab fragment.
4867 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4869 // Get the WebView fragment view.
4870 View webViewFragmentView = webViewTabFragment.getView();
4872 // Only clear the cache if the WebView exists.
4873 if (webViewFragmentView != null) {
4874 // Get the nested scroll WebView from the tab fragment.
4875 NestedScrollWebView nestedScrollWebView = webViewFragmentView.findViewById(R.id.nestedscroll_webview);
4877 // Clear the cache for this WebView.
4878 nestedScrollWebView.clearCache(true);
4882 // Manually delete the cache directories.
4884 // Delete the main cache directory.
4885 Process deleteCacheProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/cache");
4887 // Delete the secondary `Service Worker` cache directory.
4888 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4889 Process deleteServiceWorkerProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
4891 // Wait until the processes have finished.
4892 deleteCacheProcess.waitFor();
4893 deleteServiceWorkerProcess.waitFor();
4894 } catch (Exception exception) {
4895 // Do nothing if an error is thrown.
4899 // Wipe out each WebView.
4900 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4901 // Get the WebView tab fragment.
4902 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4904 // Get the WebView frame layout.
4905 FrameLayout webViewFrameLayout = (FrameLayout) webViewTabFragment.getView();
4907 // Only wipe out the WebView if it exists.
4908 if (webViewFrameLayout != null) {
4909 // Get the nested scroll WebView from the tab fragment.
4910 NestedScrollWebView nestedScrollWebView = webViewFrameLayout.findViewById(R.id.nestedscroll_webview);
4912 // Clear SSL certificate preferences for this WebView.
4913 nestedScrollWebView.clearSslPreferences();
4915 // Clear the back/forward history for this WebView.
4916 nestedScrollWebView.clearHistory();
4918 // Remove all the views from the frame layout.
4919 webViewFrameLayout.removeAllViews();
4921 // Destroy the internal state of the WebView.
4922 nestedScrollWebView.destroy();
4926 // Clear the custom headers.
4927 customHeaders.clear();
4929 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
4930 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
4931 if (clearEverything) {
4933 // Delete the folder.
4934 Process deleteAppWebviewProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
4936 // Wait until the process has finished.
4937 deleteAppWebviewProcess.waitFor();
4938 } catch (Exception exception) {
4939 // Do nothing if an error is thrown.
4943 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
4944 if (Build.VERSION.SDK_INT >= 21) {
4945 finishAndRemoveTask();
4950 // Remove the terminated program from RAM. The status code is `0`.
4954 public void bookmarksBack(View view) {
4955 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
4956 // close the bookmarks drawer.
4957 drawerLayout.closeDrawer(GravityCompat.END);
4958 } else { // A subfolder is displayed.
4959 // Place the former parent folder in `currentFolder`.
4960 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolderName(currentBookmarksFolder);
4962 // Load the new folder.
4963 loadBookmarksFolder();
4967 private void setCurrentWebView(int pageNumber) {
4968 // Stop the swipe to refresh indicator if it is running
4969 swipeRefreshLayout.setRefreshing(false);
4971 // Get the WebView tab fragment.
4972 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(pageNumber);
4974 // Get the fragment view.
4975 View webViewFragmentView = webViewTabFragment.getView();
4977 // Set the current WebView if the fragment view is not null.
4978 if (webViewFragmentView != null) { // The fragment has been populated.
4979 // Store the current WebView.
4980 currentWebView = webViewFragmentView.findViewById(R.id.nestedscroll_webview);
4982 // Update the status of swipe to refresh.
4983 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
4984 // Enable the swipe refresh layout if the WebView is scrolled all the way to the top. It is updated every time the scroll changes.
4985 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
4986 } else { // Swipe to refresh is disabled.
4987 // Disable the swipe refresh layout.
4988 swipeRefreshLayout.setEnabled(false);
4991 // Get a handle for the cookie manager.
4992 CookieManager cookieManager = CookieManager.getInstance();
4994 // Set the cookie status.
4995 cookieManager.setAcceptCookie(currentWebView.getAcceptCookies());
4997 // Update the privacy icons. `true` redraws the icons in the app bar.
4998 updatePrivacyIcons(true);
5000 // Get a handle for the input method manager.
5001 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
5003 // Remove the lint warning below that the input method manager might be null.
5004 assert inputMethodManager != null;
5006 // Get the current URL.
5007 String url = currentWebView.getUrl();
5009 // Update the URL edit text if not loading a new intent. Otherwise, this will be handled by `onPageStarted()` (if called) and `onPageFinished()`.
5010 if (!loadingNewIntent) { // A new intent is not being loaded.
5011 if ((url == null) || url.equals("about:blank")) { // The WebView is blank.
5012 // Display the hint in the URL edit text.
5013 urlEditText.setText("");
5015 // Request focus for the URL text box.
5016 urlEditText.requestFocus();
5018 // Display the keyboard.
5019 inputMethodManager.showSoftInput(urlEditText, 0);
5020 } else { // The WebView has a loaded URL.
5021 // Clear the focus from the URL text box.
5022 urlEditText.clearFocus();
5024 // Hide the soft keyboard.
5025 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
5027 // Display the current URL in the URL text box.
5028 urlEditText.setText(url);
5030 // Highlight the URL text.
5033 } else { // A new intent is being loaded.
5034 // Reset the loading new intent tracker.
5035 loadingNewIntent = false;
5038 // Set the background to indicate the domain settings status.
5039 if (currentWebView.getDomainSettingsApplied()) {
5040 // Get the current theme status.
5041 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
5043 // Set a green background on the URL relative layout to indicate that custom domain settings are being used.
5044 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
5045 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.url_bar_background_light_green, null));
5047 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.url_bar_background_dark_blue, null));
5050 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.color.transparent, null));
5052 } else { // The fragment has not been populated. Try again in 100 milliseconds.
5053 // Create a handler to set the current WebView.
5054 Handler setCurrentWebViewHandler = new Handler();
5056 // Create a runnable to set the current WebView.
5057 Runnable setCurrentWebWebRunnable = () -> {
5058 // Set the current WebView.
5059 setCurrentWebView(pageNumber);
5062 // Try setting the current WebView again after 100 milliseconds.
5063 setCurrentWebViewHandler.postDelayed(setCurrentWebWebRunnable, 100);
5067 @SuppressLint("ClickableViewAccessibility")
5069 public void initializeWebView(NestedScrollWebView nestedScrollWebView, int pageNumber, ProgressBar progressBar, String url, Boolean restoringState) {
5070 // Get a handle for the shared preferences.
5071 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
5073 // Get the WebView theme.
5074 String webViewTheme = sharedPreferences.getString("webview_theme", getString(R.string.webview_theme_default_value));
5076 // Get the WebView theme entry values string array.
5077 String[] webViewThemeEntryValuesStringArray = getResources().getStringArray(R.array.webview_theme_entry_values);
5079 // Apply the WebView theme if supported by the installed WebView.
5080 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
5081 // Set the WebView theme. A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
5082 if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) { // The light theme is selected.
5083 // Turn off the WebView dark mode.
5084 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
5086 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
5087 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
5088 nestedScrollWebView.setVisibility(View.VISIBLE);
5089 } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) { // The dark theme is selected.
5090 // Turn on the WebView dark mode.
5091 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
5092 } else { // The system default theme is selected.
5093 // Get the current system theme status.
5094 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
5096 // Set the WebView theme according to the current system theme status.
5097 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) { // The system is in day mode.
5098 // Turn off the WebView dark mode.
5099 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
5101 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
5102 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
5103 nestedScrollWebView.setVisibility(View.VISIBLE);
5104 } else { // The system is in night mode.
5105 // Turn on the WebView dark mode.
5106 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
5111 // Get a handle for the activity
5112 Activity activity = this;
5114 // Get a handle for the input method manager.
5115 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
5117 // Instantiate the blocklist helper.
5118 BlocklistHelper blocklistHelper = new BlocklistHelper();
5120 // Remove the lint warning below that the input method manager might be null.
5121 assert inputMethodManager != null;
5123 // Set the app bar scrolling.
5124 nestedScrollWebView.setNestedScrollingEnabled(scrollAppBar);
5126 // Allow pinch to zoom.
5127 nestedScrollWebView.getSettings().setBuiltInZoomControls(true);
5129 // Hide zoom controls.
5130 nestedScrollWebView.getSettings().setDisplayZoomControls(false);
5132 // Don't allow mixed content (HTTP and HTTPS) on the same website.
5133 if (Build.VERSION.SDK_INT >= 21) {
5134 nestedScrollWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW);
5137 // Set the WebView to load in overview mode (zoomed out to the maximum width).
5138 nestedScrollWebView.getSettings().setLoadWithOverviewMode(true);
5140 // Explicitly disable geolocation.
5141 nestedScrollWebView.getSettings().setGeolocationEnabled(false);
5143 // Allow loading of file:// URLs. This is necessary for opening MHT web archives, which are copies into a temporary cache location.
5144 nestedScrollWebView.getSettings().setAllowFileAccess(true);
5146 // Create a double-tap gesture detector to toggle full-screen mode.
5147 GestureDetector doubleTapGestureDetector = new GestureDetector(getApplicationContext(), new GestureDetector.SimpleOnGestureListener() {
5148 // Override `onDoubleTap()`. All other events are handled using the default settings.
5150 public boolean onDoubleTap(MotionEvent event) {
5151 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
5152 // Toggle the full screen browsing mode tracker.
5153 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
5155 // Toggle the full screen browsing mode.
5156 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
5157 // Hide the app bar if specified.
5159 // Close the find on page bar if it is visible.
5160 closeFindOnPage(null);
5162 // Hide the tab linear layout.
5163 tabsLinearLayout.setVisibility(View.GONE);
5165 // Hide the action bar.
5168 // Set layout and scrolling parameters if the app bar is at the top of the screen.
5169 if (!bottomAppBar) {
5170 // Check to see if the app bar is normally scrolled.
5171 if (scrollAppBar) { // The app bar is scrolled when it is displayed.
5172 // Get the swipe refresh layout parameters.
5173 CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
5175 // Remove the off-screen scrolling layout.
5176 swipeRefreshLayoutParams.setBehavior(null);
5177 } else { // The app bar is not scrolled when it is displayed.
5178 // Remove the padding from the top of the swipe refresh layout.
5179 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5181 // The swipe refresh circle must be moved above the now removed status bar location.
5182 swipeRefreshLayout.setProgressViewOffset(false, -200, defaultProgressViewEndOffset);
5187 /* Hide the system bars.
5188 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5189 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5190 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5191 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5193 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5194 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5195 } else { // Switch to normal viewing mode.
5196 // Show the app bar if it was hidden.
5198 // Show the tab linear layout.
5199 tabsLinearLayout.setVisibility(View.VISIBLE);
5201 // Show the action bar.
5204 // Set layout and scrolling parameters if the app bar is at the top of the screen.
5205 if (!bottomAppBar) {
5206 // Check to see if the app bar is normally scrolled.
5207 if (scrollAppBar) { // The app bar is scrolled when it is displayed.
5208 // Get the swipe refresh layout parameters.
5209 CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
5211 // Add the off-screen scrolling layout.
5212 swipeRefreshLayoutParams.setBehavior(new AppBarLayout.ScrollingViewBehavior());
5213 } else { // The app bar is not scrolled when it is displayed.
5214 // The swipe refresh layout must be manually moved below the app bar layout.
5215 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0);
5217 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5218 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight);
5223 // Remove the `SYSTEM_UI` flags from the root frame layout.
5224 rootFrameLayout.setSystemUiVisibility(0);
5227 // Consume the double-tap.
5229 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
5235 // Pass all touch events on the WebView through the double-tap gesture detector.
5236 nestedScrollWebView.setOnTouchListener((View view, MotionEvent event) -> {
5237 // Call `performClick()` on the view, which is required for accessibility.
5238 view.performClick();
5240 // Send the event to the gesture detector.
5241 return doubleTapGestureDetector.onTouchEvent(event);
5244 // Register the WebView for a context menu. This is used to see link targets and download images.
5245 registerForContextMenu(nestedScrollWebView);
5247 // Allow the downloading of files.
5248 nestedScrollWebView.setDownloadListener((String downloadUrl, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
5249 // Check the download preference.
5250 if (downloadWithExternalApp) { // Download with an external app.
5251 downloadUrlWithExternalApp(downloadUrl);
5252 } else { // Handle the download inside of Privacy Browser.
5253 // Define a formatted file size string.
5254 String formattedFileSizeString;
5256 // Process the content length if it contains data.
5257 if (contentLength > 0) { // The content length is greater than 0.
5258 // Format the content length as a string.
5259 formattedFileSizeString = NumberFormat.getInstance().format(contentLength) + " " + getString(R.string.bytes);
5260 } else { // The content length is not greater than 0.
5261 // Set the formatted file size string to be `unknown size`.
5262 formattedFileSizeString = getString(R.string.unknown_size);
5265 // Get the file name from the content disposition.
5266 String fileNameString = PrepareSaveDialog.getFileNameFromHeaders(this, contentDisposition, mimetype, downloadUrl);
5268 // Instantiate the save dialog.
5269 DialogFragment saveDialogFragment = SaveDialog.saveUrl(downloadUrl, formattedFileSizeString, fileNameString, userAgent,
5270 nestedScrollWebView.getAcceptCookies());
5272 // 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.
5274 // Show the save dialog. It must be named `save_dialog` so that the file picker can update the file name.
5275 saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
5276 } catch (Exception exception) { // The dialog could not be shown.
5277 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
5278 pendingDialogsArrayList.add(new PendingDialog(saveDialogFragment, getString(R.string.save_dialog)));
5283 // Update the find on page count.
5284 nestedScrollWebView.setFindListener(new WebView.FindListener() {
5285 // Get a handle for `findOnPageCountTextView`.
5286 final TextView findOnPageCountTextView = findViewById(R.id.find_on_page_count_textview);
5289 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
5290 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
5291 // Set `findOnPageCountTextView` to `0/0`.
5292 findOnPageCountTextView.setText(R.string.zero_of_zero);
5293 } else if (isDoneCounting) { // There are matches.
5294 // `activeMatchOrdinal` is zero-based.
5295 int activeMatch = activeMatchOrdinal + 1;
5297 // Build the match string.
5298 String matchString = activeMatch + "/" + numberOfMatches;
5300 // Set `findOnPageCountTextView`.
5301 findOnPageCountTextView.setText(matchString);
5306 // Update the status of swipe to refresh based on the scroll position of the nested scroll WebView. Also reinforce full screen browsing mode.
5307 // On API < 23, `getViewTreeObserver().addOnScrollChangedListener()` must be used, but it is a little bit buggy and appears to get garbage collected from time to time.
5308 if (Build.VERSION.SDK_INT >= 23) {
5309 nestedScrollWebView.setOnScrollChangeListener((view, scrollX, scrollY, oldScrollX, oldScrollY) -> {
5310 // Set the swipe to refresh status.
5311 if (nestedScrollWebView.getSwipeToRefresh()) {
5312 // Only enable swipe to refresh if the WebView is scrolled to the top.
5313 swipeRefreshLayout.setEnabled(nestedScrollWebView.getScrollY() == 0);
5315 // Disable swipe to refresh.
5316 swipeRefreshLayout.setEnabled(false);
5319 // Scroll the bottom app bar if enabled.
5320 if (bottomAppBar && scrollAppBar && !objectAnimator.isRunning()) {
5321 if (scrollY < oldScrollY) { // The WebView was scrolled down.
5322 // Animate the bottom app bar onto the screen.
5323 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0);
5326 objectAnimator.start();
5327 } else if (scrollY > oldScrollY) { // The WebView was scrolled up.
5328 // Animate the bottom app bar off the screen.
5329 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", appBarLayout.getHeight());
5332 objectAnimator.start();
5336 // Reinforce the system UI visibility flags if in full screen browsing mode.
5337 // This hides the status and navigation bars, which are displayed if other elements are shown, like dialog boxes, the options menu, or the keyboard.
5338 if (inFullScreenBrowsingMode) {
5339 /* Hide the system bars.
5340 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5341 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5342 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5343 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5345 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5346 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5350 nestedScrollWebView.getViewTreeObserver().addOnScrollChangedListener(() -> {
5351 if (nestedScrollWebView.getSwipeToRefresh()) {
5352 // Only enable swipe to refresh if the WebView is scrolled to the top.
5353 swipeRefreshLayout.setEnabled(nestedScrollWebView.getScrollY() == 0);
5355 // Disable swipe to refresh.
5356 swipeRefreshLayout.setEnabled(false);
5359 // Reinforce the system UI visibility flags if in full screen browsing mode.
5360 // This hides the status and navigation bars, which are displayed if other elements are shown, like dialog boxes, the options menu, or the keyboard.
5361 if (inFullScreenBrowsingMode) {
5362 /* Hide the system bars.
5363 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5364 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5365 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5366 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5368 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5369 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5374 // Set the web chrome client.
5375 nestedScrollWebView.setWebChromeClient(new WebChromeClient() {
5376 // Update the progress bar when a page is loading.
5378 public void onProgressChanged(WebView view, int progress) {
5379 // Update the progress bar.
5380 progressBar.setProgress(progress);
5382 // Set the visibility of the progress bar.
5383 if (progress < 100) {
5384 // Show the progress bar.
5385 progressBar.setVisibility(View.VISIBLE);
5387 // Hide the progress bar.
5388 progressBar.setVisibility(View.GONE);
5390 //Stop the swipe to refresh indicator if it is running
5391 swipeRefreshLayout.setRefreshing(false);
5393 // 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.
5394 nestedScrollWebView.setVisibility(View.VISIBLE);
5398 // Set the favorite icon when it changes.
5400 public void onReceivedIcon(WebView view, Bitmap icon) {
5401 // Only update the favorite icon if the website has finished loading.
5402 if (progressBar.getVisibility() == View.GONE) {
5403 // Store the new favorite icon.
5404 nestedScrollWebView.setFavoriteOrDefaultIcon(icon);
5406 // Get the current page position.
5407 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5409 // Get the current tab.
5410 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
5412 // Check to see if the tab has been populated.
5414 // Get the custom view from the tab.
5415 View tabView = tab.getCustomView();
5417 // Check to see if the custom tab view has been populated.
5418 if (tabView != null) {
5419 // Get the favorite icon image view from the tab.
5420 ImageView tabFavoriteIconImageView = tabView.findViewById(R.id.favorite_icon_imageview);
5422 // Display the favorite icon in the tab.
5423 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
5429 // Save a copy of the title when it changes.
5431 public void onReceivedTitle(WebView view, String title) {
5432 // Get the current page position.
5433 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5435 // Get the current tab.
5436 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
5438 // Only populate the title text view if the tab has been fully created.
5440 // Get the custom view from the tab.
5441 View tabView = tab.getCustomView();
5443 // Only populate the title text view if the tab view has been fully populated.
5444 if (tabView != null) {
5445 // Get the title text view from the tab.
5446 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
5448 // Set the title according to the URL.
5449 if (title.equals("about:blank")) {
5450 // Set the title to indicate a new tab.
5451 tabTitleTextView.setText(R.string.new_tab);
5453 // Set the title as the tab text.
5454 tabTitleTextView.setText(title);
5460 // Enter full screen video.
5462 public void onShowCustomView(View video, CustomViewCallback callback) {
5463 // Set the full screen video flag.
5464 displayingFullScreenVideo = true;
5466 // Hide the keyboard.
5467 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
5469 // Hide the coordinator layout.
5470 coordinatorLayout.setVisibility(View.GONE);
5472 /* Hide the system bars.
5473 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5474 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5475 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5476 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5478 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5479 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5481 // Disable the sliding drawers.
5482 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
5484 // Add the video view to the full screen video frame layout.
5485 fullScreenVideoFrameLayout.addView(video);
5487 // Show the full screen video frame layout.
5488 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
5490 // Disable the screen timeout while the video is playing. YouTube does this automatically, but not all other videos do.
5491 fullScreenVideoFrameLayout.setKeepScreenOn(true);
5494 // Exit full screen video.
5496 public void onHideCustomView() {
5497 // Exit the full screen video.
5498 exitFullScreenVideo();
5503 public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
5504 // Show the file chooser if the device is running API >= 21.
5505 if (Build.VERSION.SDK_INT >= 21) {
5506 // Store the file path callback.
5507 fileChooserCallback = filePathCallback;
5509 // Create an intent to open a chooser based on the file chooser parameters.
5510 Intent fileChooserIntent = fileChooserParams.createIntent();
5512 // Get a handle for the package manager.
5513 PackageManager packageManager = getPackageManager();
5515 // Check to see if the file chooser intent resolves to an installed package.
5516 if (fileChooserIntent.resolveActivity(packageManager) != null) { // The file chooser intent is fine.
5517 // Start the file chooser intent.
5518 startActivityForResult(fileChooserIntent, BROWSE_FILE_UPLOAD_REQUEST_CODE);
5519 } else { // The file chooser intent will cause a crash.
5520 // Create a generic intent to open a chooser.
5521 Intent genericFileChooserIntent = new Intent(Intent.ACTION_GET_CONTENT);
5523 // Request an openable file.
5524 genericFileChooserIntent.addCategory(Intent.CATEGORY_OPENABLE);
5526 // Set the file type to everything.
5527 genericFileChooserIntent.setType("*/*");
5529 // Start the generic file chooser intent.
5530 startActivityForResult(genericFileChooserIntent, BROWSE_FILE_UPLOAD_REQUEST_CODE);
5537 nestedScrollWebView.setWebViewClient(new WebViewClient() {
5538 // `shouldOverrideUrlLoading` makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
5539 // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
5541 public boolean shouldOverrideUrlLoading(WebView view, String url) {
5542 // Sanitize the url.
5543 url = sanitizeUrl(url);
5545 // Handle the URL according to the type.
5546 if (url.startsWith("http")) { // Load the URL in Privacy Browser.
5547 // Load the URL. By using `loadUrl()`, instead of `loadUrlFromBase()`, the Referer header will never be sent.
5548 loadUrl(nestedScrollWebView, url);
5550 // Returning true indicates that Privacy Browser is manually handling the loading of the URL.
5551 // Custom headers cannot be added if false is returned and the WebView handles the loading of the URL.
5553 } else if (url.startsWith("mailto:")) { // Load the email address in an external email program.
5554 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
5555 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
5557 // Parse the url and set it as the data for the intent.
5558 emailIntent.setData(Uri.parse(url));
5560 // Open the email program in a new task instead of as part of Privacy Browser.
5561 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5565 startActivity(emailIntent);
5566 } catch (ActivityNotFoundException exception) {
5567 // Display a snackbar.
5568 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
5572 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5574 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
5575 // Open the dialer and load the phone number, but wait for the user to place the call.
5576 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
5578 // Add the phone number to the intent.
5579 dialIntent.setData(Uri.parse(url));
5581 // Open the dialer in a new task instead of as part of Privacy Browser.
5582 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5586 startActivity(dialIntent);
5587 } catch (ActivityNotFoundException exception) {
5588 // Display a snackbar.
5589 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
5592 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5594 } else { // Load a system chooser to select an app that can handle the URL.
5595 // Open an app that can handle the URL.
5596 Intent genericIntent = new Intent(Intent.ACTION_VIEW);
5598 // Add the URL to the intent.
5599 genericIntent.setData(Uri.parse(url));
5601 // List all apps that can handle the URL instead of just opening the first one.
5602 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
5604 // Open the app in a new task instead of as part of Privacy Browser.
5605 genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5607 // Start the app or display a snackbar if no app is available to handle the URL.
5609 startActivity(genericIntent);
5610 } catch (ActivityNotFoundException exception) {
5611 Snackbar.make(nestedScrollWebView, getString(R.string.unrecognized_url) + " " + url, Snackbar.LENGTH_SHORT).show();
5614 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5619 // Check requests against the block lists. The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
5621 public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
5622 // Check to see if the resource request is for the main URL.
5623 if (url.equals(nestedScrollWebView.getCurrentUrl())) {
5624 // `return null` loads the resource request, which should never be blocked if it is the main URL.
5628 // 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.
5629 while (ultraPrivacy == null) {
5630 // The wait must be synchronized, which only lets one thread run on it at a time, or `java.lang.IllegalMonitorStateException` is thrown.
5631 synchronized (this) {
5633 // Check to see if the blocklists have been populated after 100 ms.
5635 } catch (InterruptedException exception) {
5641 // Sanitize the URL.
5642 url = sanitizeUrl(url);
5644 // Create an empty web resource response to be used if the resource request is blocked.
5645 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
5647 // Reset the whitelist results tracker.
5648 String[] whitelistResultStringArray = null;
5650 // Initialize the third party request tracker.
5651 boolean isThirdPartyRequest = false;
5653 // Get the current URL. `.getUrl()` throws an error because operations on the WebView cannot be made from this thread.
5654 String currentBaseDomain = nestedScrollWebView.getCurrentDomainName();
5656 // Store a copy of the current domain for use in later requests.
5657 String currentDomain = currentBaseDomain;
5659 // Nobody is happy when comparing null strings.
5661 // Convert the request URL to a URI.
5662 Uri requestUri = Uri.parse(url);
5664 // Get the request host name.
5665 String requestBaseDomain = requestUri.getHost();
5667 // Only check for third-party requests if the current base domain is not empty and the request domain is not null.
5668 if (!currentBaseDomain.isEmpty() && (requestBaseDomain != null)) {
5669 // Determine the current base domain.
5670 while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
5671 // Remove the first subdomain.
5672 currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
5675 // Determine the request base domain.
5676 while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
5677 // Remove the first subdomain.
5678 requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
5681 // Update the third party request tracker.
5682 isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
5686 // Get the current WebView page position.
5687 int webViewPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5689 // Determine if the WebView is currently displayed.
5690 boolean webViewDisplayed = (webViewPagePosition == tabLayout.getSelectedTabPosition());
5692 // Block third-party requests if enabled.
5693 if (isThirdPartyRequest && nestedScrollWebView.getBlockAllThirdPartyRequests()) {
5694 // Add the result to the resource requests.
5695 nestedScrollWebView.addResourceRequest(new String[]{BlocklistHelper.REQUEST_THIRD_PARTY, url});
5697 // Increment the blocked requests counters.
5698 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5699 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS);
5701 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5702 if (webViewDisplayed) {
5703 // Updating the UI must be run from the UI thread.
5704 activity.runOnUiThread(() -> {
5705 // Update the menu item titles.
5706 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5708 // Update the options menu if it has been populated.
5709 if (optionsMenu != null) {
5710 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5711 optionsBlockAllThirdPartyRequestsMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " +
5712 getString(R.string.block_all_third_party_requests));
5717 // Return an empty web resource response.
5718 return emptyWebResourceResponse;
5721 // Check UltraList if it is enabled.
5722 if (nestedScrollWebView.getUltraListEnabled()) {
5723 // Check the URL against UltraList.
5724 String[] ultraListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraList);
5726 // Process the UltraList results.
5727 if (ultraListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched UltraList's blacklist.
5728 // Add the result to the resource requests.
5729 nestedScrollWebView.addResourceRequest(new String[] {ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]});
5731 // Increment the blocked requests counters.
5732 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5733 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRALIST);
5735 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5736 if (webViewDisplayed) {
5737 // Updating the UI must be run from the UI thread.
5738 activity.runOnUiThread(() -> {
5739 // Update the menu item titles.
5740 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5742 // Update the options menu if it has been populated.
5743 if (optionsMenu != null) {
5744 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5745 optionsUltraListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRALIST) + " - " + getString(R.string.ultralist));
5750 // The resource request was blocked. Return an empty web resource response.
5751 return emptyWebResourceResponse;
5752 } else if (ultraListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched UltraList's whitelist.
5753 // Add a whitelist entry to the resource requests array.
5754 nestedScrollWebView.addResourceRequest(new String[] {ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]});
5756 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
5761 // Check UltraPrivacy if it is enabled.
5762 if (nestedScrollWebView.getUltraPrivacyEnabled()) {
5763 // Check the URL against UltraPrivacy.
5764 String[] ultraPrivacyResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraPrivacy);
5766 // Process the UltraPrivacy results.
5767 if (ultraPrivacyResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched UltraPrivacy's blacklist.
5768 // Add the result to the resource requests.
5769 nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5770 ultraPrivacyResults[5]});
5772 // Increment the blocked requests counters.
5773 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5774 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRAPRIVACY);
5776 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5777 if (webViewDisplayed) {
5778 // Updating the UI must be run from the UI thread.
5779 activity.runOnUiThread(() -> {
5780 // Update the menu item titles.
5781 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5783 // Update the options menu if it has been populated.
5784 if (optionsMenu != null) {
5785 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5786 optionsUltraPrivacyMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRAPRIVACY) + " - " + getString(R.string.ultraprivacy));
5791 // The resource request was blocked. Return an empty web resource response.
5792 return emptyWebResourceResponse;
5793 } else if (ultraPrivacyResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched UltraPrivacy's whitelist.
5794 // Add a whitelist entry to the resource requests array.
5795 nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5796 ultraPrivacyResults[5]});
5798 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
5803 // Check EasyList if it is enabled.
5804 if (nestedScrollWebView.getEasyListEnabled()) {
5805 // Check the URL against EasyList.
5806 String[] easyListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyList);
5808 // Process the EasyList results.
5809 if (easyListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched EasyList's blacklist.
5810 // Add the result to the resource requests.
5811 nestedScrollWebView.addResourceRequest(new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]});
5813 // Increment the blocked requests counters.
5814 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5815 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASYLIST);
5817 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5818 if (webViewDisplayed) {
5819 // Updating the UI must be run from the UI thread.
5820 activity.runOnUiThread(() -> {
5821 // Update the menu item titles.
5822 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5824 // Update the options menu if it has been populated.
5825 if (optionsMenu != null) {
5826 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5827 optionsEasyListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASYLIST) + " - " + getString(R.string.easylist));
5832 // The resource request was blocked. Return an empty web resource response.
5833 return emptyWebResourceResponse;
5834 } else if (easyListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched EasyList's whitelist.
5835 // Update the whitelist result string array tracker.
5836 whitelistResultStringArray = new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]};
5840 // Check EasyPrivacy if it is enabled.
5841 if (nestedScrollWebView.getEasyPrivacyEnabled()) {
5842 // Check the URL against EasyPrivacy.
5843 String[] easyPrivacyResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyPrivacy);
5845 // Process the EasyPrivacy results.
5846 if (easyPrivacyResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched EasyPrivacy's blacklist.
5847 // Add the result to the resource requests.
5848 nestedScrollWebView.addResourceRequest(new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4],
5849 easyPrivacyResults[5]});
5851 // Increment the blocked requests counters.
5852 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5853 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASYPRIVACY);
5855 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5856 if (webViewDisplayed) {
5857 // Updating the UI must be run from the UI thread.
5858 activity.runOnUiThread(() -> {
5859 // Update the menu item titles.
5860 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5862 // Update the options menu if it has been populated.
5863 if (optionsMenu != null) {
5864 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5865 optionsEasyPrivacyMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASYPRIVACY) + " - " + getString(R.string.easyprivacy));
5870 // The resource request was blocked. Return an empty web resource response.
5871 return emptyWebResourceResponse;
5872 } else if (easyPrivacyResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched EasyPrivacy's whitelist.
5873 // Update the whitelist result string array tracker.
5874 whitelistResultStringArray = new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5]};
5878 // Check Fanboy’s Annoyance List if it is enabled.
5879 if (nestedScrollWebView.getFanboysAnnoyanceListEnabled()) {
5880 // Check the URL against Fanboy's Annoyance List.
5881 String[] fanboysAnnoyanceListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList);
5883 // Process the Fanboy's Annoyance List results.
5884 if (fanboysAnnoyanceListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched Fanboy's Annoyance List's blacklist.
5885 // Add the result to the resource requests.
5886 nestedScrollWebView.addResourceRequest(new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5887 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]});
5889 // Increment the blocked requests counters.
5890 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5891 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST);
5893 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5894 if (webViewDisplayed) {
5895 // Updating the UI must be run from the UI thread.
5896 activity.runOnUiThread(() -> {
5897 // Update the menu item titles.
5898 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5900 // Update the options menu if it has been populated.
5901 if (optionsMenu != null) {
5902 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5903 optionsFanboysAnnoyanceListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " +
5904 getString(R.string.fanboys_annoyance_list));
5909 // The resource request was blocked. Return an empty web resource response.
5910 return emptyWebResourceResponse;
5911 } else if (fanboysAnnoyanceListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)){ // The resource request matched Fanboy's Annoyance List's whitelist.
5912 // Update the whitelist result string array tracker.
5913 whitelistResultStringArray = new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5914 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]};
5916 } else if (nestedScrollWebView.getFanboysSocialBlockingListEnabled()) { // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
5917 // Check the URL against Fanboy's Annoyance List.
5918 String[] fanboysSocialListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysSocialList);
5920 // Process the Fanboy's Social Blocking List results.
5921 if (fanboysSocialListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched Fanboy's Social Blocking List's blacklist.
5922 // Add the result to the resource requests.
5923 nestedScrollWebView.addResourceRequest(new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5924 fanboysSocialListResults[4], fanboysSocialListResults[5]});
5926 // Increment the blocked requests counters.
5927 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5928 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST);
5930 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5931 if (webViewDisplayed) {
5932 // Updating the UI must be run from the UI thread.
5933 activity.runOnUiThread(() -> {
5934 // Update the menu item titles.
5935 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5937 // Update the options menu if it has been populated.
5938 if (optionsMenu != null) {
5939 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5940 optionsFanboysSocialBlockingListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " +
5941 getString(R.string.fanboys_social_blocking_list));
5946 // The resource request was blocked. Return an empty web resource response.
5947 return emptyWebResourceResponse;
5948 } else if (fanboysSocialListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched Fanboy's Social Blocking List's whitelist.
5949 // Update the whitelist result string array tracker.
5950 whitelistResultStringArray = new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5951 fanboysSocialListResults[4], fanboysSocialListResults[5]};
5955 // Add the request to the log because it hasn't been processed by any of the previous checks.
5956 if (whitelistResultStringArray != null) { // The request was processed by a whitelist.
5957 nestedScrollWebView.addResourceRequest(whitelistResultStringArray);
5958 } else { // The request didn't match any blocklist entry. Log it as a default request.
5959 nestedScrollWebView.addResourceRequest(new String[]{BlocklistHelper.REQUEST_DEFAULT, url});
5962 // The resource request has not been blocked. `return null` loads the requested resource.
5966 // Handle HTTP authentication requests.
5968 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
5969 // Store the handler.
5970 nestedScrollWebView.setHttpAuthHandler(handler);
5972 // Instantiate an HTTP authentication dialog.
5973 DialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm, nestedScrollWebView.getWebViewFragmentId());
5975 // Show the HTTP authentication dialog.
5976 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
5980 public void onPageStarted(WebView view, String url, Bitmap favicon) {
5981 // Set the padding and layout settings if the app bar is at the top of the screen.
5982 if (!bottomAppBar) {
5983 // 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.
5984 if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) {
5985 // No padding is needed because it will automatically be placed below the app bar layout due to the scrolling layout behavior.
5986 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5988 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5989 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10, defaultProgressViewEndOffset);
5991 // Get the app bar layout height. This can't be done in `applyAppSettings()` because the app bar is not yet populated there.
5992 appBarHeight = appBarLayout.getHeight();
5994 // The swipe refresh layout must be manually moved below the app bar layout.
5995 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0);
5997 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5998 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight);
6002 // Reset the list of resource requests.
6003 nestedScrollWebView.clearResourceRequests();
6005 // Reset the requests counters.
6006 nestedScrollWebView.resetRequestsCounters();
6008 // Get the current page position.
6009 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
6011 // Update the URL text bar if the page is currently selected and the URL edit text is not currently being edited.
6012 if ((tabLayout.getSelectedTabPosition() == currentPagePosition) && !urlEditText.hasFocus()) {
6013 // Display the formatted URL text.
6014 urlEditText.setText(url);
6016 // Apply text highlighting to the URL text box.
6019 // Hide the keyboard.
6020 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
6023 // Reset the list of host IP addresses.
6024 nestedScrollWebView.setCurrentIpAddresses("");
6026 // Get a URI for the current URL.
6027 Uri currentUri = Uri.parse(url);
6029 // Get the IP addresses for the host.
6030 new GetHostIpAddresses(activity, getSupportFragmentManager(), nestedScrollWebView).execute(currentUri.getHost());
6032 // Replace Refresh with Stop if the options menu has been created. (The first WebView typically begins loading before the menu items are instantiated.)
6033 if (optionsMenu != null) {
6035 optionsRefreshMenuItem.setTitle(R.string.stop);
6037 // Get the app bar and theme preferences.
6038 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean(getString(R.string.display_additional_app_bar_icons_key), false);
6040 // If the icon is displayed in the AppBar, set it according to the theme.
6041 if (displayAdditionalAppBarIcons) {
6042 // Get the current theme status.
6043 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
6045 // Set the stop icon according to the theme.
6046 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
6047 optionsRefreshMenuItem.setIcon(R.drawable.close_blue_day);
6049 optionsRefreshMenuItem.setIcon(R.drawable.close_blue_night);
6056 public void onPageFinished(WebView view, String url) {
6057 // Flush any cookies to persistent storage. The cookie manager has become very lazy about flushing cookies in recent versions.
6058 if (nestedScrollWebView.getAcceptCookies() && Build.VERSION.SDK_INT >= 21) {
6059 CookieManager.getInstance().flush();
6062 // Update the Refresh menu item if the options menu has been created.
6063 if (optionsMenu != null) {
6064 // Reset the Refresh title.
6065 optionsRefreshMenuItem.setTitle(R.string.refresh);
6067 // Get the app bar and theme preferences.
6068 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean(getString(R.string.display_additional_app_bar_icons_key), false);
6070 // If the icon is displayed in the app bar, reset it according to the theme.
6071 if (displayAdditionalAppBarIcons) {
6072 // Get the current theme status.
6073 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
6075 // Set the icon according to the theme.
6076 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
6077 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled_day);
6079 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled_night);
6084 // Clear the cache, history, and logcat if Incognito Mode is enabled.
6085 if (incognitoModeEnabled) {
6086 // Clear the cache. `true` includes disk files.
6087 nestedScrollWebView.clearCache(true);
6089 // Clear the back/forward history.
6090 nestedScrollWebView.clearHistory();
6092 // Manually delete cache folders.
6094 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
6095 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
6096 String privateDataDirectoryString = getApplicationInfo().dataDir;
6098 // Delete the main cache directory.
6099 Runtime.getRuntime().exec("rm -rf " + privateDataDirectoryString + "/cache");
6101 // Delete the secondary `Service Worker` cache directory.
6102 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
6103 Runtime.getRuntime().exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
6104 } catch (IOException exception) {
6105 // Do nothing if an error is thrown.
6108 // Clear the logcat.
6110 // Clear the logcat. `-c` clears the logcat. `-b all` clears all the buffers (instead of just crash, main, and system).
6111 Runtime.getRuntime().exec("logcat -b all -c");
6112 } catch (IOException exception) {
6117 // Get the current page position.
6118 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
6120 // 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.
6121 String currentUrl = nestedScrollWebView.getUrl();
6123 // Get the current tab.
6124 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
6126 // Update the URL text bar if the page is currently selected and the user is not currently typing in the URL edit text.
6127 // Crash records show that, in some crazy way, it is possible for the current URL to be blank at this point.
6128 // Probably some sort of race condition when Privacy Browser is being resumed.
6129 if ((tabLayout.getSelectedTabPosition() == currentPagePosition) && !urlEditText.hasFocus() && (currentUrl != null)) {
6130 // Check to see if the URL is `about:blank`.
6131 if (currentUrl.equals("about:blank")) { // The WebView is blank.
6132 // Display the hint in the URL edit text.
6133 urlEditText.setText("");
6135 // Request focus for the URL text box.
6136 urlEditText.requestFocus();
6138 // Display the keyboard.
6139 inputMethodManager.showSoftInput(urlEditText, 0);
6141 // Apply the domain settings. This clears any settings from the previous domain.
6142 applyDomainSettings(nestedScrollWebView, "", true, false, false);
6144 // Only populate the title text view if the tab has been fully created.
6146 // Get the custom view from the tab.
6147 View tabView = tab.getCustomView();
6149 // Remove the incorrect warning below that the current tab view might be null.
6150 assert tabView != null;
6152 // Get the title text view from the tab.
6153 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
6155 // Set the title as the tab text.
6156 tabTitleTextView.setText(R.string.new_tab);
6158 } else { // The WebView has loaded a webpage.
6159 // Update the URL edit text if it is not currently being edited.
6160 if (!urlEditText.hasFocus()) {
6161 // 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.
6162 String sanitizedUrl = sanitizeUrl(currentUrl);
6164 // Display the final URL. Getting the URL from the WebView instead of using the one provided by `onPageFinished()` makes websites like YouTube function correctly.
6165 urlEditText.setText(sanitizedUrl);
6167 // Apply text highlighting to the URL.
6171 // Only populate the title text view if the tab has been fully created.
6173 // Get the custom view from the tab.
6174 View tabView = tab.getCustomView();
6176 // Remove the incorrect warning below that the current tab view might be null.
6177 assert tabView != null;
6179 // Get the title text view from the tab.
6180 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
6182 // Set the title as the tab text. Sometimes `onReceivedTitle()` is not called, especially when navigating history.
6183 tabTitleTextView.setText(nestedScrollWebView.getTitle());
6189 // Handle SSL Certificate errors.
6191 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
6192 // Get the current website SSL certificate.
6193 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
6195 // Extract the individual pieces of information from the current website SSL certificate.
6196 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
6197 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
6198 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
6199 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
6200 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
6201 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
6202 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
6203 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
6205 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
6206 if (nestedScrollWebView.hasPinnedSslCertificate()) {
6207 // Get the pinned SSL certificate.
6208 ArrayList<Object> pinnedSslCertificateArrayList = nestedScrollWebView.getPinnedSslCertificate();
6210 // Extract the arrays from the array list.
6211 String[] pinnedSslCertificateStringArray = (String[]) pinnedSslCertificateArrayList.get(0);
6212 Date[] pinnedSslCertificateDateArray = (Date[]) pinnedSslCertificateArrayList.get(1);
6214 // Check if the current SSL certificate matches the pinned certificate.
6215 if (currentWebsiteIssuedToCName.equals(pinnedSslCertificateStringArray[0]) && currentWebsiteIssuedToOName.equals(pinnedSslCertificateStringArray[1]) &&
6216 currentWebsiteIssuedToUName.equals(pinnedSslCertificateStringArray[2]) && currentWebsiteIssuedByCName.equals(pinnedSslCertificateStringArray[3]) &&
6217 currentWebsiteIssuedByOName.equals(pinnedSslCertificateStringArray[4]) && currentWebsiteIssuedByUName.equals(pinnedSslCertificateStringArray[5]) &&
6218 currentWebsiteSslStartDate.equals(pinnedSslCertificateDateArray[0]) && currentWebsiteSslEndDate.equals(pinnedSslCertificateDateArray[1])) {
6220 // An SSL certificate is pinned and matches the current domain certificate. Proceed to the website without displaying an error.
6223 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
6224 // Store the SSL error handler.
6225 nestedScrollWebView.setSslErrorHandler(handler);
6227 // Instantiate an SSL certificate error alert dialog.
6228 DialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error, nestedScrollWebView.getWebViewFragmentId());
6230 // 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.
6232 // Show the SSL certificate error dialog.
6233 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
6234 } catch (Exception exception) {
6235 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
6236 pendingDialogsArrayList.add(new PendingDialog(sslCertificateErrorDialogFragment, getString(R.string.ssl_certificate_error)));
6242 // Check to see if the state is being restored.
6243 if (restoringState) { // The state is being restored.
6244 // Resume the nested scroll WebView JavaScript timers.
6245 nestedScrollWebView.resumeTimers();
6246 } else if (pageNumber == 0) { // The first page is being loaded.
6247 // Set this nested scroll WebView as the current WebView.
6248 currentWebView = nestedScrollWebView;
6250 // Initialize the URL to load string.
6251 String urlToLoadString;
6253 // Get the intent that started the app.
6254 Intent launchingIntent = getIntent();
6256 // Reset the intent. This prevents a duplicate tab from being created on restart.
6257 setIntent(new Intent());
6259 // Get the information from the intent.
6260 String launchingIntentAction = launchingIntent.getAction();
6261 Uri launchingIntentUriData = launchingIntent.getData();
6262 String launchingIntentStringExtra = launchingIntent.getStringExtra(Intent.EXTRA_TEXT);
6264 // Parse the launching intent URL.
6265 if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) { // The intent contains a search string.
6266 // Create an encoded URL string.
6267 String encodedUrlString;
6269 // Sanitize the search input and convert it to a search.
6271 encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
6272 } catch (UnsupportedEncodingException exception) {
6273 encodedUrlString = "";
6276 // Store the web search as the URL to load.
6277 urlToLoadString = searchURL + encodedUrlString;
6278 } else if (launchingIntentUriData != null) { // The launching intent contains a URL formatted as a URI.
6279 // Store the URI as a URL.
6280 urlToLoadString = launchingIntentUriData.toString();
6281 } else if (launchingIntentStringExtra != null) { // The launching intent contains text that might be a URL.
6283 urlToLoadString = launchingIntentStringExtra;
6284 } else if (!url.equals("")) { // The activity has been restarted.
6285 // Load the saved URL.
6286 urlToLoadString = url;
6287 } else { // The is no URL in the intent.
6288 // Store the homepage to be loaded.
6289 urlToLoadString = sharedPreferences.getString("homepage", getString(R.string.homepage_default_value));
6292 // Load the website if not waiting for the proxy.
6293 if (waitingForProxy) { // Store the URL to be loaded in the Nested Scroll WebView.
6294 nestedScrollWebView.setWaitingForProxyUrlString(urlToLoadString);
6295 } else { // Load the URL.
6296 loadUrl(nestedScrollWebView, urlToLoadString);
6299 // 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.
6300 // 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.
6301 setIntent(new Intent());
6302 } else { // This is not the first tab.
6304 loadUrl(nestedScrollWebView, url);
6306 // Set the focus and display the keyboard if the URL is blank.
6307 if (url.equals("")) {
6308 // Request focus for the URL text box.
6309 urlEditText.requestFocus();
6311 // Create a display keyboard handler.
6312 Handler displayKeyboardHandler = new Handler();
6314 // Create a display keyboard runnable.
6315 Runnable displayKeyboardRunnable = () -> {
6316 // Display the keyboard.
6317 inputMethodManager.showSoftInput(urlEditText, 0);
6320 // Display the keyboard after 100 milliseconds, which leaves enough time for the tab to transition.
6321 displayKeyboardHandler.postDelayed(displayKeyboardRunnable, 100);