2 * Copyright © 2015-2022 Soren Stoutner <soren@stoutner.com>.
4 * Download cookie code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
6 * This file is part of Privacy Browser Android <https://www.stoutner.com/privacy-browser-android>.
8 * Privacy Browser Android is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
13 * Privacy Browser Android is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with Privacy Browser Android. If not, see <http://www.gnu.org/licenses/>.
22 package com.stoutner.privacybrowser.activities;
24 import android.animation.ObjectAnimator;
25 import android.annotation.SuppressLint;
26 import android.app.Activity;
27 import android.app.Dialog;
28 import android.app.DownloadManager;
29 import android.app.SearchManager;
30 import android.content.ActivityNotFoundException;
31 import android.content.BroadcastReceiver;
32 import android.content.ClipData;
33 import android.content.ClipboardManager;
34 import android.content.Context;
35 import android.content.Intent;
36 import android.content.IntentFilter;
37 import android.content.SharedPreferences;
38 import android.content.pm.PackageManager;
39 import android.content.res.Configuration;
40 import android.database.Cursor;
41 import android.graphics.Bitmap;
42 import android.graphics.BitmapFactory;
43 import android.graphics.Typeface;
44 import android.graphics.drawable.BitmapDrawable;
45 import android.graphics.drawable.Drawable;
46 import android.net.Uri;
47 import android.net.http.SslCertificate;
48 import android.net.http.SslError;
49 import android.os.AsyncTask;
50 import android.os.Build;
51 import android.os.Bundle;
52 import android.os.Environment;
53 import android.os.Handler;
54 import android.os.Message;
55 import android.preference.PreferenceManager;
56 import android.print.PrintDocumentAdapter;
57 import android.print.PrintManager;
58 import android.provider.DocumentsContract;
59 import android.provider.OpenableColumns;
60 import android.text.Editable;
61 import android.text.Spanned;
62 import android.text.TextWatcher;
63 import android.text.style.ForegroundColorSpan;
64 import android.util.Patterns;
65 import android.util.TypedValue;
66 import android.view.ContextMenu;
67 import android.view.GestureDetector;
68 import android.view.KeyEvent;
69 import android.view.Menu;
70 import android.view.MenuItem;
71 import android.view.MotionEvent;
72 import android.view.View;
73 import android.view.ViewGroup;
74 import android.view.WindowManager;
75 import android.view.inputmethod.InputMethodManager;
76 import android.webkit.CookieManager;
77 import android.webkit.HttpAuthHandler;
78 import android.webkit.SslErrorHandler;
79 import android.webkit.ValueCallback;
80 import android.webkit.WebBackForwardList;
81 import android.webkit.WebChromeClient;
82 import android.webkit.WebResourceRequest;
83 import android.webkit.WebResourceResponse;
84 import android.webkit.WebSettings;
85 import android.webkit.WebStorage;
86 import android.webkit.WebView;
87 import android.webkit.WebViewClient;
88 import android.webkit.WebViewDatabase;
89 import android.widget.ArrayAdapter;
90 import android.widget.CheckBox;
91 import android.widget.CursorAdapter;
92 import android.widget.EditText;
93 import android.widget.FrameLayout;
94 import android.widget.ImageView;
95 import android.widget.LinearLayout;
96 import android.widget.ListView;
97 import android.widget.ProgressBar;
98 import android.widget.RadioButton;
99 import android.widget.RelativeLayout;
100 import android.widget.TextView;
102 import androidx.activity.result.ActivityResultCallback;
103 import androidx.activity.result.ActivityResultLauncher;
104 import androidx.activity.result.contract.ActivityResultContracts;
105 import androidx.annotation.NonNull;
106 import androidx.appcompat.app.ActionBar;
107 import androidx.appcompat.app.ActionBarDrawerToggle;
108 import androidx.appcompat.app.AppCompatActivity;
109 import androidx.appcompat.app.AppCompatDelegate;
110 import androidx.appcompat.widget.Toolbar;
111 import androidx.coordinatorlayout.widget.CoordinatorLayout;
112 import androidx.core.content.res.ResourcesCompat;
113 import androidx.core.view.GravityCompat;
114 import androidx.drawerlayout.widget.DrawerLayout;
115 import androidx.fragment.app.DialogFragment;
116 import androidx.fragment.app.Fragment;
117 import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
118 import androidx.viewpager.widget.ViewPager;
119 import androidx.webkit.WebSettingsCompat;
120 import androidx.webkit.WebViewFeature;
123 import com.google.android.material.appbar.AppBarLayout;
124 import com.google.android.material.floatingactionbutton.FloatingActionButton;
125 import com.google.android.material.navigation.NavigationView;
126 import com.google.android.material.snackbar.Snackbar;
127 import com.google.android.material.tabs.TabLayout;
129 import com.stoutner.privacybrowser.R;
130 import com.stoutner.privacybrowser.adapters.WebViewPagerAdapter;
131 import com.stoutner.privacybrowser.asynctasks.GetHostIpAddresses;
132 import com.stoutner.privacybrowser.asynctasks.PopulateBlocklists;
133 import com.stoutner.privacybrowser.asynctasks.PrepareSaveDialog;
134 import com.stoutner.privacybrowser.asynctasks.SaveUrl;
135 import com.stoutner.privacybrowser.asynctasks.SaveWebpageImage;
136 import com.stoutner.privacybrowser.dataclasses.PendingDialog;
137 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
138 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
139 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
140 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
141 import com.stoutner.privacybrowser.dialogs.FontSizeDialog;
142 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
143 import com.stoutner.privacybrowser.dialogs.OpenDialog;
144 import com.stoutner.privacybrowser.dialogs.ProxyNotInstalledDialog;
145 import com.stoutner.privacybrowser.dialogs.PinnedMismatchDialog;
146 import com.stoutner.privacybrowser.dialogs.SaveDialog;
147 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
148 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
149 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
150 import com.stoutner.privacybrowser.dialogs.WaitingForProxyDialog;
151 import com.stoutner.privacybrowser.fragments.WebViewTabFragment;
152 import com.stoutner.privacybrowser.helpers.BlocklistHelper;
153 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
154 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
155 import com.stoutner.privacybrowser.helpers.ProxyHelper;
156 import com.stoutner.privacybrowser.views.NestedScrollWebView;
158 import java.io.ByteArrayInputStream;
159 import java.io.ByteArrayOutputStream;
161 import java.io.FileInputStream;
162 import java.io.FileOutputStream;
163 import java.io.IOException;
164 import java.io.InputStream;
165 import java.io.OutputStream;
166 import java.io.UnsupportedEncodingException;
168 import java.net.MalformedURLException;
170 import java.net.URLDecoder;
171 import java.net.URLEncoder;
173 import java.text.NumberFormat;
175 import java.util.ArrayList;
176 import java.util.Date;
177 import java.util.HashMap;
178 import java.util.HashSet;
179 import java.util.List;
180 import java.util.Map;
181 import java.util.Objects;
182 import java.util.Set;
183 import java.util.concurrent.ExecutorService;
184 import java.util.concurrent.Executors;
186 public class MainWebViewActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener,
187 EditBookmarkFolderDialog.EditBookmarkFolderListener, FontSizeDialog.UpdateFontSizeListener, NavigationView.OnNavigationItemSelectedListener, OpenDialog.OpenListener,
188 PinnedMismatchDialog.PinnedMismatchListener, PopulateBlocklists.PopulateBlocklistsListener, SaveDialog.SaveListener, UrlHistoryDialog.NavigateHistoryListener,
189 WebViewTabFragment.NewTabListener {
191 // Define the public static variables.
192 public static ExecutorService executorService = Executors.newFixedThreadPool(4);
193 public static String orbotStatus = "unknown";
194 public static ArrayList<PendingDialog> pendingDialogsArrayList = new ArrayList<>();
195 public static String proxyMode = ProxyHelper.NONE;
197 // Declare the public static variables.
198 public static String currentBookmarksFolder;
199 public static boolean restartFromBookmarksActivity;
200 public static WebViewPagerAdapter webViewPagerAdapter;
202 // Declare the public static views.
203 public static AppBarLayout appBarLayout;
205 // The user agent constants are public static so they can be accessed from `SettingsFragment`, `DomainsActivity`, and `DomainSettingsFragment`.
206 public final static int UNRECOGNIZED_USER_AGENT = -1;
207 public final static int SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1;
208 public final static int SETTINGS_CUSTOM_USER_AGENT = 11;
209 public final static int DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0;
210 public final static int DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2;
211 public final static int DOMAINS_CUSTOM_USER_AGENT = 12;
213 // Define the start activity for result request codes. The public static entry is accessed from `OpenDialog()`.
214 private final int BROWSE_FILE_UPLOAD_REQUEST_CODE = 0;
215 public final static int BROWSE_OPEN_REQUEST_CODE = 1;
217 // Define the saved instance state constants.
218 private final String SAVED_STATE_ARRAY_LIST = "saved_state_array_list";
219 private final String SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST = "saved_nested_scroll_webview_state_array_list";
220 private final String SAVED_TAB_POSITION = "saved_tab_position";
221 private final String PROXY_MODE = "proxy_mode";
223 // Define the saved instance state variables.
224 private ArrayList<Bundle> savedStateArrayList;
225 private ArrayList<Bundle> savedNestedScrollWebViewStateArrayList;
226 private int savedTabPosition;
227 private String savedProxyMode;
229 // Define the class variables.
230 @SuppressWarnings("rawtypes")
231 AsyncTask populateBlocklists;
233 // The current WebView is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
234 // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, `applyProxy()`, and `applyDomainSettings()`.
235 private NestedScrollWebView currentWebView;
237 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
238 private final Map<String, String> customHeaders = new HashMap<>();
240 // The search URL is set in `applyAppSettings()` and used in `onNewIntent()`, `loadUrlFromTextBox()`, `initializeApp()`, and `initializeWebView()`.
241 private String searchURL;
243 // The blocklists are populated in `finishedPopulatingBlocklists()` and accessed from `initializeWebView()`.
244 private ArrayList<List<String[]>> easyList;
245 private ArrayList<List<String[]>> easyPrivacy;
246 private ArrayList<List<String[]>> fanboysAnnoyanceList;
247 private ArrayList<List<String[]>> fanboysSocialList;
248 private ArrayList<List<String[]>> ultraList;
249 private ArrayList<List<String[]>> ultraPrivacy;
251 // The action bar drawer toggle is initialized in `onCreate()` and used in `onResume()`.
252 private ActionBarDrawerToggle actionBarDrawerToggle;
254 // The color spans are used in `onCreate()` and `highlightUrlText()`.
255 private ForegroundColorSpan redColorSpan;
256 private ForegroundColorSpan initialGrayColorSpan;
257 private ForegroundColorSpan finalGrayColorSpan;
259 // `bookmarksCursor` is used in `onDestroy()`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
260 private Cursor bookmarksCursor;
262 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
263 private CursorAdapter bookmarksCursorAdapter;
265 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
266 private String oldFolderNameString;
268 // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
269 private ValueCallback<Uri[]> fileChooserCallback;
271 // The default progress view offsets are set in `onCreate()` and used in `initializeWebView()`.
272 private int appBarHeight;
273 private int defaultProgressViewStartOffset;
274 private int defaultProgressViewEndOffset;
276 // The URL sanitizers are set in `applyAppSettings()` and used in `sanitizeUrl()`.
277 private boolean sanitizeGoogleAnalytics;
278 private boolean sanitizeFacebookClickIds;
279 private boolean sanitizeTwitterAmpRedirects;
281 // Declare the class variables
282 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
283 private boolean bottomAppBar;
284 private boolean displayingFullScreenVideo;
285 private boolean downloadWithExternalApp;
286 private boolean fullScreenBrowsingModeEnabled;
287 private boolean hideAppBar;
288 private boolean incognitoModeEnabled;
289 private boolean inFullScreenBrowsingMode;
290 private boolean loadingNewIntent;
291 private BroadcastReceiver orbotStatusBroadcastReceiver;
292 private ProxyHelper proxyHelper;
293 private boolean reapplyAppSettingsOnRestart;
294 private boolean reapplyDomainSettingsOnRestart;
295 private boolean scrollAppBar;
296 private boolean waitingForProxy;
297 private String webViewDefaultUserAgent;
299 // Define the class variables.
300 private ObjectAnimator objectAnimator = new ObjectAnimator();
301 private String saveUrlString = "";
303 // Declare the class views.
304 private FrameLayout rootFrameLayout;
305 private DrawerLayout drawerLayout;
306 private CoordinatorLayout coordinatorLayout;
307 private Toolbar toolbar;
308 private RelativeLayout urlRelativeLayout;
309 private EditText urlEditText;
310 private ActionBar actionBar;
311 private LinearLayout findOnPageLinearLayout;
312 private LinearLayout tabsLinearLayout;
313 private TabLayout tabLayout;
314 private SwipeRefreshLayout swipeRefreshLayout;
315 private ViewPager webViewPager;
316 private FrameLayout fullScreenVideoFrameLayout;
318 // Declare the class menus.
319 private Menu optionsMenu;
321 // Declare the class menu items.
322 private MenuItem navigationBackMenuItem;
323 private MenuItem navigationForwardMenuItem;
324 private MenuItem navigationHistoryMenuItem;
325 private MenuItem navigationRequestsMenuItem;
326 private MenuItem optionsPrivacyMenuItem;
327 private MenuItem optionsRefreshMenuItem;
328 private MenuItem optionsCookiesMenuItem;
329 private MenuItem optionsDomStorageMenuItem;
330 private MenuItem optionsSaveFormDataMenuItem;
331 private MenuItem optionsClearDataMenuItem;
332 private MenuItem optionsClearCookiesMenuItem;
333 private MenuItem optionsClearDomStorageMenuItem;
334 private MenuItem optionsClearFormDataMenuItem;
335 private MenuItem optionsBlocklistsMenuItem;
336 private MenuItem optionsEasyListMenuItem;
337 private MenuItem optionsEasyPrivacyMenuItem;
338 private MenuItem optionsFanboysAnnoyanceListMenuItem;
339 private MenuItem optionsFanboysSocialBlockingListMenuItem;
340 private MenuItem optionsUltraListMenuItem;
341 private MenuItem optionsUltraPrivacyMenuItem;
342 private MenuItem optionsBlockAllThirdPartyRequestsMenuItem;
343 private MenuItem optionsProxyMenuItem;
344 private MenuItem optionsProxyNoneMenuItem;
345 private MenuItem optionsProxyTorMenuItem;
346 private MenuItem optionsProxyI2pMenuItem;
347 private MenuItem optionsProxyCustomMenuItem;
348 private MenuItem optionsUserAgentMenuItem;
349 private MenuItem optionsUserAgentPrivacyBrowserMenuItem;
350 private MenuItem optionsUserAgentWebViewDefaultMenuItem;
351 private MenuItem optionsUserAgentFirefoxOnAndroidMenuItem;
352 private MenuItem optionsUserAgentChromeOnAndroidMenuItem;
353 private MenuItem optionsUserAgentSafariOnIosMenuItem;
354 private MenuItem optionsUserAgentFirefoxOnLinuxMenuItem;
355 private MenuItem optionsUserAgentChromiumOnLinuxMenuItem;
356 private MenuItem optionsUserAgentFirefoxOnWindowsMenuItem;
357 private MenuItem optionsUserAgentChromeOnWindowsMenuItem;
358 private MenuItem optionsUserAgentEdgeOnWindowsMenuItem;
359 private MenuItem optionsUserAgentInternetExplorerOnWindowsMenuItem;
360 private MenuItem optionsUserAgentSafariOnMacosMenuItem;
361 private MenuItem optionsUserAgentCustomMenuItem;
362 private MenuItem optionsSwipeToRefreshMenuItem;
363 private MenuItem optionsWideViewportMenuItem;
364 private MenuItem optionsDisplayImagesMenuItem;
365 private MenuItem optionsDarkWebViewMenuItem;
366 private MenuItem optionsFontSizeMenuItem;
367 private MenuItem optionsAddOrEditDomainMenuItem;
369 // This variable won't be needed once the class is migrated to Kotlin, as can be seen in LogcatActivity or AboutVersionFragment.
370 private Activity resultLauncherActivityHandle;
372 // Define the save URL activity result launcher. It must be defined before `onCreate()` is run or the app will crash.
373 private final ActivityResultLauncher<String> saveUrlActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.CreateDocument(),
374 new ActivityResultCallback<Uri>() {
376 public void onActivityResult(Uri fileUri) {
377 // Only save the URL if the file URI is not null, which happens if the user exited the file picker by pressing back.
378 if (fileUri != null) {
379 new SaveUrl(getApplicationContext(), resultLauncherActivityHandle, fileUri, currentWebView.getSettings().getUserAgentString(), currentWebView.getAcceptCookies()).execute(saveUrlString);
382 // Reset the save URL string.
387 // Define the save webpage archive activity result launcher. It must be defined before `onCreate()` is run or the app will crash.
388 private final ActivityResultLauncher<String> saveWebpageArchiveActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.CreateDocument(),
389 new ActivityResultCallback<Uri>() {
391 public void onActivityResult(Uri fileUri) {
392 // Only save the webpage archive if the file URI is not null, which happens if the user exited the file picker by pressing back.
393 if (fileUri != null) {
395 // Create a temporary MHT file.
396 File temporaryMhtFile = File.createTempFile("temporary_mht_file", ".mht", getCacheDir());
398 // Save the temporary MHT file.
399 currentWebView.saveWebArchive(temporaryMhtFile.toString(), false, callbackValue -> {
400 if (callbackValue != null) { // The temporary MHT file was saved successfully.
402 // Create a temporary MHT file input stream.
403 FileInputStream temporaryMhtFileInputStream = new FileInputStream(temporaryMhtFile);
405 // Get an output stream for the save webpage file path.
406 OutputStream mhtOutputStream = getContentResolver().openOutputStream(fileUri);
408 // Create a transfer byte array.
409 byte[] transferByteArray = new byte[1024];
411 // Create an integer to track the number of bytes read.
414 // Copy the temporary MHT file input stream to the MHT output stream.
415 while ((bytesRead = temporaryMhtFileInputStream.read(transferByteArray)) > 0) {
416 mhtOutputStream.write(transferByteArray, 0, bytesRead);
419 // Close the streams.
420 mhtOutputStream.close();
421 temporaryMhtFileInputStream.close();
423 // Initialize the file name string from the file URI last path segment.
424 String fileNameString = fileUri.getLastPathSegment();
426 // Query the exact file name if the API >= 26.
427 if (Build.VERSION.SDK_INT >= 26) {
428 // Get a cursor from the content resolver.
429 Cursor contentResolverCursor = resultLauncherActivityHandle.getContentResolver().query(fileUri, null, null, null);
431 // Move to the fist row.
432 contentResolverCursor.moveToFirst();
434 // Get the file name from the cursor.
435 fileNameString = contentResolverCursor.getString(contentResolverCursor.getColumnIndexOrThrow(OpenableColumns.DISPLAY_NAME));
438 contentResolverCursor.close();
441 // Display a snackbar.
442 Snackbar.make(currentWebView, getString(R.string.file_saved) + " " + fileNameString, Snackbar.LENGTH_SHORT).show();
443 } catch (Exception exception) {
444 // Display a snackbar with the exception.
445 Snackbar.make(currentWebView, getString(R.string.error_saving_file) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
447 // Delete the temporary MHT file.
448 //noinspection ResultOfMethodCallIgnored
449 temporaryMhtFile.delete();
451 } else { // There was an unspecified error while saving the temporary MHT file.
452 // Display an error snackbar.
453 Snackbar.make(currentWebView, getString(R.string.error_saving_file), Snackbar.LENGTH_INDEFINITE).show();
456 } catch (IOException ioException) {
457 // Display a snackbar with the IO exception.
458 Snackbar.make(currentWebView, getString(R.string.error_saving_file) + " " + ioException, Snackbar.LENGTH_INDEFINITE).show();
464 // Define the save webpage image activity result launcher. It must be defined before `onCreate()` is run or the app will crash.
465 private final ActivityResultLauncher<String> saveWebpageImageActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.CreateDocument(),
466 new ActivityResultCallback<Uri>() {
468 public void onActivityResult(Uri fileUri) {
469 // Only save the webpage image if the file URI is not null, which happens if the user exited the file picker by pressing back.
470 if (fileUri != null) {
471 // Save the webpage image.
472 new SaveWebpageImage(resultLauncherActivityHandle, fileUri, currentWebView).execute();
477 // Remove the warning about needing to override `performClick()` when using an `OnTouchListener` with WebView.
478 @SuppressLint("ClickableViewAccessibility")
480 protected void onCreate(Bundle savedInstanceState) {
481 // Run the default commands.
482 super.onCreate(savedInstanceState);
484 // Populate the result launcher activity. This will no longer be needed once the activity has transitioned to Kotlin.
485 resultLauncherActivityHandle = this;
487 // Check to see if the activity has been restarted.
488 if (savedInstanceState != null) {
489 // Store the saved instance state variables.
490 savedStateArrayList = savedInstanceState.getParcelableArrayList(SAVED_STATE_ARRAY_LIST);
491 savedNestedScrollWebViewStateArrayList = savedInstanceState.getParcelableArrayList(SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST);
492 savedTabPosition = savedInstanceState.getInt(SAVED_TAB_POSITION);
493 savedProxyMode = savedInstanceState.getString(PROXY_MODE);
496 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
497 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
499 // Get a handle for the shared preferences.
500 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
502 // Get the preferences.
503 String appTheme = sharedPreferences.getString("app_theme", getString(R.string.app_theme_default_value));
504 boolean allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false);
505 bottomAppBar = sharedPreferences.getBoolean(getString(R.string.bottom_app_bar_key), false);
507 // Get the theme entry values string array.
508 String[] appThemeEntryValuesStringArray = getResources().getStringArray(R.array.app_theme_entry_values);
510 // 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.
511 if (appTheme.equals(appThemeEntryValuesStringArray[1])) { // The light theme is selected.
512 // Apply the light theme.
513 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
514 } else if (appTheme.equals(appThemeEntryValuesStringArray[2])) { // The dark theme is selected.
515 // Apply the dark theme.
516 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
517 } else { // The system default theme is selected.
518 if (Build.VERSION.SDK_INT >= 28) { // The system default theme is supported.
519 // Follow the system default theme.
520 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
521 } else { // The system default theme is not supported.
522 // Follow the battery saver mode.
523 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY);
527 // Disable screenshots if not allowed.
528 if (!allowScreenshots) {
529 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
532 // 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.
533 WebView.enableSlowWholeDocumentDraw();
536 setTheme(R.style.PrivacyBrowser);
538 // Set the content view according to the position of the app bar.
539 if (bottomAppBar) setContentView(R.layout.main_framelayout_bottom_appbar);
540 else setContentView(R.layout.main_framelayout_top_appbar);
542 // Get handles for the views.
543 rootFrameLayout = findViewById(R.id.root_framelayout);
544 drawerLayout = findViewById(R.id.drawerlayout);
545 coordinatorLayout = findViewById(R.id.coordinatorlayout);
546 appBarLayout = findViewById(R.id.appbar_layout);
547 toolbar = findViewById(R.id.toolbar);
548 findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
549 tabsLinearLayout = findViewById(R.id.tabs_linearlayout);
550 tabLayout = findViewById(R.id.tablayout);
551 swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
552 webViewPager = findViewById(R.id.webviewpager);
553 NavigationView navigationView = findViewById(R.id.navigationview);
554 fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
556 // Get a handle for the navigation menu.
557 Menu navigationMenu = navigationView.getMenu();
559 // Get handles for the navigation menu items.
560 navigationBackMenuItem = navigationMenu.findItem(R.id.back);
561 navigationForwardMenuItem = navigationMenu.findItem(R.id.forward);
562 navigationHistoryMenuItem = navigationMenu.findItem(R.id.history);
563 navigationRequestsMenuItem = navigationMenu.findItem(R.id.requests);
565 // Listen for touches on the navigation menu.
566 navigationView.setNavigationItemSelectedListener(this);
568 // Get a handle for the app compat delegate.
569 AppCompatDelegate appCompatDelegate = getDelegate();
571 // Set the support action bar.
572 appCompatDelegate.setSupportActionBar(toolbar);
574 // Get a handle for the action bar.
575 actionBar = appCompatDelegate.getSupportActionBar();
577 // Remove the incorrect lint warning below that the action bar might be null.
578 assert actionBar != null;
580 // Add the custom layout, which shows the URL text bar.
581 actionBar.setCustomView(R.layout.url_app_bar);
582 actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
584 // Get handles for the views in the URL app bar.
585 urlRelativeLayout = findViewById(R.id.url_relativelayout);
586 urlEditText = findViewById(R.id.url_edittext);
588 // Create the hamburger icon at the start of the AppBar.
589 actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
591 // Initially disable the sliding drawers. They will be enabled once the blocklists are loaded.
592 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
594 // Initialize the web view pager adapter.
595 webViewPagerAdapter = new WebViewPagerAdapter(getSupportFragmentManager());
597 // Set the pager adapter on the web view pager.
598 webViewPager.setAdapter(webViewPagerAdapter);
600 // Store up to 100 tabs in memory.
601 webViewPager.setOffscreenPageLimit(100);
603 // Instantiate the proxy helper.
604 proxyHelper = new ProxyHelper();
606 // Initialize the app.
609 // Apply the app settings from the shared preferences.
612 // Populate the blocklists.
613 populateBlocklists = new PopulateBlocklists(this, this).execute();
617 protected void onNewIntent(Intent intent) {
618 // Run the default commands.
619 super.onNewIntent(intent);
621 // Replace the intent that started the app with this one.
624 // Check to see if the app is being restarted from a saved state.
625 if (savedStateArrayList == null || savedStateArrayList.size() == 0) { // The activity is not being restarted from a saved state.
626 // Get the information from the intent.
627 String intentAction = intent.getAction();
628 Uri intentUriData = intent.getData();
629 String intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT);
631 // Determine if this is a web search.
632 boolean isWebSearch = ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH));
634 // 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.
635 if (intentUriData != null || intentStringExtra != null || isWebSearch) {
636 // Exit the full screen video if it is displayed.
637 if (displayingFullScreenVideo) {
638 // Exit full screen video mode.
639 exitFullScreenVideo();
641 // Reload the current WebView. Otherwise, it can display entirely black.
642 currentWebView.reload();
645 // Get the shared preferences.
646 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
648 // Create a URL string.
651 // If the intent action is a web search, perform the search.
652 if (isWebSearch) { // The intent is a web search.
653 // Create an encoded URL string.
654 String encodedUrlString;
656 // Sanitize the search input and convert it to a search.
658 encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
659 } catch (UnsupportedEncodingException exception) {
660 encodedUrlString = "";
663 // Add the base search URL.
664 url = searchURL + encodedUrlString;
665 } else if (intentUriData != null) { // The intent contains a URL formatted as a URI.
666 // Set the intent data as the URL.
667 url = intentUriData.toString();
668 } else { // The intent contains a string, which might be a URL.
669 // Set the intent string as the URL.
670 url = intentStringExtra;
673 // Add a new tab if specified in the preferences.
674 if (sharedPreferences.getBoolean("open_intents_in_new_tab", true)) { // Load the URL in a new tab.
675 // Set the loading new intent flag.
676 loadingNewIntent = true;
679 addNewTab(url, true);
680 } else { // Load the URL in the current tab.
682 loadUrl(currentWebView, url);
685 // Close the navigation drawer if it is open.
686 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
687 drawerLayout.closeDrawer(GravityCompat.START);
690 // Close the bookmarks drawer if it is open.
691 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
692 drawerLayout.closeDrawer(GravityCompat.END);
699 public void onRestart() {
700 // Run the default commands.
703 // Apply the app settings if returning from the Settings activity.
704 if (reapplyAppSettingsOnRestart) {
705 // Reset the reapply app settings on restart tracker.
706 reapplyAppSettingsOnRestart = false;
708 // Apply the app settings.
712 // Apply the domain settings if returning from the settings or domains activity.
713 if (reapplyDomainSettingsOnRestart) {
714 // Reset the reapply domain settings on restart tracker.
715 reapplyDomainSettingsOnRestart = false;
717 // Reapply the domain settings for each tab.
718 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
719 // Get the WebView tab fragment.
720 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
722 // Get the fragment view.
723 View fragmentView = webViewTabFragment.getView();
725 // Only reload the WebViews if they exist.
726 if (fragmentView != null) {
727 // Get the nested scroll WebView from the tab fragment.
728 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
730 // Reset the current domain name so the domain settings will be reapplied.
731 nestedScrollWebView.setCurrentDomainName("");
733 // Reapply the domain settings if the URL is not null, which can happen if an empty tab is active when returning from settings.
734 if (nestedScrollWebView.getUrl() != null) {
735 applyDomainSettings(nestedScrollWebView, nestedScrollWebView.getUrl(), false, true, false);
741 // Update the bookmarks drawer if returning from the Bookmarks activity.
742 if (restartFromBookmarksActivity) {
743 // Close the bookmarks drawer.
744 drawerLayout.closeDrawer(GravityCompat.END);
746 // Reload the bookmarks drawer.
747 loadBookmarksFolder();
749 // Reset `restartFromBookmarksActivity`.
750 restartFromBookmarksActivity = false;
753 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
754 updatePrivacyIcons(true);
757 // `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.
759 public void onStart() {
760 // Run the default commands.
763 // Resume any WebViews.
764 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
765 // Get the WebView tab fragment.
766 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
768 // Get the fragment view.
769 View fragmentView = webViewTabFragment.getView();
771 // Only resume the WebViews if they exist (they won't when the app is first created).
772 if (fragmentView != null) {
773 // Get the nested scroll WebView from the tab fragment.
774 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
776 // Resume the nested scroll WebView.
777 nestedScrollWebView.onResume();
781 // Resume the nested scroll WebView JavaScript timers. This is a global command that resumes JavaScript timers on all WebViews.
782 if (currentWebView != null) {
783 currentWebView.resumeTimers();
786 // Reapply the proxy settings if the system is using a proxy. This redisplays the appropriate alert dialog.
787 if (!proxyMode.equals(ProxyHelper.NONE)) {
791 // Reapply any system UI flags.
792 if (displayingFullScreenVideo || inFullScreenBrowsingMode) { // The system is displaying a website or a video in full screen mode.
793 /* Hide the system bars.
794 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
795 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
796 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
797 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
799 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
800 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
803 // Show any pending dialogs.
804 for (int i = 0; i < pendingDialogsArrayList.size(); i++) {
805 // Get the pending dialog from the array list.
806 PendingDialog pendingDialog = pendingDialogsArrayList.get(i);
808 // Show the pending dialog.
809 pendingDialog.dialogFragment.show(getSupportFragmentManager(), pendingDialog.tag);
812 // Clear the pending dialogs array list.
813 pendingDialogsArrayList.clear();
816 // `onStop()` runs after `onPause()`. It is used instead of `onPause()` so the commands are not called every time the screen is partially hidden.
818 public void onStop() {
819 // Run the default commands.
822 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
823 // Get the WebView tab fragment.
824 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
826 // Get the fragment view.
827 View fragmentView = webViewTabFragment.getView();
829 // Only pause the WebViews if they exist (they won't when the app is first created).
830 if (fragmentView != null) {
831 // Get the nested scroll WebView from the tab fragment.
832 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
834 // Pause the nested scroll WebView.
835 nestedScrollWebView.onPause();
839 // Pause the WebView JavaScript timers. This is a global command that pauses JavaScript on all WebViews.
840 if (currentWebView != null) {
841 currentWebView.pauseTimers();
846 public void onSaveInstanceState(@NonNull Bundle savedInstanceState) {
847 // Run the default commands.
848 super.onSaveInstanceState(savedInstanceState);
850 // Create the saved state array lists.
851 ArrayList<Bundle> savedStateArrayList = new ArrayList<>();
852 ArrayList<Bundle> savedNestedScrollWebViewStateArrayList = new ArrayList<>();
854 // Get the URLs from each tab.
855 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
856 // Get the WebView tab fragment.
857 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
859 // Get the fragment view.
860 View fragmentView = webViewTabFragment.getView();
862 if (fragmentView != null) {
863 // Get the nested scroll WebView from the tab fragment.
864 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
866 // Create saved state bundle.
867 Bundle savedStateBundle = new Bundle();
869 // Get the current states.
870 nestedScrollWebView.saveState(savedStateBundle);
871 Bundle savedNestedScrollWebViewStateBundle = nestedScrollWebView.saveNestedScrollWebViewState();
873 // Store the saved states in the array lists.
874 savedStateArrayList.add(savedStateBundle);
875 savedNestedScrollWebViewStateArrayList.add(savedNestedScrollWebViewStateBundle);
879 // Get the current tab position.
880 int currentTabPosition = tabLayout.getSelectedTabPosition();
882 // Store the saved states in the bundle.
883 savedInstanceState.putParcelableArrayList(SAVED_STATE_ARRAY_LIST, savedStateArrayList);
884 savedInstanceState.putParcelableArrayList(SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST, savedNestedScrollWebViewStateArrayList);
885 savedInstanceState.putInt(SAVED_TAB_POSITION, currentTabPosition);
886 savedInstanceState.putString(PROXY_MODE, proxyMode);
890 public void onDestroy() {
891 // Unregister the orbot status broadcast receiver if it exists.
892 if (orbotStatusBroadcastReceiver != null) {
893 this.unregisterReceiver(orbotStatusBroadcastReceiver);
896 // Close the bookmarks cursor if it exists.
897 if (bookmarksCursor != null) {
898 bookmarksCursor.close();
901 // Close the bookmarks database if it exists.
902 if (bookmarksDatabaseHelper != null) {
903 bookmarksDatabaseHelper.close();
906 // Stop populating the blocklists if the AsyncTask is running in the background.
907 if (populateBlocklists != null) {
908 populateBlocklists.cancel(true);
911 // Run the default commands.
916 public boolean onCreateOptionsMenu(Menu menu) {
917 // Inflate the menu. This adds items to the action bar if it is present.
918 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
920 // Store a handle for the options menu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons()`.
923 // Get handles for the menu items.
924 optionsPrivacyMenuItem = menu.findItem(R.id.javascript);
925 optionsRefreshMenuItem = menu.findItem(R.id.refresh);
926 MenuItem bookmarksMenuItem = menu.findItem(R.id.bookmarks);
927 optionsCookiesMenuItem = menu.findItem(R.id.cookies);
928 optionsDomStorageMenuItem = menu.findItem(R.id.dom_storage);
929 optionsSaveFormDataMenuItem = menu.findItem(R.id.save_form_data); // Form data can be removed once the minimum API >= 26.
930 optionsClearDataMenuItem = menu.findItem(R.id.clear_data);
931 optionsClearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
932 optionsClearDomStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
933 optionsClearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
934 optionsBlocklistsMenuItem = menu.findItem(R.id.blocklists);
935 optionsEasyListMenuItem = menu.findItem(R.id.easylist);
936 optionsEasyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
937 optionsFanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
938 optionsFanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
939 optionsUltraListMenuItem = menu.findItem(R.id.ultralist);
940 optionsUltraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
941 optionsBlockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
942 optionsProxyMenuItem = menu.findItem(R.id.proxy);
943 optionsProxyNoneMenuItem = menu.findItem(R.id.proxy_none);
944 optionsProxyTorMenuItem = menu.findItem(R.id.proxy_tor);
945 optionsProxyI2pMenuItem = menu.findItem(R.id.proxy_i2p);
946 optionsProxyCustomMenuItem = menu.findItem(R.id.proxy_custom);
947 optionsUserAgentMenuItem = menu.findItem(R.id.user_agent);
948 optionsUserAgentPrivacyBrowserMenuItem = menu.findItem(R.id.user_agent_privacy_browser);
949 optionsUserAgentWebViewDefaultMenuItem = menu.findItem(R.id.user_agent_webview_default);
950 optionsUserAgentFirefoxOnAndroidMenuItem = menu.findItem(R.id.user_agent_firefox_on_android);
951 optionsUserAgentChromeOnAndroidMenuItem = menu.findItem(R.id.user_agent_chrome_on_android);
952 optionsUserAgentSafariOnIosMenuItem = menu.findItem(R.id.user_agent_safari_on_ios);
953 optionsUserAgentFirefoxOnLinuxMenuItem = menu.findItem(R.id.user_agent_firefox_on_linux);
954 optionsUserAgentChromiumOnLinuxMenuItem = menu.findItem(R.id.user_agent_chromium_on_linux);
955 optionsUserAgentFirefoxOnWindowsMenuItem = menu.findItem(R.id.user_agent_firefox_on_windows);
956 optionsUserAgentChromeOnWindowsMenuItem = menu.findItem(R.id.user_agent_chrome_on_windows);
957 optionsUserAgentEdgeOnWindowsMenuItem = menu.findItem(R.id.user_agent_edge_on_windows);
958 optionsUserAgentInternetExplorerOnWindowsMenuItem = menu.findItem(R.id.user_agent_internet_explorer_on_windows);
959 optionsUserAgentSafariOnMacosMenuItem = menu.findItem(R.id.user_agent_safari_on_macos);
960 optionsUserAgentCustomMenuItem = menu.findItem(R.id.user_agent_custom);
961 optionsSwipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
962 optionsWideViewportMenuItem = menu.findItem(R.id.wide_viewport);
963 optionsDisplayImagesMenuItem = menu.findItem(R.id.display_images);
964 optionsDarkWebViewMenuItem = menu.findItem(R.id.dark_webview);
965 optionsFontSizeMenuItem = menu.findItem(R.id.font_size);
966 optionsAddOrEditDomainMenuItem = menu.findItem(R.id.add_or_edit_domain);
968 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
969 updatePrivacyIcons(false);
971 // Only display the form data menu items if the API < 26.
972 optionsSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
973 optionsClearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
975 // Disable the clear form data menu item if the API >= 26 so that the status of the main Clear Data is calculated correctly.
976 optionsClearFormDataMenuItem.setEnabled(Build.VERSION.SDK_INT < 26);
978 // Get the shared preferences.
979 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
981 // Get the dark theme and app bar preferences.
982 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean(getString(R.string.display_additional_app_bar_icons_key), false);
984 // 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.
985 if (displayAdditionalAppBarIcons) {
986 optionsRefreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
987 bookmarksMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
988 optionsCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
989 } else { //Do not display the additional icons.
990 optionsRefreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
991 bookmarksMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
992 optionsCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
995 // Replace Refresh with Stop if a URL is already loading.
996 if (currentWebView != null && currentWebView.getProgress() != 100) {
998 optionsRefreshMenuItem.setTitle(R.string.stop);
1000 // Set the icon if it is displayed in the app bar. Once the minimum API is >= 26, the blue and black icons can be combined with a tint list.
1001 if (displayAdditionalAppBarIcons) {
1002 optionsRefreshMenuItem.setIcon(R.drawable.close_blue);
1011 public boolean onPrepareOptionsMenu(Menu menu) {
1012 // Get a handle for the cookie manager.
1013 CookieManager cookieManager = CookieManager.getInstance();
1015 // Initialize the current user agent string and the font size.
1016 String currentUserAgent = getString(R.string.user_agent_privacy_browser);
1019 // 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.
1020 if (currentWebView != null) {
1021 // Set the add or edit domain text.
1022 if (currentWebView.getDomainSettingsApplied()) {
1023 optionsAddOrEditDomainMenuItem.setTitle(R.string.edit_domain_settings);
1025 optionsAddOrEditDomainMenuItem.setTitle(R.string.add_domain_settings);
1028 // Get the current user agent from the WebView.
1029 currentUserAgent = currentWebView.getSettings().getUserAgentString();
1031 // Get the current font size from the
1032 fontSize = currentWebView.getSettings().getTextZoom();
1034 // Set the status of the menu item checkboxes.
1035 optionsDomStorageMenuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1036 optionsSaveFormDataMenuItem.setChecked(currentWebView.getSettings().getSaveFormData()); // Form data can be removed once the minimum API >= 26.
1037 optionsEasyListMenuItem.setChecked(currentWebView.getEasyListEnabled());
1038 optionsEasyPrivacyMenuItem.setChecked(currentWebView.getEasyPrivacyEnabled());
1039 optionsFanboysAnnoyanceListMenuItem.setChecked(currentWebView.getFanboysAnnoyanceListEnabled());
1040 optionsFanboysSocialBlockingListMenuItem.setChecked(currentWebView.getFanboysSocialBlockingListEnabled());
1041 optionsUltraListMenuItem.setChecked(currentWebView.getUltraListEnabled());
1042 optionsUltraPrivacyMenuItem.setChecked(currentWebView.getUltraPrivacyEnabled());
1043 optionsBlockAllThirdPartyRequestsMenuItem.setChecked(currentWebView.getBlockAllThirdPartyRequests());
1044 optionsSwipeToRefreshMenuItem.setChecked(currentWebView.getSwipeToRefresh());
1045 optionsWideViewportMenuItem.setChecked(currentWebView.getSettings().getUseWideViewPort());
1046 optionsDisplayImagesMenuItem.setChecked(currentWebView.getSettings().getLoadsImagesAutomatically());
1048 // Initialize the display names for the blocklists with the number of blocked requests.
1049 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
1050 optionsEasyListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASYLIST) + " - " + getString(R.string.easylist));
1051 optionsEasyPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASYPRIVACY) + " - " + getString(R.string.easyprivacy));
1052 optionsFanboysAnnoyanceListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " + getString(R.string.fanboys_annoyance_list));
1053 optionsFanboysSocialBlockingListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " + getString(R.string.fanboys_social_blocking_list));
1054 optionsUltraListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRALIST) + " - " + getString(R.string.ultralist));
1055 optionsUltraPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRAPRIVACY) + " - " + getString(R.string.ultraprivacy));
1056 optionsBlockAllThirdPartyRequestsMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " + getString(R.string.block_all_third_party_requests));
1058 // Enable DOM Storage if JavaScript is enabled.
1059 optionsDomStorageMenuItem.setEnabled(currentWebView.getSettings().getJavaScriptEnabled());
1061 // Set the checkbox status for dark WebView if the WebView supports it.
1062 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
1063 optionsDarkWebViewMenuItem.setChecked(WebSettingsCompat.getForceDark(currentWebView.getSettings()) == WebSettingsCompat.FORCE_DARK_ON);
1067 // Set the cookies menu item checked status.
1068 optionsCookiesMenuItem.setChecked(cookieManager.acceptCookie());
1070 // Enable Clear Cookies if there are any.
1071 optionsClearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1073 // 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`.
1074 String privateDataDirectoryString = getApplicationInfo().dataDir;
1076 // Get a count of the number of files in the Local Storage directory.
1077 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1078 int localStorageDirectoryNumberOfFiles = 0;
1079 if (localStorageDirectory.exists()) {
1080 // `Objects.requireNonNull` removes a lint warning that `localStorageDirectory.list` might produce a null pointed exception if it is dereferenced.
1081 localStorageDirectoryNumberOfFiles = Objects.requireNonNull(localStorageDirectory.list()).length;
1084 // Get a count of the number of files in the IndexedDB directory.
1085 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1086 int indexedDBDirectoryNumberOfFiles = 0;
1087 if (indexedDBDirectory.exists()) {
1088 // `Objects.requireNonNull` removes a lint warning that `indexedDBDirectory.list` might produce a null pointed exception if it is dereferenced.
1089 indexedDBDirectoryNumberOfFiles = Objects.requireNonNull(indexedDBDirectory.list()).length;
1092 // Enable Clear DOM Storage if there is any.
1093 optionsClearDomStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1095 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
1096 if (Build.VERSION.SDK_INT < 26) {
1097 // Get the WebView database.
1098 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1100 // Enable the clear form data menu item if there is anything to clear.
1101 optionsClearFormDataMenuItem.setEnabled(webViewDatabase.hasFormData());
1104 // Enable Clear Data if any of the submenu items are enabled.
1105 optionsClearDataMenuItem.setEnabled(optionsClearCookiesMenuItem.isEnabled() || optionsClearDomStorageMenuItem.isEnabled() || optionsClearFormDataMenuItem.isEnabled());
1107 // Disable Fanboy's Social Blocking List menu item if Fanboy's Annoyance List is checked.
1108 optionsFanboysSocialBlockingListMenuItem.setEnabled(!optionsFanboysAnnoyanceListMenuItem.isChecked());
1110 // Set the proxy title and check the applied proxy.
1111 switch (proxyMode) {
1112 case ProxyHelper.NONE:
1113 // Set the proxy title.
1114 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_none));
1116 // Check the proxy None radio button.
1117 optionsProxyNoneMenuItem.setChecked(true);
1120 case ProxyHelper.TOR:
1121 // Set the proxy title.
1122 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_tor));
1124 // Check the proxy Tor radio button.
1125 optionsProxyTorMenuItem.setChecked(true);
1128 case ProxyHelper.I2P:
1129 // Set the proxy title.
1130 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_i2p));
1132 // Check the proxy I2P radio button.
1133 optionsProxyI2pMenuItem.setChecked(true);
1136 case ProxyHelper.CUSTOM:
1137 // Set the proxy title.
1138 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_custom));
1140 // Check the proxy Custom radio button.
1141 optionsProxyCustomMenuItem.setChecked(true);
1145 // Select the current user agent menu item. A switch statement cannot be used because the user agents are not compile time constants.
1146 if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) { // Privacy Browser.
1147 // Update the user agent menu item title.
1148 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_privacy_browser));
1150 // Select the Privacy Browser radio box.
1151 optionsUserAgentPrivacyBrowserMenuItem.setChecked(true);
1152 } else if (currentUserAgent.equals(webViewDefaultUserAgent)) { // WebView Default.
1153 // Update the user agent menu item title.
1154 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_webview_default));
1156 // Select the WebView Default radio box.
1157 optionsUserAgentWebViewDefaultMenuItem.setChecked(true);
1158 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) { // Firefox on Android.
1159 // Update the user agent menu item title.
1160 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_android));
1162 // Select the Firefox on Android radio box.
1163 optionsUserAgentFirefoxOnAndroidMenuItem.setChecked(true);
1164 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) { // Chrome on Android.
1165 // Update the user agent menu item title.
1166 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_android));
1168 // Select the Chrome on Android radio box.
1169 optionsUserAgentChromeOnAndroidMenuItem.setChecked(true);
1170 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) { // Safari on iOS.
1171 // Update the user agent menu item title.
1172 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_ios));
1174 // Select the Safari on iOS radio box.
1175 optionsUserAgentSafariOnIosMenuItem.setChecked(true);
1176 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) { // Firefox on Linux.
1177 // Update the user agent menu item title.
1178 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_linux));
1180 // Select the Firefox on Linux radio box.
1181 optionsUserAgentFirefoxOnLinuxMenuItem.setChecked(true);
1182 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) { // Chromium on Linux.
1183 // Update the user agent menu item title.
1184 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chromium_on_linux));
1186 // Select the Chromium on Linux radio box.
1187 optionsUserAgentChromiumOnLinuxMenuItem.setChecked(true);
1188 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) { // Firefox on Windows.
1189 // Update the user agent menu item title.
1190 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_windows));
1192 // Select the Firefox on Windows radio box.
1193 optionsUserAgentFirefoxOnWindowsMenuItem.setChecked(true);
1194 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) { // Chrome on Windows.
1195 // Update the user agent menu item title.
1196 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_windows));
1198 // Select the Chrome on Windows radio box.
1199 optionsUserAgentChromeOnWindowsMenuItem.setChecked(true);
1200 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) { // Edge on Windows.
1201 // Update the user agent menu item title.
1202 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_edge_on_windows));
1204 // Select the Edge on Windows radio box.
1205 optionsUserAgentEdgeOnWindowsMenuItem.setChecked(true);
1206 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) { // Internet Explorer on Windows.
1207 // Update the user agent menu item title.
1208 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_internet_explorer_on_windows));
1210 // Select the Internet on Windows radio box.
1211 optionsUserAgentInternetExplorerOnWindowsMenuItem.setChecked(true);
1212 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) { // Safari on macOS.
1213 // Update the user agent menu item title.
1214 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_macos));
1216 // Select the Safari on macOS radio box.
1217 optionsUserAgentSafariOnMacosMenuItem.setChecked(true);
1218 } else { // Custom user agent.
1219 // Update the user agent menu item title.
1220 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_custom));
1222 // Select the Custom radio box.
1223 optionsUserAgentCustomMenuItem.setChecked(true);
1226 // Set the font size title.
1227 optionsFontSizeMenuItem.setTitle(getString(R.string.font_size) + " - " + fontSize + "%");
1229 // Run all the other default commands.
1230 super.onPrepareOptionsMenu(menu);
1232 // Display the menu.
1237 public boolean onOptionsItemSelected(MenuItem menuItem) {
1238 // Get a handle for the shared preferences.
1239 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1241 // Get a handle for the cookie manager.
1242 CookieManager cookieManager = CookieManager.getInstance();
1244 // Get the selected menu item ID.
1245 int menuItemId = menuItem.getItemId();
1247 // Run the commands that correlate to the selected menu item.
1248 if (menuItemId == R.id.javascript) { // JavaScript.
1249 // Toggle the JavaScript status.
1250 currentWebView.getSettings().setJavaScriptEnabled(!currentWebView.getSettings().getJavaScriptEnabled());
1252 // Update the privacy icon.
1253 updatePrivacyIcons(true);
1255 // Display a `Snackbar`.
1256 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScrip is enabled.
1257 Snackbar.make(webViewPager, R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1258 } else if (cookieManager.acceptCookie()) { // JavaScript is disabled, but first-party cookies are enabled.
1259 Snackbar.make(webViewPager, R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1260 } else { // Privacy mode.
1261 Snackbar.make(webViewPager, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1264 // Reload the current WebView.
1265 currentWebView.reload();
1267 // Consume the event.
1269 } else if (menuItemId == R.id.refresh) { // Refresh.
1270 // Run the command that correlates to the current status of the menu item.
1271 if (menuItem.getTitle().equals(getString(R.string.refresh))) { // The refresh button was pushed.
1272 // Reload the current WebView.
1273 currentWebView.reload();
1274 } else { // The stop button was pushed.
1275 // Stop the loading of the WebView.
1276 currentWebView.stopLoading();
1279 // Consume the event.
1281 } else if (menuItemId == R.id.bookmarks) { // Bookmarks.
1282 // Open the bookmarks drawer.
1283 drawerLayout.openDrawer(GravityCompat.END);
1285 // Consume the event.
1287 } else if (menuItemId == R.id.cookies) { // Cookies.
1288 // Switch the first-party cookie status.
1289 cookieManager.setAcceptCookie(!cookieManager.acceptCookie());
1291 // Store the cookie status.
1292 currentWebView.setAcceptCookies(cookieManager.acceptCookie());
1294 // Update the menu checkbox.
1295 menuItem.setChecked(cookieManager.acceptCookie());
1297 // Update the privacy icon.
1298 updatePrivacyIcons(true);
1300 // Display a snackbar.
1301 if (cookieManager.acceptCookie()) { // Cookies are enabled.
1302 Snackbar.make(webViewPager, R.string.cookies_enabled, Snackbar.LENGTH_SHORT).show();
1303 } else if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is still enabled.
1304 Snackbar.make(webViewPager, R.string.cookies_disabled, Snackbar.LENGTH_SHORT).show();
1305 } else { // Privacy mode.
1306 Snackbar.make(webViewPager, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1309 // Reload the current WebView.
1310 currentWebView.reload();
1312 // Consume the event.
1314 } else if (menuItemId == R.id.dom_storage) { // DOM storage.
1315 // Toggle the status of domStorageEnabled.
1316 currentWebView.getSettings().setDomStorageEnabled(!currentWebView.getSettings().getDomStorageEnabled());
1318 // Update the menu checkbox.
1319 menuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1321 // Update the privacy icon.
1322 updatePrivacyIcons(true);
1324 // Display a snackbar.
1325 if (currentWebView.getSettings().getDomStorageEnabled()) {
1326 Snackbar.make(webViewPager, R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1328 Snackbar.make(webViewPager, R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1331 // Reload the current WebView.
1332 currentWebView.reload();
1334 // Consume the event.
1336 } else if (menuItemId == R.id.save_form_data) { // Form data. This can be removed once the minimum API >= 26.
1337 // Switch the status of saveFormDataEnabled.
1338 currentWebView.getSettings().setSaveFormData(!currentWebView.getSettings().getSaveFormData());
1340 // Update the menu checkbox.
1341 menuItem.setChecked(currentWebView.getSettings().getSaveFormData());
1343 // Display a snackbar.
1344 if (currentWebView.getSettings().getSaveFormData()) {
1345 Snackbar.make(webViewPager, R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1347 Snackbar.make(webViewPager, R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1350 // Update the privacy icon.
1351 updatePrivacyIcons(true);
1353 // Reload the current WebView.
1354 currentWebView.reload();
1356 // Consume the event.
1358 } else if (menuItemId == R.id.clear_cookies) { // Clear cookies.
1359 // Create a snackbar.
1360 Snackbar.make(webViewPager, R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1361 .setAction(R.string.undo, v -> {
1362 // Do nothing because everything will be handled by `onDismissed()` below.
1364 .addCallback(new Snackbar.Callback() {
1366 public void onDismissed(Snackbar snackbar, int event) {
1367 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1368 // Delete the cookies.
1369 cookieManager.removeAllCookies(null);
1375 // Consume the event.
1377 } else if (menuItemId == R.id.clear_dom_storage) { // Clear DOM storage.
1378 // Create a snackbar.
1379 Snackbar.make(webViewPager, R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1380 .setAction(R.string.undo, v -> {
1381 // Do nothing because everything will be handled by `onDismissed()` below.
1383 .addCallback(new Snackbar.Callback() {
1385 public void onDismissed(Snackbar snackbar, int event) {
1386 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1387 // Delete the DOM Storage.
1388 WebStorage webStorage = WebStorage.getInstance();
1389 webStorage.deleteAllData();
1391 // Initialize a handler to manually delete the DOM storage files and directories.
1392 Handler deleteDomStorageHandler = new Handler();
1394 // Setup a runnable to manually delete the DOM storage files and directories.
1395 Runnable deleteDomStorageRunnable = () -> {
1397 // Get a handle for the runtime.
1398 Runtime runtime = Runtime.getRuntime();
1400 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
1401 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
1402 String privateDataDirectoryString = getApplicationInfo().dataDir;
1404 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1405 Process deleteLocalStorageProcess = runtime.exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1407 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1408 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1409 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1410 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1411 Process deleteDatabasesProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1413 // Wait for the processes to finish.
1414 deleteLocalStorageProcess.waitFor();
1415 deleteIndexProcess.waitFor();
1416 deleteQuotaManagerProcess.waitFor();
1417 deleteQuotaManagerJournalProcess.waitFor();
1418 deleteDatabasesProcess.waitFor();
1419 } catch (Exception exception) {
1420 // Do nothing if an error is thrown.
1424 // Manually delete the DOM storage files after 200 milliseconds.
1425 deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200);
1431 // Consume the event.
1433 } else if (menuItemId == R.id.clear_form_data) { // Clear form data. This can be remove once the minimum API >= 26.
1434 // Create a snackbar.
1435 Snackbar.make(webViewPager, R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1436 .setAction(R.string.undo, v -> {
1437 // Do nothing because everything will be handled by `onDismissed()` below.
1439 .addCallback(new Snackbar.Callback() {
1441 public void onDismissed(Snackbar snackbar, int event) {
1442 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1443 // Get a handle for the webView database.
1444 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1446 // Delete the form data.
1447 webViewDatabase.clearFormData();
1453 // Consume the event.
1455 } else if (menuItemId == R.id.easylist) { // EasyList.
1456 // Toggle the EasyList status.
1457 currentWebView.setEasyListEnabled(!currentWebView.getEasyListEnabled());
1459 // Update the menu checkbox.
1460 menuItem.setChecked(currentWebView.getEasyListEnabled());
1462 // Reload the current WebView.
1463 currentWebView.reload();
1465 // Consume the event.
1467 } else if (menuItemId == R.id.easyprivacy) { // EasyPrivacy.
1468 // Toggle the EasyPrivacy status.
1469 currentWebView.setEasyPrivacyEnabled(!currentWebView.getEasyPrivacyEnabled());
1471 // Update the menu checkbox.
1472 menuItem.setChecked(currentWebView.getEasyPrivacyEnabled());
1474 // Reload the current WebView.
1475 currentWebView.reload();
1477 // Consume the event.
1479 } else if (menuItemId == R.id.fanboys_annoyance_list) { // Fanboy's Annoyance List.
1480 // Toggle Fanboy's Annoyance List status.
1481 currentWebView.setFanboysAnnoyanceListEnabled(!currentWebView.getFanboysAnnoyanceListEnabled());
1483 // Update the menu checkbox.
1484 menuItem.setChecked(currentWebView.getFanboysAnnoyanceListEnabled());
1486 // Update the status of Fanboy's Social Blocking List.
1487 optionsFanboysSocialBlockingListMenuItem.setEnabled(!currentWebView.getFanboysAnnoyanceListEnabled());
1489 // Reload the current WebView.
1490 currentWebView.reload();
1492 // Consume the event.
1494 } else if (menuItemId == R.id.fanboys_social_blocking_list) { // Fanboy's Social Blocking List.
1495 // Toggle Fanboy's Social Blocking List status.
1496 currentWebView.setFanboysSocialBlockingListEnabled(!currentWebView.getFanboysSocialBlockingListEnabled());
1498 // Update the menu checkbox.
1499 menuItem.setChecked(currentWebView.getFanboysSocialBlockingListEnabled());
1501 // Reload the current WebView.
1502 currentWebView.reload();
1504 // Consume the event.
1506 } else if (menuItemId == R.id.ultralist) { // UltraList.
1507 // Toggle the UltraList status.
1508 currentWebView.setUltraListEnabled(!currentWebView.getUltraListEnabled());
1510 // Update the menu checkbox.
1511 menuItem.setChecked(currentWebView.getUltraListEnabled());
1513 // Reload the current WebView.
1514 currentWebView.reload();
1516 // Consume the event.
1518 } else if (menuItemId == R.id.ultraprivacy) { // UltraPrivacy.
1519 // Toggle the UltraPrivacy status.
1520 currentWebView.setUltraPrivacyEnabled(!currentWebView.getUltraPrivacyEnabled());
1522 // Update the menu checkbox.
1523 menuItem.setChecked(currentWebView.getUltraPrivacyEnabled());
1525 // Reload the current WebView.
1526 currentWebView.reload();
1528 // Consume the event.
1530 } else if (menuItemId == R.id.block_all_third_party_requests) { // Block all third-party requests.
1531 //Toggle the third-party requests blocker status.
1532 currentWebView.setBlockAllThirdPartyRequests(!currentWebView.getBlockAllThirdPartyRequests());
1534 // Update the menu checkbox.
1535 menuItem.setChecked(currentWebView.getBlockAllThirdPartyRequests());
1537 // Reload the current WebView.
1538 currentWebView.reload();
1540 // Consume the event.
1542 } else if (menuItemId == R.id.proxy_none) { // Proxy - None.
1543 // Update the proxy mode.
1544 proxyMode = ProxyHelper.NONE;
1546 // Apply the proxy mode.
1549 // Consume the event.
1551 } else if (menuItemId == R.id.proxy_tor) { // Proxy - Tor.
1552 // Update the proxy mode.
1553 proxyMode = ProxyHelper.TOR;
1555 // Apply the proxy mode.
1558 // Consume the event.
1560 } else if (menuItemId == R.id.proxy_i2p) { // Proxy - I2P.
1561 // Update the proxy mode.
1562 proxyMode = ProxyHelper.I2P;
1564 // Apply the proxy mode.
1567 // Consume the event.
1569 } else if (menuItemId == R.id.proxy_custom) { // Proxy - Custom.
1570 // Update the proxy mode.
1571 proxyMode = ProxyHelper.CUSTOM;
1573 // Apply the proxy mode.
1576 // Consume the event.
1578 } else if (menuItemId == R.id.user_agent_privacy_browser) { // User Agent - Privacy Browser.
1579 // Update the user agent.
1580 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
1582 // Reload the current WebView.
1583 currentWebView.reload();
1585 // Consume the event.
1587 } else if (menuItemId == R.id.user_agent_webview_default) { // User Agent - WebView Default.
1588 // Update the user agent.
1589 currentWebView.getSettings().setUserAgentString("");
1591 // Reload the current WebView.
1592 currentWebView.reload();
1594 // Consume the event.
1596 } else if (menuItemId == R.id.user_agent_firefox_on_android) { // User Agent - Firefox on Android.
1597 // Update the user agent.
1598 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
1600 // Reload the current WebView.
1601 currentWebView.reload();
1603 // Consume the event.
1605 } else if (menuItemId == R.id.user_agent_chrome_on_android) { // User Agent - Chrome on Android.
1606 // Update the user agent.
1607 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
1609 // Reload the current WebView.
1610 currentWebView.reload();
1612 // Consume the event.
1614 } else if (menuItemId == R.id.user_agent_safari_on_ios) { // User Agent - Safari on iOS.
1615 // Update the user agent.
1616 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
1618 // Reload the current WebView.
1619 currentWebView.reload();
1621 // Consume the event.
1623 } else if (menuItemId == R.id.user_agent_firefox_on_linux) { // User Agent - Firefox on Linux.
1624 // Update the user agent.
1625 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
1627 // Reload the current WebView.
1628 currentWebView.reload();
1630 // Consume the event.
1632 } else if (menuItemId == R.id.user_agent_chromium_on_linux) { // User Agent - Chromium on Linux.
1633 // Update the user agent.
1634 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
1636 // Reload the current WebView.
1637 currentWebView.reload();
1639 // Consume the event.
1641 } else if (menuItemId == R.id.user_agent_firefox_on_windows) { // User Agent - Firefox on Windows.
1642 // Update the user agent.
1643 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
1645 // Reload the current WebView.
1646 currentWebView.reload();
1648 // Consume the event.
1650 } else if (menuItemId == R.id.user_agent_chrome_on_windows) { // User Agent - Chrome on Windows.
1651 // Update the user agent.
1652 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
1654 // Reload the current WebView.
1655 currentWebView.reload();
1657 // Consume the event.
1659 } else if (menuItemId == R.id.user_agent_edge_on_windows) { // User Agent - Edge on Windows.
1660 // Update the user agent.
1661 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
1663 // Reload the current WebView.
1664 currentWebView.reload();
1666 // Consume the event.
1668 } else if (menuItemId == R.id.user_agent_internet_explorer_on_windows) { // User Agent - Internet Explorer on Windows.
1669 // Update the user agent.
1670 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
1672 // Reload the current WebView.
1673 currentWebView.reload();
1675 // Consume the event.
1677 } else if (menuItemId == R.id.user_agent_safari_on_macos) { // User Agent - Safari on macOS.
1678 // Update the user agent.
1679 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
1681 // Reload the current WebView.
1682 currentWebView.reload();
1684 // Consume the event.
1686 } else if (menuItemId == R.id.user_agent_custom) { // User Agent - Custom.
1687 // Update the user agent.
1688 currentWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
1690 // Reload the current WebView.
1691 currentWebView.reload();
1693 // Consume the event.
1695 } else if (menuItemId == R.id.font_size) { // Font size.
1696 // Instantiate the font size dialog.
1697 DialogFragment fontSizeDialogFragment = FontSizeDialog.displayDialog(currentWebView.getSettings().getTextZoom());
1699 // Show the font size dialog.
1700 fontSizeDialogFragment.show(getSupportFragmentManager(), getString(R.string.font_size));
1702 // Consume the event.
1704 } else if (menuItemId == R.id.swipe_to_refresh) { // Swipe to refresh.
1705 // Toggle the stored status of swipe to refresh.
1706 currentWebView.setSwipeToRefresh(!currentWebView.getSwipeToRefresh());
1708 // Update the swipe refresh layout.
1709 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
1710 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
1711 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
1712 } else { // Swipe to refresh is disabled.
1713 // Disable the swipe refresh layout.
1714 swipeRefreshLayout.setEnabled(false);
1717 // Consume the event.
1719 } else if (menuItemId == R.id.wide_viewport) { // Wide viewport.
1720 // Toggle the viewport.
1721 currentWebView.getSettings().setUseWideViewPort(!currentWebView.getSettings().getUseWideViewPort());
1723 // Consume the event.
1725 } else if (menuItemId == R.id.display_images) { // Display images.
1726 // Toggle the displaying of images.
1727 if (currentWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1728 // Disable loading of images.
1729 currentWebView.getSettings().setLoadsImagesAutomatically(false);
1731 // Reload the website to remove existing images.
1732 currentWebView.reload();
1733 } else { // Images are not currently loaded automatically.
1734 // Enable loading of images. Missing images will be loaded without the need for a reload.
1735 currentWebView.getSettings().setLoadsImagesAutomatically(true);
1738 // Consume the event.
1740 } else if (menuItemId == R.id.dark_webview) { // Dark WebView.
1741 // Check to see if dark WebView is supported by this WebView.
1742 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
1743 // Toggle the dark WebView setting.
1744 if (WebSettingsCompat.getForceDark(currentWebView.getSettings()) == WebSettingsCompat.FORCE_DARK_ON) { // Dark WebView is currently enabled.
1745 // Turn off dark WebView.
1746 WebSettingsCompat.setForceDark(currentWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
1747 } else { // Dark WebView is currently disabled.
1748 // Turn on dark WebView.
1749 WebSettingsCompat.setForceDark(currentWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
1753 // Consume the event.
1755 } else if (menuItemId == R.id.find_on_page) { // Find on page.
1756 // Get a handle for the views.
1757 Toolbar toolbar = findViewById(R.id.toolbar);
1758 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
1759 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
1761 // Set the minimum height of the find on page linear layout to match the toolbar.
1762 findOnPageLinearLayout.setMinimumHeight(toolbar.getHeight());
1764 // Hide the toolbar.
1765 toolbar.setVisibility(View.GONE);
1767 // Show the find on page linear layout.
1768 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1770 // Display the keyboard. The app must wait 200 ms before running the command to work around a bug in Android.
1771 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1772 findOnPageEditText.postDelayed(() -> {
1773 // Set the focus on the find on page edit text.
1774 findOnPageEditText.requestFocus();
1776 // Get a handle for the input method manager.
1777 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1779 // Remove the lint warning below that the input method manager might be null.
1780 assert inputMethodManager != null;
1782 // Display the keyboard. `0` sets no input flags.
1783 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1786 // Consume the event.
1788 } else if (menuItemId == R.id.print) { // Print.
1789 // Get a print manager instance.
1790 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1792 // Remove the lint error below that print manager might be null.
1793 assert printManager != null;
1795 // Create a print document adapter from the current WebView.
1796 PrintDocumentAdapter printDocumentAdapter = currentWebView.createPrintDocumentAdapter(getString(R.string.print));
1798 // Print the document.
1799 printManager.print(getString(R.string.privacy_browser_webpage), printDocumentAdapter, null);
1801 // Consume the event.
1803 } else if (menuItemId == R.id.save_url) { // Save URL.
1804 // Check the download preference.
1805 if (downloadWithExternalApp) { // Download with an external app.
1806 downloadUrlWithExternalApp(currentWebView.getCurrentUrl());
1807 } else { // Handle the download inside of Privacy Browser.
1808 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
1809 new PrepareSaveDialog(this, this, getSupportFragmentManager(), currentWebView.getSettings().getUserAgentString(),
1810 currentWebView.getAcceptCookies()).execute(currentWebView.getCurrentUrl());
1813 // Consume the event.
1815 } else if (menuItemId == R.id.save_archive) {
1816 // Open the file picker with a default file name built from the current domain name.
1817 saveWebpageArchiveActivityResultLauncher.launch(currentWebView.getCurrentDomainName() + ".mht");
1819 // Consume the event.
1821 } else if (menuItemId == R.id.save_image) { // Save image.
1822 // Open the file picker with a default file name built from the current domain name.
1823 saveWebpageImageActivityResultLauncher.launch(currentWebView.getCurrentDomainName() + ".png");
1825 // Consume the event.
1827 } else if (menuItemId == R.id.add_to_homescreen) { // Add to homescreen.
1828 // Instantiate the create home screen shortcut dialog.
1829 DialogFragment createHomeScreenShortcutDialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView.getTitle(), currentWebView.getUrl(),
1830 currentWebView.getFavoriteOrDefaultIcon());
1832 // Show the create home screen shortcut dialog.
1833 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
1835 // Consume the event.
1837 } else if (menuItemId == R.id.view_source) { // View source.
1838 // Create an intent to launch the view source activity.
1839 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
1841 // Add the variables to the intent.
1842 viewSourceIntent.putExtra(ViewSourceActivityKt.CURRENT_URL, currentWebView.getUrl());
1843 viewSourceIntent.putExtra(ViewSourceActivityKt.USER_AGENT, currentWebView.getSettings().getUserAgentString());
1846 startActivity(viewSourceIntent);
1848 // Consume the event.
1850 } else if (menuItemId == R.id.share_message) { // Share a message.
1851 // Prepare the share string.
1852 String shareString = currentWebView.getTitle() + " – " + currentWebView.getUrl();
1854 // Create the share intent.
1855 Intent shareMessageIntent = new Intent(Intent.ACTION_SEND);
1857 // Add the share string to the intent.
1858 shareMessageIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1860 // Set the MIME type.
1861 shareMessageIntent.setType("text/plain");
1863 // Set the intent to open in a new task.
1864 shareMessageIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1867 startActivity(Intent.createChooser(shareMessageIntent, getString(R.string.share_message)));
1869 // Consume the event.
1871 } else if (menuItemId == R.id.share_url) { // Share URL.
1872 // Create the share intent.
1873 Intent shareUrlIntent = new Intent(Intent.ACTION_SEND);
1875 // Add the URL to the intent.
1876 shareUrlIntent.putExtra(Intent.EXTRA_TEXT, currentWebView.getUrl());
1878 // Add the title to the intent.
1879 shareUrlIntent.putExtra(Intent.EXTRA_SUBJECT, currentWebView.getTitle());
1881 // Set the MIME type.
1882 shareUrlIntent.setType("text/plain");
1884 // Set the intent to open in a new task.
1885 shareUrlIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1888 startActivity(Intent.createChooser(shareUrlIntent, getString(R.string.share_url)));
1890 // Consume the event.
1892 } else if (menuItemId == R.id.open_with_app) { // Open with app.
1893 // Open the URL with an outside app.
1894 openWithApp(currentWebView.getUrl());
1896 // Consume the event.
1898 } else if (menuItemId == R.id.open_with_browser) { // Open with browser.
1899 // Open the URL with an outside browser.
1900 openWithBrowser(currentWebView.getUrl());
1902 // Consume the event.
1904 } else if (menuItemId == R.id.add_or_edit_domain) { // Add or edit domain.
1905 // Check if domain settings currently exist.
1906 if (currentWebView.getDomainSettingsApplied()) { // Edit the current domain settings.
1907 // Reapply the domain settings on returning to `MainWebViewActivity`.
1908 reapplyDomainSettingsOnRestart = true;
1910 // Create an intent to launch the domains activity.
1911 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1913 // Add the extra information to the intent.
1914 domainsIntent.putExtra("load_domain", currentWebView.getDomainSettingsDatabaseId());
1915 domainsIntent.putExtra("close_on_back", true);
1916 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1917 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1919 // Get the current certificate.
1920 SslCertificate sslCertificate = currentWebView.getCertificate();
1922 // Check to see if the SSL certificate is populated.
1923 if (sslCertificate != null) {
1924 // Extract the certificate to strings.
1925 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1926 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1927 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1928 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1929 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1930 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1931 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1932 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1934 // Add the certificate to the intent.
1935 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1936 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1937 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1938 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1939 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1940 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1941 domainsIntent.putExtra("ssl_start_date", startDateLong);
1942 domainsIntent.putExtra("ssl_end_date", endDateLong);
1946 startActivity(domainsIntent);
1947 } else { // Add a new domain.
1948 // Apply the new domain settings on returning to `MainWebViewActivity`.
1949 reapplyDomainSettingsOnRestart = true;
1951 // Get the current domain
1952 Uri currentUri = Uri.parse(currentWebView.getUrl());
1953 String currentDomain = currentUri.getHost();
1955 // Initialize the database handler.
1956 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this);
1958 // Create the domain and store the database ID.
1959 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1961 // Create an intent to launch the domains activity.
1962 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1964 // Add the extra information to the intent.
1965 domainsIntent.putExtra("load_domain", newDomainDatabaseId);
1966 domainsIntent.putExtra("close_on_back", true);
1967 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1968 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1970 // Get the current certificate.
1971 SslCertificate sslCertificate = currentWebView.getCertificate();
1973 // Check to see if the SSL certificate is populated.
1974 if (sslCertificate != null) {
1975 // Extract the certificate to strings.
1976 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1977 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1978 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1979 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1980 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1981 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1982 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1983 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1985 // Add the certificate to the intent.
1986 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1987 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1988 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1989 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1990 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1991 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1992 domainsIntent.putExtra("ssl_start_date", startDateLong);
1993 domainsIntent.putExtra("ssl_end_date", endDateLong);
1997 startActivity(domainsIntent);
2000 // Consume the event.
2002 } else { // There is no match with the options menu. Pass the event up to the parent method.
2003 // Don't consume the event.
2004 return super.onOptionsItemSelected(menuItem);
2008 // removeAllCookies is deprecated, but it is required for API < 21.
2010 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2011 // Get a handle for the shared preferences.
2012 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2014 // Get the menu item ID.
2015 int menuItemId = menuItem.getItemId();
2017 // Run the commands that correspond to the selected menu item.
2018 if (menuItemId == R.id.clear_and_exit) { // Clear and exit.
2019 // Clear and exit Privacy Browser.
2021 } else if (menuItemId == R.id.home) { // Home.
2022 // Load the homepage.
2023 loadUrl(currentWebView, sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
2024 } else if (menuItemId == R.id.back) { // Back.
2025 // Check if the WebView can go back.
2026 if (currentWebView.canGoBack()) {
2027 // Get the current web back forward list.
2028 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
2030 // Get the previous entry URL.
2031 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
2033 // Apply the domain settings.
2034 applyDomainSettings(currentWebView, previousUrl, false, false, false);
2036 // Load the previous website in the history.
2037 currentWebView.goBack();
2039 } else if (menuItemId == R.id.forward) { // Forward.
2040 // Check if the WebView can go forward.
2041 if (currentWebView.canGoForward()) {
2042 // Get the current web back forward list.
2043 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
2045 // Get the next entry URL.
2046 String nextUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() + 1).getUrl();
2048 // Apply the domain settings.
2049 applyDomainSettings(currentWebView, nextUrl, false, false, false);
2051 // Load the next website in the history.
2052 currentWebView.goForward();
2054 } else if (menuItemId == R.id.history) { // History.
2055 // Instantiate the URL history dialog.
2056 DialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(currentWebView.getWebViewFragmentId());
2058 // Show the URL history dialog.
2059 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2060 } else if (menuItemId == R.id.open) { // Open.
2061 // Instantiate the open file dialog.
2062 DialogFragment openDialogFragment = new OpenDialog();
2064 // Show the open file dialog.
2065 openDialogFragment.show(getSupportFragmentManager(), getString(R.string.open));
2066 } else if (menuItemId == R.id.requests) { // Requests.
2067 // Populate the resource requests.
2068 RequestsActivity.resourceRequests = currentWebView.getResourceRequests();
2070 // Create an intent to launch the Requests activity.
2071 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2073 // Add the block third-party requests status to the intent.
2074 requestsIntent.putExtra("block_all_third_party_requests", currentWebView.getBlockAllThirdPartyRequests());
2077 startActivity(requestsIntent);
2078 } else if (menuItemId == R.id.downloads) { // Downloads.
2079 // Try the default system download manager.
2081 // Launch the default system Download Manager.
2082 Intent defaultDownloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2084 // Launch as a new task so that the download manager and Privacy Browser show as separate windows in the recent tasks list.
2085 defaultDownloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2088 startActivity(defaultDownloadManagerIntent);
2089 } catch (Exception defaultDownloadManagerException) {
2090 // Try a generic file manager.
2092 // Create a generic file manager intent.
2093 Intent genericFileManagerIntent = new Intent(Intent.ACTION_VIEW);
2095 // Open the download directory.
2096 genericFileManagerIntent.setDataAndType(Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()), DocumentsContract.Document.MIME_TYPE_DIR);
2098 // Launch as a new task so that the file manager and Privacy Browser show as separate windows in the recent tasks list.
2099 genericFileManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2102 startActivity(genericFileManagerIntent);
2103 } catch (Exception genericFileManagerException) {
2104 // Try an alternate file manager.
2106 // Create an alternate file manager intent.
2107 Intent alternateFileManagerIntent = new Intent(Intent.ACTION_VIEW);
2109 // Open the download directory.
2110 alternateFileManagerIntent.setDataAndType(Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()), "resource/folder");
2112 // Launch as a new task so that the file manager and Privacy Browser show as separate windows in the recent tasks list.
2113 alternateFileManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2115 // Open the alternate file manager.
2116 startActivity(alternateFileManagerIntent);
2117 } catch (Exception alternateFileManagerException) {
2118 // Display a snackbar.
2119 Snackbar.make(currentWebView, R.string.no_file_manager_detected, Snackbar.LENGTH_INDEFINITE).show();
2123 } else if (menuItemId == R.id.domains) { // Domains.
2124 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2125 reapplyDomainSettingsOnRestart = true;
2127 // Launch the domains activity.
2128 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2130 // Add the extra information to the intent.
2131 domainsIntent.putExtra("current_url", currentWebView.getUrl());
2132 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
2134 // Get the current certificate.
2135 SslCertificate sslCertificate = currentWebView.getCertificate();
2137 // Check to see if the SSL certificate is populated.
2138 if (sslCertificate != null) {
2139 // Extract the certificate to strings.
2140 String issuedToCName = sslCertificate.getIssuedTo().getCName();
2141 String issuedToOName = sslCertificate.getIssuedTo().getOName();
2142 String issuedToUName = sslCertificate.getIssuedTo().getUName();
2143 String issuedByCName = sslCertificate.getIssuedBy().getCName();
2144 String issuedByOName = sslCertificate.getIssuedBy().getOName();
2145 String issuedByUName = sslCertificate.getIssuedBy().getUName();
2146 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
2147 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
2149 // Add the certificate to the intent.
2150 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
2151 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
2152 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
2153 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
2154 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
2155 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
2156 domainsIntent.putExtra("ssl_start_date", startDateLong);
2157 domainsIntent.putExtra("ssl_end_date", endDateLong);
2161 startActivity(domainsIntent);
2162 } else if (menuItemId == R.id.settings) { // Settings.
2163 // Set the flag to reapply app settings on restart when returning from Settings.
2164 reapplyAppSettingsOnRestart = true;
2166 // Set the flag to reapply the domain settings on restart when returning from Settings.
2167 reapplyDomainSettingsOnRestart = true;
2169 // Launch the settings activity.
2170 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2171 startActivity(settingsIntent);
2172 } else if (menuItemId == R.id.import_export) { // Import/Export.
2173 // Create an intent to launch the import/export activity.
2174 Intent importExportIntent = new Intent(this, ImportExportActivity.class);
2177 startActivity(importExportIntent);
2178 } else if (menuItemId == R.id.logcat) { // Logcat.
2179 // Create an intent to launch the logcat activity.
2180 Intent logcatIntent = new Intent(this, LogcatActivity.class);
2183 startActivity(logcatIntent);
2184 } else if (menuItemId == R.id.guide) { // Guide.
2185 // Create an intent to launch the guide activity.
2186 Intent guideIntent = new Intent(this, GuideActivity.class);
2189 startActivity(guideIntent);
2190 } else if (menuItemId == R.id.about) { // About
2191 // Create an intent to launch the about activity.
2192 Intent aboutIntent = new Intent(this, AboutActivity.class);
2194 // Create a string array for the blocklist versions.
2195 String[] blocklistVersions = new String[]{easyList.get(0).get(0)[0], easyPrivacy.get(0).get(0)[0], fanboysAnnoyanceList.get(0).get(0)[0], fanboysSocialList.get(0).get(0)[0],
2196 ultraList.get(0).get(0)[0], ultraPrivacy.get(0).get(0)[0]};
2198 // Add the blocklist versions to the intent.
2199 aboutIntent.putExtra(AboutActivity.BLOCKLIST_VERSIONS, blocklistVersions);
2202 startActivity(aboutIntent);
2205 // Close the navigation drawer.
2206 drawerLayout.closeDrawer(GravityCompat.START);
2211 public void onPostCreate(Bundle savedInstanceState) {
2212 // Run the default commands.
2213 super.onPostCreate(savedInstanceState);
2215 // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished. This creates the navigation drawer icon.
2216 actionBarDrawerToggle.syncState();
2220 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2221 // Get the hit test result.
2222 final WebView.HitTestResult hitTestResult = currentWebView.getHitTestResult();
2224 // Define the URL strings.
2225 final String imageUrl;
2226 final String linkUrl;
2228 // Get handles for the system managers.
2229 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2231 // Remove the lint errors below that the clipboard manager might be null.
2232 assert clipboardManager != null;
2234 // Process the link according to the type.
2235 switch (hitTestResult.getType()) {
2236 // `SRC_ANCHOR_TYPE` is a link.
2237 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2238 // Get the target URL.
2239 linkUrl = hitTestResult.getExtra();
2241 // Set the target URL as the title of the `ContextMenu`.
2242 menu.setHeaderTitle(linkUrl);
2244 // Add an Open in New Tab entry.
2245 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2246 // Load the link URL in a new tab and move to it.
2247 addNewTab(linkUrl, true);
2249 // Consume the event.
2253 // Add an Open in Background entry.
2254 menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
2255 // Load the link URL in a new tab but do not move to it.
2256 addNewTab(linkUrl, false);
2258 // Consume the event.
2262 // Add an Open with App entry.
2263 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2264 openWithApp(linkUrl);
2266 // Consume the event.
2270 // Add an Open with Browser entry.
2271 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2272 openWithBrowser(linkUrl);
2274 // Consume the event.
2278 // Add a Copy URL entry.
2279 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2280 // Save the link URL in a `ClipData`.
2281 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2283 // Set the `ClipData` as the clipboard's primary clip.
2284 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2286 // Consume the event.
2290 // Add a Save URL entry.
2291 menu.add(R.string.save_url).setOnMenuItemClickListener((MenuItem item) -> {
2292 // Check the download preference.
2293 if (downloadWithExternalApp) { // Download with an external app.
2294 downloadUrlWithExternalApp(linkUrl);
2295 } else { // Handle the download inside of Privacy Browser.
2296 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2297 new PrepareSaveDialog(this, this, getSupportFragmentManager(), currentWebView.getSettings().getUserAgentString(),
2298 currentWebView.getAcceptCookies()).execute(linkUrl);
2301 // Consume the event.
2305 // Add an empty Cancel entry, which by default closes the context menu.
2306 menu.add(R.string.cancel);
2309 // `IMAGE_TYPE` is an image.
2310 case WebView.HitTestResult.IMAGE_TYPE:
2311 // Get the image URL.
2312 imageUrl = hitTestResult.getExtra();
2314 // Remove the incorrect lint warning below that the image URL might be null.
2315 assert imageUrl != null;
2317 // Set the context menu title.
2318 if (imageUrl.startsWith("data:")) { // The image data is contained in within the URL, making it exceedingly long.
2319 // Truncate the image URL before making it the title.
2320 menu.setHeaderTitle(imageUrl.substring(0, 100));
2321 } else { // The image URL does not contain the full image data.
2322 // Set the image URL as the title of the context menu.
2323 menu.setHeaderTitle(imageUrl);
2326 // Add an Open in New Tab entry.
2327 menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2328 // Load the image in a new tab.
2329 addNewTab(imageUrl, true);
2331 // Consume the event.
2335 // Add an Open with App entry.
2336 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2337 // Open the image URL with an external app.
2338 openWithApp(imageUrl);
2340 // Consume the event.
2344 // Add an Open with Browser entry.
2345 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2346 // Open the image URL with an external browser.
2347 openWithBrowser(imageUrl);
2349 // Consume the event.
2353 // Add a View Image entry.
2354 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2355 // Load the image in the current tab.
2356 loadUrl(currentWebView, imageUrl);
2358 // Consume the event.
2362 // Add a Save Image entry.
2363 menu.add(R.string.save_image).setOnMenuItemClickListener((MenuItem item) -> {
2364 // Check the download preference.
2365 if (downloadWithExternalApp) { // Download with an external app.
2366 downloadUrlWithExternalApp(imageUrl);
2367 } else { // Handle the download inside of Privacy Browser.
2368 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2369 new PrepareSaveDialog(this, this, getSupportFragmentManager(), currentWebView.getSettings().getUserAgentString(),
2370 currentWebView.getAcceptCookies()).execute(imageUrl);
2373 // Consume the event.
2377 // Add a Copy URL entry.
2378 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2379 // Save the image URL in a clip data.
2380 ClipData imageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2382 // Set the clip data as the clipboard's primary clip.
2383 clipboardManager.setPrimaryClip(imageTypeClipData);
2385 // Consume the event.
2389 // Add an empty Cancel entry, which by default closes the context menu.
2390 menu.add(R.string.cancel);
2393 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2394 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2395 // Get the image URL.
2396 imageUrl = hitTestResult.getExtra();
2398 // Instantiate a handler.
2399 Handler handler = new Handler();
2401 // Get a message from the handler.
2402 Message message = handler.obtainMessage();
2404 // Request the image details from the last touched node be returned in the message.
2405 currentWebView.requestFocusNodeHref(message);
2407 // Get the link URL from the message data.
2408 linkUrl = message.getData().getString("url");
2410 // Set the link URL as the title of the context menu.
2411 menu.setHeaderTitle(linkUrl);
2413 // Add an Open in New Tab entry.
2414 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2415 // Load the link URL in a new tab and move to it.
2416 addNewTab(linkUrl, true);
2418 // Consume the event.
2422 // Add an Open in Background entry.
2423 menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
2424 // Lod the link URL in a new tab but do not move to it.
2425 addNewTab(linkUrl, false);
2427 // Consume the event.
2431 // Add an Open Image in New Tab entry.
2432 menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2433 // Load the image in a new tab and move to it.
2434 addNewTab(imageUrl, true);
2436 // Consume the event.
2440 // Add an Open with App entry.
2441 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2442 // Open the link URL with an external app.
2443 openWithApp(linkUrl);
2445 // Consume the event.
2449 // Add an Open with Browser entry.
2450 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2451 // Open the link URL with an external browser.
2452 openWithBrowser(linkUrl);
2454 // Consume the event.
2458 // Add a View Image entry.
2459 menu.add(R.string.view_image).setOnMenuItemClickListener((MenuItem item) -> {
2460 // View the image in the current tab.
2461 loadUrl(currentWebView, imageUrl);
2463 // Consume the event.
2467 // Add a Save Image entry.
2468 menu.add(R.string.save_image).setOnMenuItemClickListener((MenuItem item) -> {
2469 // Check the download preference.
2470 if (downloadWithExternalApp) { // Download with an external app.
2471 downloadUrlWithExternalApp(imageUrl);
2472 } else { // Handle the download inside of Privacy Browser.
2473 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2474 new PrepareSaveDialog(this, this, getSupportFragmentManager(), currentWebView.getSettings().getUserAgentString(),
2475 currentWebView.getAcceptCookies()).execute(imageUrl);
2478 // Consume the event.
2482 // Add a Copy URL entry.
2483 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2484 // Save the link URL in a clip data.
2485 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2487 // Set the clip data as the clipboard's primary clip.
2488 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2490 // Consume the event.
2494 // Add a Save URL entry.
2495 menu.add(R.string.save_url).setOnMenuItemClickListener((MenuItem item) -> {
2496 // Check the download preference.
2497 if (downloadWithExternalApp) { // Download with an external app.
2498 downloadUrlWithExternalApp(linkUrl);
2499 } else { // Handle the download inside of Privacy Browser.
2500 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2501 new PrepareSaveDialog(this, this, getSupportFragmentManager(), currentWebView.getSettings().getUserAgentString(),
2502 currentWebView.getAcceptCookies()).execute(linkUrl);
2505 // Consume the event.
2509 // Add an empty Cancel entry, which by default closes the context menu.
2510 menu.add(R.string.cancel);
2513 case WebView.HitTestResult.EMAIL_TYPE:
2514 // Get the target URL.
2515 linkUrl = hitTestResult.getExtra();
2517 // Set the target URL as the title of the `ContextMenu`.
2518 menu.setHeaderTitle(linkUrl);
2520 // Add a Write Email entry.
2521 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2522 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2523 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2525 // Parse the url and set it as the data for the `Intent`.
2526 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2528 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2529 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2533 startActivity(emailIntent);
2534 } catch (ActivityNotFoundException exception) {
2535 // Display a snackbar.
2536 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
2539 // Consume the event.
2543 // Add a Copy Email Address entry.
2544 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2545 // Save the email address in a `ClipData`.
2546 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2548 // Set the `ClipData` as the clipboard's primary clip.
2549 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2551 // Consume the event.
2555 // Add an empty Cancel entry, which by default closes the context menu.
2556 menu.add(R.string.cancel);
2562 public void onCreateBookmark(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2563 // Get a handle for the bookmarks list view.
2564 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2567 Dialog dialog = dialogFragment.getDialog();
2569 // Remove the incorrect lint warning below that the dialog might be null.
2570 assert dialog != null;
2572 // Get the views from the dialog fragment.
2573 EditText createBookmarkNameEditText = dialog.findViewById(R.id.create_bookmark_name_edittext);
2574 EditText createBookmarkUrlEditText = dialog.findViewById(R.id.create_bookmark_url_edittext);
2576 // Extract the strings from the edit texts.
2577 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2578 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2580 // Create a favorite icon byte array output stream.
2581 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2583 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2584 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2586 // Convert the favorite icon byte array stream to a byte array.
2587 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2589 // Display the new bookmark below the current items in the (0 indexed) list.
2590 int newBookmarkDisplayOrder = bookmarksListView.getCount();
2592 // Create the bookmark.
2593 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2595 // Update the bookmarks cursor with the current contents of this folder.
2596 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2598 // Update the list view.
2599 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2601 // Scroll to the new bookmark.
2602 bookmarksListView.setSelection(newBookmarkDisplayOrder);
2606 public void onCreateBookmarkFolder(DialogFragment dialogFragment, @NonNull Bitmap favoriteIconBitmap) {
2607 // Get a handle for the bookmarks list view.
2608 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2611 Dialog dialog = dialogFragment.getDialog();
2613 // Remove the incorrect lint warning below that the dialog might be null.
2614 assert dialog != null;
2616 // Get handles for the views in the dialog fragment.
2617 EditText folderNameEditText = dialog.findViewById(R.id.folder_name_edittext);
2618 RadioButton defaultIconRadioButton = dialog.findViewById(R.id.default_icon_radiobutton);
2619 ImageView defaultIconImageView = dialog.findViewById(R.id.default_icon_imageview);
2621 // Get new folder name string.
2622 String folderNameString = folderNameEditText.getText().toString();
2624 // Create a folder icon bitmap.
2625 Bitmap folderIconBitmap;
2627 // Set the folder icon bitmap according to the dialog.
2628 if (defaultIconRadioButton.isChecked()) { // Use the default folder icon.
2629 // Get the default folder icon drawable.
2630 Drawable folderIconDrawable = defaultIconImageView.getDrawable();
2632 // Convert the folder icon drawable to a bitmap drawable.
2633 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2635 // Convert the folder icon bitmap drawable to a bitmap.
2636 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2637 } else { // Use the WebView favorite icon.
2638 // Copy the favorite icon bitmap to the folder icon bitmap.
2639 folderIconBitmap = favoriteIconBitmap;
2642 // Create a folder icon byte array output stream.
2643 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2645 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2646 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2648 // Convert the folder icon byte array stream to a byte array.
2649 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2651 // Move all the bookmarks down one in the display order.
2652 for (int i = 0; i < bookmarksListView.getCount(); i++) {
2653 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2654 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2657 // Create the folder, which will be placed at the top of the `ListView`.
2658 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2660 // Update the bookmarks cursor with the current contents of this folder.
2661 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2663 // Update the `ListView`.
2664 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2666 // Scroll to the new folder.
2667 bookmarksListView.setSelection(0);
2671 public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId, @NonNull Bitmap favoriteIconBitmap) {
2672 // Remove the incorrect lint warning below that the dialog fragment might be null.
2673 assert dialogFragment != null;
2676 Dialog dialog = dialogFragment.getDialog();
2678 // Remove the incorrect lint warning below that the dialog might be null.
2679 assert dialog != null;
2681 // Get handles for the views from the dialog.
2682 RadioButton currentFolderIconRadioButton = dialog.findViewById(R.id.current_icon_radiobutton);
2683 RadioButton defaultFolderIconRadioButton = dialog.findViewById(R.id.default_icon_radiobutton);
2684 ImageView defaultFolderIconImageView = dialog.findViewById(R.id.default_icon_imageview);
2685 EditText editFolderNameEditText = dialog.findViewById(R.id.folder_name_edittext);
2687 // Get the new folder name.
2688 String newFolderNameString = editFolderNameEditText.getText().toString();
2690 // Check if the favorite icon has changed.
2691 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
2692 // Update the name in the database.
2693 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2694 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
2695 // Create the new folder icon Bitmap.
2696 Bitmap folderIconBitmap;
2698 // Populate the new folder icon bitmap.
2699 if (defaultFolderIconRadioButton.isChecked()) {
2700 // Get the default folder icon drawable.
2701 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2703 // Convert the folder icon drawable to a bitmap drawable.
2704 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2706 // Convert the folder icon bitmap drawable to a bitmap.
2707 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2708 } else { // Use the `WebView` favorite icon.
2709 // Copy the favorite icon bitmap to the folder icon bitmap.
2710 folderIconBitmap = favoriteIconBitmap;
2713 // Create a folder icon byte array output stream.
2714 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2716 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2717 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2719 // Convert the folder icon byte array stream to a byte array.
2720 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2722 // Update the folder icon in the database.
2723 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, newFolderIconByteArray);
2724 } else { // The folder icon and the name have changed.
2725 // Get the new folder icon bitmap.
2726 Bitmap folderIconBitmap;
2727 if (defaultFolderIconRadioButton.isChecked()) {
2728 // Get the default folder icon drawable.
2729 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2731 // Convert the folder icon drawable to a bitmap drawable.
2732 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2734 // Convert the folder icon bitmap drawable to a bitmap.
2735 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2736 } else { // Use the `WebView` favorite icon.
2737 // Copy the favorite icon bitmap to the folder icon bitmap.
2738 folderIconBitmap = favoriteIconBitmap;
2741 // Create a folder icon byte array output stream.
2742 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2744 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2745 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2747 // Convert the folder icon byte array stream to a byte array.
2748 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2750 // Update the folder name and icon in the database.
2751 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, newFolderIconByteArray);
2754 // Update the bookmarks cursor with the current contents of this folder.
2755 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2757 // Update the `ListView`.
2758 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2761 // Override `onBackPressed()` to handle the navigation drawer and and the WebViews.
2763 public void onBackPressed() {
2764 // Check the different options for processing `back`.
2765 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
2766 // Close the navigation drawer.
2767 drawerLayout.closeDrawer(GravityCompat.START);
2768 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
2769 // close the bookmarks drawer.
2770 drawerLayout.closeDrawer(GravityCompat.END);
2771 } else if (displayingFullScreenVideo) { // A full screen video is shown.
2772 // Exit the full screen video.
2773 exitFullScreenVideo();
2774 } else if (currentWebView.canGoBack()) { // There is at least one item in the current WebView history.
2775 // Get the current web back forward list.
2776 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
2778 // Get the previous entry URL.
2779 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
2781 // Apply the domain settings.
2782 applyDomainSettings(currentWebView, previousUrl, false, false, false);
2785 currentWebView.goBack();
2786 } else if (tabLayout.getTabCount() > 1) { // There are at least two tabs.
2787 // Close the current tab.
2789 } else { // There isn't anything to do in Privacy Browser.
2790 // Close Privacy Browser. `finishAndRemoveTask()` also removes Privacy Browser from the recent app list.
2791 finishAndRemoveTask();
2793 // Manually kill Privacy Browser. Otherwise, it is glitchy when restarted.
2798 // Process the results of a file browse.
2800 public void onActivityResult(int requestCode, int resultCode, Intent returnedIntent) {
2801 // Run the default commands.
2802 super.onActivityResult(requestCode, resultCode, returnedIntent);
2804 // Run the commands that correlate to the specified request code.
2805 switch (requestCode) {
2806 case BROWSE_FILE_UPLOAD_REQUEST_CODE:
2807 // Pass the file to the WebView.
2808 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, returnedIntent));
2811 case BROWSE_OPEN_REQUEST_CODE:
2812 // Don't do anything if the user pressed back from the file picker.
2813 if (resultCode == Activity.RESULT_OK) {
2814 // Get a handle for the open dialog fragment.
2815 DialogFragment openDialogFragment = (DialogFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.open));
2817 // Only update the file name if the dialog still exists.
2818 if (openDialogFragment != null) {
2819 // Get a handle for the open dialog.
2820 Dialog openDialog = openDialogFragment.getDialog();
2822 // Remove the incorrect lint warning below that the dialog might be null.
2823 assert openDialog != null;
2825 // Get a handle for the file name edit text.
2826 EditText fileNameEditText = openDialog.findViewById(R.id.file_name_edittext);
2828 // Get the file name URI from the intent.
2829 Uri fileNameUri = returnedIntent.getData();
2831 // Get the file name string from the URI.
2832 String fileNameString = fileNameUri.toString();
2834 // Set the file name text.
2835 fileNameEditText.setText(fileNameString);
2837 // Move the cursor to the end of the file name edit text.
2838 fileNameEditText.setSelection(fileNameString.length());
2845 private void loadUrlFromTextBox() {
2846 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
2847 String unformattedUrlString = urlEditText.getText().toString().trim();
2849 // Initialize the formatted URL string.
2852 // Check to see if the unformatted URL string is a valid URL. Otherwise, convert it into a search.
2853 if (unformattedUrlString.startsWith("content://")) { // This is a Content URL.
2854 // Load the entire content URL.
2855 url = unformattedUrlString;
2856 } else if (Patterns.WEB_URL.matcher(unformattedUrlString).matches() || unformattedUrlString.startsWith("http://") || unformattedUrlString.startsWith("https://") ||
2857 unformattedUrlString.startsWith("file://")) { // This is a standard URL.
2858 // Add `https://` at the beginning if there is no protocol. Otherwise the app will segfault.
2859 if (!unformattedUrlString.startsWith("http") && !unformattedUrlString.startsWith("file://")) {
2860 unformattedUrlString = "https://" + unformattedUrlString;
2863 // Initialize the unformatted URL.
2864 URL unformattedUrl = null;
2866 // Convert the unformatted URL string to a URL, then to a URI, and then back to a string, which sanitizes the input and adds in any missing components.
2868 unformattedUrl = new URL(unformattedUrlString);
2869 } catch (MalformedURLException e) {
2870 e.printStackTrace();
2873 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2874 String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2875 String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2876 String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2877 String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2878 String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2881 Uri.Builder uri = new Uri.Builder();
2882 uri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2884 // Decode the URI as a UTF-8 string in.
2886 url = URLDecoder.decode(uri.build().toString(), "UTF-8");
2887 } catch (UnsupportedEncodingException exception) {
2888 // Do nothing. The formatted URL string will remain blank.
2890 } else if (!unformattedUrlString.isEmpty()){ // This is not a URL, but rather a search string.
2891 // Create an encoded URL String.
2892 String encodedUrlString;
2894 // Sanitize the search input.
2896 encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2897 } catch (UnsupportedEncodingException exception) {
2898 encodedUrlString = "";
2901 // Add the base search URL.
2902 url = searchURL + encodedUrlString;
2905 // Clear the focus from the URL edit text. Otherwise, proximate typing in the box will retain the colorized formatting instead of being reset during refocus.
2906 urlEditText.clearFocus();
2909 loadUrl(currentWebView, url);
2912 private void loadUrl(NestedScrollWebView nestedScrollWebView, String url) {
2913 // Sanitize the URL.
2914 url = sanitizeUrl(url);
2916 // Apply the domain settings and load the URL.
2917 applyDomainSettings(nestedScrollWebView, url, true, false, true);
2920 public void findPreviousOnPage(View view) {
2921 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
2922 currentWebView.findNext(false);
2925 public void findNextOnPage(View view) {
2926 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2927 currentWebView.findNext(true);
2930 public void closeFindOnPage(View view) {
2931 // Get a handle for the views.
2932 Toolbar toolbar = findViewById(R.id.toolbar);
2933 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
2934 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
2936 // Delete the contents of `find_on_page_edittext`.
2937 findOnPageEditText.setText(null);
2939 // Clear the highlighted phrases if the WebView is not null.
2940 if (currentWebView != null) {
2941 currentWebView.clearMatches();
2944 // Hide the find on page linear layout.
2945 findOnPageLinearLayout.setVisibility(View.GONE);
2947 // Show the toolbar.
2948 toolbar.setVisibility(View.VISIBLE);
2950 // Get a handle for the input method manager.
2951 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
2953 // Remove the lint warning below that the input method manager might be null.
2954 assert inputMethodManager != null;
2956 // Hide the keyboard.
2957 inputMethodManager.hideSoftInputFromWindow(toolbar.getWindowToken(), 0);
2961 public void onApplyNewFontSize(DialogFragment dialogFragment) {
2962 // Remove the incorrect lint warning below that the dialog fragment might be null.
2963 assert dialogFragment != null;
2966 Dialog dialog = dialogFragment.getDialog();
2968 // Remove the incorrect lint warning below tha the dialog might be null.
2969 assert dialog != null;
2971 // Get a handle for the font size edit text.
2972 EditText fontSizeEditText = dialog.findViewById(R.id.font_size_edittext);
2974 // Initialize the new font size variable with the current font size.
2975 int newFontSize = currentWebView.getSettings().getTextZoom();
2977 // Get the font size from the edit text.
2979 newFontSize = Integer.parseInt(fontSizeEditText.getText().toString());
2980 } catch (Exception exception) {
2981 // If the edit text does not contain a valid font size do nothing.
2984 // Apply the new font size.
2985 currentWebView.getSettings().setTextZoom(newFontSize);
2989 public void onOpen(DialogFragment dialogFragment) {
2991 Dialog dialog = dialogFragment.getDialog();
2993 // Remove the incorrect lint warning below that the dialog might be null.
2994 assert dialog != null;
2996 // Get handles for the views.
2997 EditText fileNameEditText = dialog.findViewById(R.id.file_name_edittext);
2998 CheckBox mhtCheckBox = dialog.findViewById(R.id.mht_checkbox);
3000 // Get the file path string.
3001 String openFilePath = fileNameEditText.getText().toString();
3003 // Apply the domain settings. This resets the favorite icon and removes any domain settings.
3004 applyDomainSettings(currentWebView, openFilePath, true, false, false);
3006 // Open the file according to the type.
3007 if (mhtCheckBox.isChecked()) { // Force opening of an MHT file.
3009 // Get the MHT file input stream.
3010 InputStream mhtFileInputStream = getContentResolver().openInputStream(Uri.parse(openFilePath));
3012 // Create a temporary MHT file.
3013 File temporaryMhtFile = File.createTempFile("temporary_mht_file", ".mht", getCacheDir());
3015 // Get a file output stream for the temporary MHT file.
3016 FileOutputStream temporaryMhtFileOutputStream = new FileOutputStream(temporaryMhtFile);
3018 // Create a transfer byte array.
3019 byte[] transferByteArray = new byte[1024];
3021 // Create an integer to track the number of bytes read.
3024 // Copy the temporary MHT file input stream to the MHT output stream.
3025 while ((bytesRead = mhtFileInputStream.read(transferByteArray)) > 0) {
3026 temporaryMhtFileOutputStream.write(transferByteArray, 0, bytesRead);
3029 // Flush the temporary MHT file output stream.
3030 temporaryMhtFileOutputStream.flush();
3032 // Close the streams.
3033 temporaryMhtFileOutputStream.close();
3034 mhtFileInputStream.close();
3036 // Load the temporary MHT file.
3037 currentWebView.loadUrl(temporaryMhtFile.toString());
3038 } catch (Exception exception) {
3039 // Display a snackbar.
3040 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
3042 } else { // Let the WebView handle opening of the file.
3044 currentWebView.loadUrl(openFilePath);
3048 private void downloadUrlWithExternalApp(String url) {
3049 // Create a download intent. Not specifying the action type will display the maximum number of options.
3050 Intent downloadIntent = new Intent();
3052 // Set the URI and the mime type.
3053 downloadIntent.setDataAndType(Uri.parse(url), "text/html");
3055 // Flag the intent to open in a new task.
3056 downloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3058 // Show the chooser.
3059 startActivity(Intent.createChooser(downloadIntent, getString(R.string.download_with_external_app)));
3062 public void onSaveUrl(@NonNull String originalUrlString, @NonNull String fileNameString, @NonNull DialogFragment dialogFragment) {
3063 // Store the URL. This will be used in the save URL activity result launcher.
3064 if (originalUrlString.startsWith("data:")) {
3065 // Save the original URL.
3066 saveUrlString = originalUrlString;
3069 Dialog dialog = dialogFragment.getDialog();
3071 // Remove the incorrect lint warning below that the dialog might be null.
3072 assert dialog != null;
3074 // Get a handle for the dialog URL edit text.
3075 EditText dialogUrlEditText = dialog.findViewById(R.id.url_edittext);
3077 // Get the URL from the edit text, which may have been modified.
3078 saveUrlString = dialogUrlEditText.getText().toString();
3081 // Open the file picker.
3082 saveUrlActivityResultLauncher.launch(fileNameString);
3085 // Remove the warning that `OnTouchListener()` needs to override `performClick()`, as the only purpose of setting the `OnTouchListener()` is to make it do nothing.
3086 @SuppressLint("ClickableViewAccessibility")
3087 private void initializeApp() {
3088 // Get a handle for the input method.
3089 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
3091 // Remove the lint warning below that the input method manager might be null.
3092 assert inputMethodManager != null;
3094 // Initialize the gray foreground color spans for highlighting the URLs.
3095 initialGrayColorSpan = new ForegroundColorSpan(getColor(R.color.gray_500));
3096 finalGrayColorSpan = new ForegroundColorSpan(getColor(R.color.gray_500));
3098 // Get the current theme status.
3099 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
3101 // Set the red color span according to the theme.
3102 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
3103 redColorSpan = new ForegroundColorSpan(getColor(R.color.red_a700));
3105 redColorSpan = new ForegroundColorSpan(getColor(R.color.red_900));
3108 // Remove the formatting from the URL edit text when the user is editing the text.
3109 urlEditText.setOnFocusChangeListener((View v, boolean hasFocus) -> {
3110 if (hasFocus) { // The user is editing the URL text box.
3111 // Remove the highlighting.
3112 urlEditText.getText().removeSpan(redColorSpan);
3113 urlEditText.getText().removeSpan(initialGrayColorSpan);
3114 urlEditText.getText().removeSpan(finalGrayColorSpan);
3115 } else { // The user has stopped editing the URL text box.
3116 // Move to the beginning of the string.
3117 urlEditText.setSelection(0);
3119 // Reapply the highlighting.
3124 // Set the go button on the keyboard to load the URL in `urlTextBox`.
3125 urlEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
3126 // If the event is a key-down event on the `enter` button, load the URL.
3127 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
3128 // Load the URL into the mainWebView and consume the event.
3129 loadUrlFromTextBox();
3131 // If the enter key was pressed, consume the event.
3134 // If any other key was pressed, do not consume the event.
3139 // Create an Orbot status broadcast receiver.
3140 orbotStatusBroadcastReceiver = new BroadcastReceiver() {
3142 public void onReceive(Context context, Intent intent) {
3143 // Store the content of the status message in `orbotStatus`.
3144 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
3146 // If Privacy Browser is waiting on the proxy, load the website now that Orbot is connected.
3147 if ((orbotStatus != null) && orbotStatus.equals(ProxyHelper.ORBOT_STATUS_ON) && waitingForProxy) {
3148 // Reset the waiting for proxy status.
3149 waitingForProxy = false;
3151 // Get a list of the current fragments.
3152 List<Fragment> fragmentList = getSupportFragmentManager().getFragments();
3154 // Check each fragment to see if it is a waiting for proxy dialog. Sometimes more than one is displayed.
3155 for (int i = 0; i < fragmentList.size(); i++) {
3156 // Get the fragment tag.
3157 String fragmentTag = fragmentList.get(i).getTag();
3159 // Check to see if it is the waiting for proxy dialog.
3160 if ((fragmentTag!= null) && fragmentTag.equals(getString(R.string.waiting_for_proxy_dialog))) {
3161 // Dismiss the waiting for proxy dialog.
3162 ((DialogFragment) fragmentList.get(i)).dismiss();
3166 // Reload existing URLs and load any URLs that are waiting for the proxy.
3167 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3168 // Get the WebView tab fragment.
3169 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3171 // Get the fragment view.
3172 View fragmentView = webViewTabFragment.getView();
3174 // Only process the WebViews if they exist.
3175 if (fragmentView != null) {
3176 // Get the nested scroll WebView from the tab fragment.
3177 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3179 // Get the waiting for proxy URL string.
3180 String waitingForProxyUrlString = nestedScrollWebView.getWaitingForProxyUrlString();
3182 // Load the pending URL if it exists.
3183 if (!waitingForProxyUrlString.isEmpty()) { // A URL is waiting to be loaded.
3185 loadUrl(nestedScrollWebView, waitingForProxyUrlString);
3187 // Reset the waiting for proxy URL string.
3188 nestedScrollWebView.setWaitingForProxyUrlString("");
3189 } else { // No URL is waiting to be loaded.
3190 // Reload the existing URL.
3191 nestedScrollWebView.reload();
3199 // Register the Orbot status broadcast receiver on `this` context.
3200 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
3202 // Get handles for views that need to be modified.
3203 LinearLayout bookmarksHeaderLinearLayout = findViewById(R.id.bookmarks_header_linearlayout);
3204 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
3205 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
3206 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
3207 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
3208 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
3210 // Update the web view pager every time a tab is modified.
3211 webViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
3213 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
3218 public void onPageSelected(int position) {
3219 // Close the find on page bar if it is open.
3220 closeFindOnPage(null);
3222 // Set the current WebView.
3223 setCurrentWebView(position);
3225 // Select the corresponding tab if it does not match the currently selected page. This will happen if the page was scrolled by creating a new tab.
3226 if (tabLayout.getSelectedTabPosition() != position) {
3227 // Wait until the new tab has been created.
3228 tabLayout.post(() -> {
3229 // Get a handle for the tab.
3230 TabLayout.Tab tab = tabLayout.getTabAt(position);
3232 // Assert that the tab is not null.
3242 public void onPageScrollStateChanged(int state) {
3247 // Display the View SSL Certificate dialog when the currently selected tab is reselected.
3248 tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
3250 public void onTabSelected(TabLayout.Tab tab) {
3251 // Select the same page in the view pager.
3252 webViewPager.setCurrentItem(tab.getPosition());
3256 public void onTabUnselected(TabLayout.Tab tab) {
3261 public void onTabReselected(TabLayout.Tab tab) {
3262 // Instantiate the View SSL Certificate dialog.
3263 DialogFragment viewSslCertificateDialogFragment = ViewSslCertificateDialog.displayDialog(currentWebView.getWebViewFragmentId(), currentWebView.getFavoriteOrDefaultIcon());
3265 // Display the View SSL Certificate dialog.
3266 viewSslCertificateDialogFragment.show(getSupportFragmentManager(), getString(R.string.view_ssl_certificate));
3270 // Set a touch listener on the bookmarks header linear layout so that touches don't pass through to the button underneath.
3271 bookmarksHeaderLinearLayout.setOnTouchListener((view, motionEvent) -> {
3272 // Consume the touch.
3276 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
3277 launchBookmarksActivityFab.setOnClickListener(v -> {
3278 // Get a copy of the favorite icon bitmap.
3279 Bitmap favoriteIconBitmap = currentWebView.getFavoriteOrDefaultIcon();
3281 // Create a favorite icon byte array output stream.
3282 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3284 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
3285 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
3287 // Convert the favorite icon byte array stream to a byte array.
3288 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
3290 // Create an intent to launch the bookmarks activity.
3291 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
3293 // Add the extra information to the intent.
3294 bookmarksIntent.putExtra("current_url", currentWebView.getUrl());
3295 bookmarksIntent.putExtra("current_title", currentWebView.getTitle());
3296 bookmarksIntent.putExtra("current_folder", currentBookmarksFolder);
3297 bookmarksIntent.putExtra("favorite_icon_byte_array", favoriteIconByteArray);
3300 startActivity(bookmarksIntent);
3303 // Set the create new bookmark folder FAB to display an alert dialog.
3304 createBookmarkFolderFab.setOnClickListener(v -> {
3305 // Create a create bookmark folder dialog.
3306 DialogFragment createBookmarkFolderDialog = CreateBookmarkFolderDialog.createBookmarkFolder(currentWebView.getFavoriteOrDefaultIcon());
3308 // Show the create bookmark folder dialog.
3309 createBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.create_folder));
3312 // Set the create new bookmark FAB to display an alert dialog.
3313 createBookmarkFab.setOnClickListener(view -> {
3314 // Instantiate the create bookmark dialog.
3315 DialogFragment createBookmarkDialog = CreateBookmarkDialog.createBookmark(currentWebView.getUrl(), currentWebView.getTitle(), currentWebView.getFavoriteOrDefaultIcon());
3317 // Display the create bookmark dialog.
3318 createBookmarkDialog.show(getSupportFragmentManager(), getString(R.string.create_bookmark));
3321 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
3322 findOnPageEditText.addTextChangedListener(new TextWatcher() {
3324 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
3329 public void onTextChanged(CharSequence s, int start, int before, int count) {
3334 public void afterTextChanged(Editable s) {
3335 // Search for the text in the WebView if it is not null. Sometimes on resume after a period of non-use the WebView will be null.
3336 if (currentWebView != null) {
3337 currentWebView.findAllAsync(findOnPageEditText.getText().toString());
3342 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
3343 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
3344 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
3345 // Hide the soft keyboard.
3346 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
3348 // Consume the event.
3350 } else { // A different key was pressed.
3351 // Do not consume the event.
3356 // Implement swipe to refresh.
3357 swipeRefreshLayout.setOnRefreshListener(() -> {
3358 // Reload the website.
3359 currentWebView.reload();
3362 // Store the default progress view offsets for use later in `initializeWebView()`.
3363 defaultProgressViewStartOffset = swipeRefreshLayout.getProgressViewStartOffset();
3364 defaultProgressViewEndOffset = swipeRefreshLayout.getProgressViewEndOffset();
3366 // Set the refresh color scheme according to the theme.
3367 swipeRefreshLayout.setColorSchemeResources(R.color.blue_text);
3369 // Initialize a color background typed value.
3370 TypedValue colorBackgroundTypedValue = new TypedValue();
3372 // Get the color background from the theme.
3373 getTheme().resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true);
3375 // Get the color background int from the typed value.
3376 int colorBackgroundInt = colorBackgroundTypedValue.data;
3378 // Set the swipe refresh background color.
3379 swipeRefreshLayout.setProgressBackgroundColorSchemeColor(colorBackgroundInt);
3381 // The drawer titles identify the drawer layouts in accessibility mode.
3382 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
3383 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
3385 // Initialize the bookmarks database helper.
3386 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this);
3388 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
3389 currentBookmarksFolder = "";
3391 // Load the home folder, which is `""` in the database.
3392 loadBookmarksFolder();
3394 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
3395 // Convert the id from long to int to match the format of the bookmarks database.
3396 int databaseId = (int) id;
3398 // Get the bookmark cursor for this ID.
3399 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseId);
3401 // Move the bookmark cursor to the first row.
3402 bookmarkCursor.moveToFirst();
3404 // Act upon the bookmark according to the type.
3405 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
3406 // Store the new folder name in `currentBookmarksFolder`.
3407 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME));
3409 // Load the new folder.
3410 loadBookmarksFolder();
3411 } else { // The selected bookmark is not a folder.
3412 // Load the bookmark URL.
3413 loadUrl(currentWebView, bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_URL)));
3415 // Close the bookmarks drawer.
3416 drawerLayout.closeDrawer(GravityCompat.END);
3419 // Close the `Cursor`.
3420 bookmarkCursor.close();
3423 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
3424 // Convert the database ID from `long` to `int`.
3425 int databaseId = (int) id;
3427 // Find out if the selected bookmark is a folder.
3428 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
3430 // Check to see if the bookmark is a folder.
3431 if (isFolder) { // The bookmark is a folder.
3432 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
3433 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME));
3435 // Instantiate the edit folder bookmark dialog.
3436 DialogFragment editBookmarkFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId, currentWebView.getFavoriteOrDefaultIcon());
3438 // Show the edit folder bookmark dialog.
3439 editBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.edit_folder));
3440 } else { // The bookmark is not a folder.
3441 // Get the bookmark cursor for this ID.
3442 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseId);
3444 // Move the bookmark cursor to the first row.
3445 bookmarkCursor.moveToFirst();
3447 // Load the bookmark in a new tab but do not switch to the tab or close the drawer.
3448 addNewTab(bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_URL)), false);
3450 // Display a snackbar.
3451 Snackbar.make(drawerLayout, R.string.bookmark_opened_in_background, Snackbar.LENGTH_SHORT).show();
3454 // Consume the event.
3458 // The drawer listener is used to update the navigation menu.
3459 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
3461 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
3465 public void onDrawerOpened(@NonNull View drawerView) {
3469 public void onDrawerClosed(@NonNull View drawerView) {
3470 // Reset the drawer icon when the drawer is closed. Otherwise, it is an arrow if the drawer is open when the app is restarted.
3471 actionBarDrawerToggle.syncState();
3475 public void onDrawerStateChanged(int newState) {
3476 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // A drawer is opening or closing.
3477 // Update the navigation menu items if the WebView is not null.
3478 if (currentWebView != null) {
3479 navigationBackMenuItem.setEnabled(currentWebView.canGoBack());
3480 navigationForwardMenuItem.setEnabled(currentWebView.canGoForward());
3481 navigationHistoryMenuItem.setEnabled((currentWebView.canGoBack() || currentWebView.canGoForward()));
3482 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
3484 // Hide the keyboard (if displayed).
3485 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
3488 // 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.
3489 urlEditText.clearFocus();
3491 // 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.
3492 if (currentWebView != null) {
3493 // Clearing the focus from the WebView removes any text selection markers and context menus, which otherwise draw above the open drawers.
3494 currentWebView.clearFocus();
3500 // 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).
3501 customHeaders.put("X-Requested-With", "");
3503 // Inflate a bare WebView to get the default user agent. It is not used to render content on the screen.
3504 @SuppressLint("InflateParams") View webViewLayout = getLayoutInflater().inflate(R.layout.bare_webview, null, false);
3506 // Get a handle for the WebView.
3507 WebView bareWebView = webViewLayout.findViewById(R.id.bare_webview);
3509 // Store the default user agent.
3510 webViewDefaultUserAgent = bareWebView.getSettings().getUserAgentString();
3512 // Destroy the bare WebView.
3513 bareWebView.destroy();
3516 private void applyAppSettings() {
3517 // Get a handle for the shared preferences.
3518 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3520 // Store the values from the shared preferences in variables.
3521 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3522 sanitizeGoogleAnalytics = sharedPreferences.getBoolean("google_analytics", true);
3523 sanitizeFacebookClickIds = sharedPreferences.getBoolean("facebook_click_ids", true);
3524 sanitizeTwitterAmpRedirects = sharedPreferences.getBoolean("twitter_amp_redirects", true);
3525 proxyMode = sharedPreferences.getString("proxy", getString(R.string.proxy_default_value));
3526 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3527 downloadWithExternalApp = sharedPreferences.getBoolean(getString(R.string.download_with_external_app_key), false);
3528 hideAppBar = sharedPreferences.getBoolean("hide_app_bar", true);
3529 scrollAppBar = sharedPreferences.getBoolean(getString(R.string.scroll_app_bar_key), true);
3531 // Apply the saved proxy mode if the app has been restarted.
3532 if (savedProxyMode != null) {
3533 // Apply the saved proxy mode.
3534 proxyMode = savedProxyMode;
3536 // Reset the saved proxy mode.
3537 savedProxyMode = null;
3540 // Get the search string.
3541 String searchString = sharedPreferences.getString("search", getString(R.string.search_default_value));
3543 // Set the search string.
3544 if (searchString.equals("Custom URL")) { // A custom search string is used.
3545 searchURL = sharedPreferences.getString("search_custom_url", getString(R.string.search_custom_url_default_value));
3546 } else { // A custom search string is not used.
3547 searchURL = searchString;
3553 // Adjust the layout and scrolling parameters according to the position of the app bar.
3554 if (bottomAppBar) { // The app bar is on the bottom.
3556 if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) { // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
3557 // Reset the WebView padding to fill the available space.
3558 swipeRefreshLayout.setPadding(0, 0, 0, 0);
3559 } else { // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
3560 // Move the WebView above the app bar layout.
3561 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight);
3563 // Show the app bar if it is scrolled off the screen.
3564 if (appBarLayout.getTranslationY() != 0) {
3565 // Animate the bottom app bar onto the screen.
3566 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0);
3569 objectAnimator.start();
3572 } else { // The app bar is on the top.
3573 // Get the current layout parameters. Using coordinator layout parameters allows the `setBehavior()` command and using app bar layout parameters allows the `setScrollFlags()` command.
3574 CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
3575 AppBarLayout.LayoutParams toolbarLayoutParams = (AppBarLayout.LayoutParams) toolbar.getLayoutParams();
3576 AppBarLayout.LayoutParams findOnPageLayoutParams = (AppBarLayout.LayoutParams) findOnPageLinearLayout.getLayoutParams();
3577 AppBarLayout.LayoutParams tabsLayoutParams = (AppBarLayout.LayoutParams) tabsLinearLayout.getLayoutParams();
3579 // Add the scrolling behavior to the layout parameters.
3581 // Enable scrolling of the app bar.
3582 swipeRefreshLayoutParams.setBehavior(new AppBarLayout.ScrollingViewBehavior());
3583 toolbarLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3584 findOnPageLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3585 tabsLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3587 // Disable scrolling of the app bar.
3588 swipeRefreshLayoutParams.setBehavior(null);
3589 toolbarLayoutParams.setScrollFlags(0);
3590 findOnPageLayoutParams.setScrollFlags(0);
3591 tabsLayoutParams.setScrollFlags(0);
3593 // Expand the app bar if it is currently collapsed.
3594 appBarLayout.setExpanded(true);
3597 // Set the app bar scrolling for each WebView.
3598 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3599 // Get the WebView tab fragment.
3600 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3602 // Get the fragment view.
3603 View fragmentView = webViewTabFragment.getView();
3605 // Only modify the WebViews if they exist.
3606 if (fragmentView != null) {
3607 // Get the nested scroll WebView from the tab fragment.
3608 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3610 // Set the app bar scrolling.
3611 nestedScrollWebView.setNestedScrollingEnabled(scrollAppBar);
3616 // Update the full screen browsing mode settings.
3617 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
3618 // Update the visibility of the app bar, which might have changed in the settings.
3620 // Hide the tab linear layout.
3621 tabsLinearLayout.setVisibility(View.GONE);
3623 // Hide the action bar.
3626 // Show the tab linear layout.
3627 tabsLinearLayout.setVisibility(View.VISIBLE);
3629 // Show the action bar.
3633 /* Hide the system bars.
3634 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3635 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
3636 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3637 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3639 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
3640 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3641 } else { // Privacy Browser is not in full screen browsing mode.
3642 // 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.
3643 inFullScreenBrowsingMode = false;
3645 // Show the tab linear layout.
3646 tabsLinearLayout.setVisibility(View.VISIBLE);
3648 // Show the action bar.
3651 // Remove the `SYSTEM_UI` flags from the root frame layout.
3652 rootFrameLayout.setSystemUiVisibility(0);
3657 public void navigateHistory(@NonNull String url, int steps) {
3658 // Apply the domain settings.
3659 applyDomainSettings(currentWebView, url, false, false, false);
3661 // Load the history entry.
3662 currentWebView.goBackOrForward(steps);
3666 public void pinnedErrorGoBack() {
3667 // Get the current web back forward list.
3668 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
3670 // Get the previous entry URL.
3671 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
3673 // Apply the domain settings.
3674 applyDomainSettings(currentWebView, previousUrl, false, false, false);
3677 currentWebView.goBack();
3680 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
3681 @SuppressLint("SetJavaScriptEnabled")
3682 private void applyDomainSettings(NestedScrollWebView nestedScrollWebView, String url, boolean resetTab, boolean reloadWebsite, boolean loadUrl) {
3683 // Store the current URL.
3684 nestedScrollWebView.setCurrentUrl(url);
3686 // Parse the URL into a URI.
3687 Uri uri = Uri.parse(url);
3689 // Extract the domain from `uri`.
3690 String newHostName = uri.getHost();
3692 // Strings don't like to be null.
3693 if (newHostName == null) {
3697 // 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.
3698 if (!nestedScrollWebView.getCurrentDomainName().equals(newHostName) || newHostName.equals("")) {
3699 // Set the new host name as the current domain name.
3700 nestedScrollWebView.setCurrentDomainName(newHostName);
3702 // Reset the ignoring of pinned domain information.
3703 nestedScrollWebView.setIgnorePinnedDomainInformation(false);
3705 // Clear any pinned SSL certificate or IP addresses.
3706 nestedScrollWebView.clearPinnedSslCertificate();
3707 nestedScrollWebView.setPinnedIpAddresses("");
3709 // Reset the favorite icon if specified.
3711 // Initialize the favorite icon.
3712 nestedScrollWebView.initializeFavoriteIcon();
3714 // Get the current page position.
3715 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
3717 // Get the corresponding tab.
3718 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
3720 // Update the tab if it isn't null, which sometimes happens when restarting from the background.
3722 // Get the tab custom view.
3723 View tabCustomView = tab.getCustomView();
3725 // Remove the warning below that the tab custom view might be null.
3726 assert tabCustomView != null;
3728 // Get the tab views.
3729 ImageView tabFavoriteIconImageView = tabCustomView.findViewById(R.id.favorite_icon_imageview);
3730 TextView tabTitleTextView = tabCustomView.findViewById(R.id.title_textview);
3732 // Set the default favorite icon as the favorite icon for this tab.
3733 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(nestedScrollWebView.getFavoriteOrDefaultIcon(), 64, 64, true));
3735 // Set the loading title text.
3736 tabTitleTextView.setText(R.string.loading);
3740 // Initialize the database handler.
3741 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this);
3743 // Get a full cursor from `domainsDatabaseHelper`.
3744 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3746 // Initialize `domainSettingsSet`.
3747 Set<String> domainSettingsSet = new HashSet<>();
3749 // Get the domain name column index.
3750 int domainNameColumnIndex = domainNameCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.DOMAIN_NAME);
3752 // Populate the domain settings set.
3753 for (int i = 0; i < domainNameCursor.getCount(); i++) {
3754 // Move the domains cursor to the current row.
3755 domainNameCursor.moveToPosition(i);
3757 // Store the domain name in the domain settings set.
3758 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3761 // Close the domain name cursor.
3762 domainNameCursor.close();
3764 // Initialize the domain name in database variable.
3765 String domainNameInDatabase = null;
3767 // Check the hostname against the domain settings set.
3768 if (domainSettingsSet.contains(newHostName)) { // The hostname is contained in the domain settings set.
3769 // Record the domain name in the database.
3770 domainNameInDatabase = newHostName;
3772 // Set the domain settings applied tracker to true.
3773 nestedScrollWebView.setDomainSettingsApplied(true);
3774 } else { // The hostname is not contained in the domain settings set.
3775 // Set the domain settings applied tracker to false.
3776 nestedScrollWebView.setDomainSettingsApplied(false);
3779 // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3780 while (!nestedScrollWebView.getDomainSettingsApplied() && newHostName.contains(".")) { // Stop checking if domain settings are already applied or there are no more `.` in the hostname.
3781 if (domainSettingsSet.contains("*." + newHostName)) { // Check the host name prepended by `*.`.
3782 // Set the domain settings applied tracker to true.
3783 nestedScrollWebView.setDomainSettingsApplied(true);
3785 // Store the applied domain names as it appears in the database.
3786 domainNameInDatabase = "*." + newHostName;
3789 // Strip out the lowest subdomain of of the host name.
3790 newHostName = newHostName.substring(newHostName.indexOf(".") + 1);
3794 // Get a handle for the shared preferences.
3795 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3797 // Store the general preference information.
3798 String defaultFontSizeString = sharedPreferences.getString("font_size", getString(R.string.font_size_default_value));
3799 String defaultUserAgentName = sharedPreferences.getString("user_agent", getString(R.string.user_agent_default_value));
3800 boolean defaultSwipeToRefresh = sharedPreferences.getBoolean("swipe_to_refresh", true);
3801 String webViewTheme = sharedPreferences.getString("webview_theme", getString(R.string.webview_theme_default_value));
3802 boolean wideViewport = sharedPreferences.getBoolean("wide_viewport", true);
3803 boolean displayWebpageImages = sharedPreferences.getBoolean("display_webpage_images", true);
3805 // Get the WebView theme entry values string array.
3806 String[] webViewThemeEntryValuesStringArray = getResources().getStringArray(R.array.webview_theme_entry_values);
3808 // Get a handle for the cookie manager.
3809 CookieManager cookieManager = CookieManager.getInstance();
3811 // Initialize the user agent array adapter and string array.
3812 ArrayAdapter<CharSequence> userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item);
3813 String[] userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
3815 if (nestedScrollWebView.getDomainSettingsApplied()) { // The url has custom domain settings.
3816 // Remove the incorrect lint warning below that the domain name in database might be null.
3817 assert domainNameInDatabase != null;
3819 // Get a cursor for the current host.
3820 Cursor currentDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3822 // Move to the first position.
3823 currentDomainSettingsCursor.moveToFirst();
3825 // Get the settings from the cursor.
3826 nestedScrollWebView.setDomainSettingsDatabaseId(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ID)));
3827 nestedScrollWebView.getSettings().setJavaScriptEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3828 nestedScrollWebView.setAcceptCookies(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.COOKIES)) == 1);
3829 nestedScrollWebView.getSettings().setDomStorageEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3830 // Form data can be removed once the minimum API >= 26.
3831 boolean saveFormData = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3832 nestedScrollWebView.setEasyListEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3833 nestedScrollWebView.setEasyPrivacyEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3834 nestedScrollWebView.setFanboysAnnoyanceListEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3835 nestedScrollWebView.setFanboysSocialBlockingListEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(
3836 DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3837 nestedScrollWebView.setUltraListEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ULTRALIST)) == 1);
3838 nestedScrollWebView.setUltraPrivacyEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_ULTRAPRIVACY)) == 1);
3839 nestedScrollWebView.setBlockAllThirdPartyRequests(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
3840 String userAgentName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.USER_AGENT));
3841 int fontSize = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.FONT_SIZE));
3842 int swipeToRefreshInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
3843 int webViewThemeInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.WEBVIEW_THEME));
3844 int wideViewportInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.WIDE_VIEWPORT));
3845 int displayWebpageImagesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.DISPLAY_IMAGES));
3846 boolean pinnedSslCertificate = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3847 String pinnedSslIssuedToCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3848 String pinnedSslIssuedToOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3849 String pinnedSslIssuedToUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3850 String pinnedSslIssuedByCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3851 String pinnedSslIssuedByOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3852 String pinnedSslIssuedByUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3853 Date pinnedSslStartDate = new Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_START_DATE)));
3854 Date pinnedSslEndDate = new Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_END_DATE)));
3855 boolean pinnedIpAddresses = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.PINNED_IP_ADDRESSES)) == 1);
3856 String pinnedHostIpAddresses = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.IP_ADDRESSES));
3858 // Close the current host domain settings cursor.
3859 currentDomainSettingsCursor.close();
3861 // If there is a pinned SSL certificate, store it in the WebView.
3862 if (pinnedSslCertificate) {
3863 nestedScrollWebView.setPinnedSslCertificate(pinnedSslIssuedToCName, pinnedSslIssuedToOName, pinnedSslIssuedToUName, pinnedSslIssuedByCName, pinnedSslIssuedByOName, pinnedSslIssuedByUName,
3864 pinnedSslStartDate, pinnedSslEndDate);
3867 // If there is a pinned IP address, store it in the WebView.
3868 if (pinnedIpAddresses) {
3869 nestedScrollWebView.setPinnedIpAddresses(pinnedHostIpAddresses);
3872 // Apply the cookie domain settings.
3873 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptCookies());
3875 // Apply the form data setting if the API < 26.
3876 if (Build.VERSION.SDK_INT < 26) {
3877 nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
3880 // Apply the font size.
3881 try { // Try the specified font size to see if it is valid.
3882 if (fontSize == 0) { // Apply the default font size.
3883 // Try to set the font size from the value in the app settings.
3884 nestedScrollWebView.getSettings().setTextZoom(Integer.parseInt(defaultFontSizeString));
3885 } else { // Apply the font size from domain settings.
3886 nestedScrollWebView.getSettings().setTextZoom(fontSize);
3888 } catch (Exception exception) { // The specified font size is invalid
3889 // Set the font size to be 100%
3890 nestedScrollWebView.getSettings().setTextZoom(100);
3893 // Set the user agent.
3894 if (userAgentName.equals(getString(R.string.system_default_user_agent))) { // Use the system default user agent.
3895 // Get the array position of the default user agent name.
3896 int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3898 // Set the user agent according to the system default.
3899 switch (defaultUserAgentArrayPosition) {
3900 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
3901 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3902 nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
3905 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3906 // Set the user agent to `""`, which uses the default value.
3907 nestedScrollWebView.getSettings().setUserAgentString("");
3910 case SETTINGS_CUSTOM_USER_AGENT:
3911 // Set the default custom user agent.
3912 nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
3916 // Get the user agent string from the user agent data array
3917 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
3919 } else { // Set the user agent according to the stored name.
3920 // Get the array position of the user agent name.
3921 int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
3923 switch (userAgentArrayPosition) {
3924 case UNRECOGNIZED_USER_AGENT: // The user agent name contains a custom user agent.
3925 nestedScrollWebView.getSettings().setUserAgentString(userAgentName);
3928 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3929 // Set the user agent to `""`, which uses the default value.
3930 nestedScrollWebView.getSettings().setUserAgentString("");
3934 // Get the user agent string from the user agent data array.
3935 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3939 // Set swipe to refresh.
3940 switch (swipeToRefreshInt) {
3941 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
3942 // Store the swipe to refresh status in the nested scroll WebView.
3943 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
3945 // Update the swipe refresh layout.
3946 if (defaultSwipeToRefresh) { // Swipe to refresh is enabled.
3947 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
3948 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
3949 } else { // Swipe to refresh is disabled.
3950 // Disable the swipe refresh layout.
3951 swipeRefreshLayout.setEnabled(false);
3955 case DomainsDatabaseHelper.ENABLED:
3956 // Store the swipe to refresh status in the nested scroll WebView.
3957 nestedScrollWebView.setSwipeToRefresh(true);
3959 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
3960 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
3963 case DomainsDatabaseHelper.DISABLED:
3964 // Store the swipe to refresh status in the nested scroll WebView.
3965 nestedScrollWebView.setSwipeToRefresh(false);
3967 // Disable swipe to refresh.
3968 swipeRefreshLayout.setEnabled(false);
3971 // Check to see if WebView themes are supported.
3972 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
3973 // Set the WebView theme.
3974 switch (webViewThemeInt) {
3975 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
3976 // Set the WebView theme. A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
3977 if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) { // The light theme is selected.
3978 // Turn off the WebView dark mode.
3979 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
3980 } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) { // The dark theme is selected.
3981 // Turn on the WebView dark mode.
3982 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
3983 } else { // The system default theme is selected.
3984 // Get the current system theme status.
3985 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
3987 // Set the WebView theme according to the current system theme status.
3988 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) { // The system is in day mode.
3989 // Turn off the WebView dark mode.
3990 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
3991 } else { // The system is in night mode.
3992 // Turn on the WebView dark mode.
3993 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
3998 case DomainsDatabaseHelper.LIGHT_THEME:
3999 // Turn off the WebView dark mode.
4000 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4003 case DomainsDatabaseHelper.DARK_THEME:
4004 // Turn on the WebView dark mode.
4005 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4010 // Set the viewport.
4011 switch (wideViewportInt) {
4012 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4013 nestedScrollWebView.getSettings().setUseWideViewPort(wideViewport);
4016 case DomainsDatabaseHelper.ENABLED:
4017 nestedScrollWebView.getSettings().setUseWideViewPort(true);
4020 case DomainsDatabaseHelper.DISABLED:
4021 nestedScrollWebView.getSettings().setUseWideViewPort(false);
4025 // Set the loading of webpage images.
4026 switch (displayWebpageImagesInt) {
4027 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4028 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
4031 case DomainsDatabaseHelper.ENABLED:
4032 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(true);
4035 case DomainsDatabaseHelper.DISABLED:
4036 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(false);
4040 // Set a background on the URL relative layout to indicate that custom domain settings are being used.
4041 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.domain_settings_url_background, null));
4042 } else { // The new URL does not have custom domain settings. Load the defaults.
4043 // Store the values from the shared preferences.
4044 nestedScrollWebView.getSettings().setJavaScriptEnabled(sharedPreferences.getBoolean("javascript", false));
4045 nestedScrollWebView.setAcceptCookies(sharedPreferences.getBoolean(getString(R.string.cookies_key), false));
4046 nestedScrollWebView.getSettings().setDomStorageEnabled(sharedPreferences.getBoolean("dom_storage", false));
4047 boolean saveFormData = sharedPreferences.getBoolean("save_form_data", false); // Form data can be removed once the minimum API >= 26.
4048 nestedScrollWebView.setEasyListEnabled(sharedPreferences.getBoolean("easylist", true));
4049 nestedScrollWebView.setEasyPrivacyEnabled(sharedPreferences.getBoolean("easyprivacy", true));
4050 nestedScrollWebView.setFanboysAnnoyanceListEnabled(sharedPreferences.getBoolean("fanboys_annoyance_list", true));
4051 nestedScrollWebView.setFanboysSocialBlockingListEnabled(sharedPreferences.getBoolean("fanboys_social_blocking_list", true));
4052 nestedScrollWebView.setUltraListEnabled(sharedPreferences.getBoolean("ultralist", true));
4053 nestedScrollWebView.setUltraPrivacyEnabled(sharedPreferences.getBoolean("ultraprivacy", true));
4054 nestedScrollWebView.setBlockAllThirdPartyRequests(sharedPreferences.getBoolean("block_all_third_party_requests", false));
4056 // Apply the default cookie setting.
4057 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptCookies());
4059 // Apply the default font size setting.
4061 // Try to set the font size from the value in the app settings.
4062 nestedScrollWebView.getSettings().setTextZoom(Integer.parseInt(defaultFontSizeString));
4063 } catch (Exception exception) {
4064 // If the app settings value is invalid, set the font size to 100%.
4065 nestedScrollWebView.getSettings().setTextZoom(100);
4068 // Apply the form data setting if the API < 26.
4069 if (Build.VERSION.SDK_INT < 26) {
4070 nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
4073 // Store the swipe to refresh status in the nested scroll WebView.
4074 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
4076 // Update the swipe refresh layout.
4077 if (defaultSwipeToRefresh) { // Swipe to refresh is enabled.
4078 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
4079 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
4080 } else { // Swipe to refresh is disabled.
4081 // Disable the swipe refresh layout.
4082 swipeRefreshLayout.setEnabled(false);
4085 // Reset the pinned variables.
4086 nestedScrollWebView.setDomainSettingsDatabaseId(-1);
4088 // Get the array position of the user agent name.
4089 int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
4091 // Set the user agent.
4092 switch (userAgentArrayPosition) {
4093 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
4094 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
4095 nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
4098 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4099 // Set the user agent to `""`, which uses the default value.
4100 nestedScrollWebView.getSettings().setUserAgentString("");
4103 case SETTINGS_CUSTOM_USER_AGENT:
4104 // Set the default custom user agent.
4105 nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
4109 // Get the user agent string from the user agent data array
4110 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4113 // Apply the WebView theme if supported by the installed WebView.
4114 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
4115 // Set the WebView theme. A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
4116 if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) { // The light theme is selected.
4117 // Turn off the WebView dark mode.
4118 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4119 } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) { // The dark theme is selected.
4120 // Turn on the WebView dark mode.
4121 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4122 } else { // The system default theme is selected.
4123 // Get the current system theme status.
4124 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4126 // Set the WebView theme according to the current system theme status.
4127 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) { // The system is in day mode.
4128 // Turn off the WebView dark mode.
4129 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4130 } else { // The system is in night mode.
4131 // Turn on the WebView dark mode.
4132 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4137 // Set the viewport.
4138 nestedScrollWebView.getSettings().setUseWideViewPort(wideViewport);
4140 // Set the loading of webpage images.
4141 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
4143 // Set a transparent background on the URL relative layout.
4144 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.color.transparent, null));
4147 // Close the domains database helper.
4148 domainsDatabaseHelper.close();
4150 // Update the privacy icons.
4151 updatePrivacyIcons(true);
4154 // Reload the website if returning from the Domains activity.
4155 if (reloadWebsite) {
4156 nestedScrollWebView.reload();
4159 // 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.
4161 nestedScrollWebView.loadUrl(url, customHeaders);
4165 private void applyProxy(boolean reloadWebViews) {
4166 // Set the proxy according to the mode.
4167 proxyHelper.setProxy(getApplicationContext(), appBarLayout, proxyMode);
4169 // Reset the waiting for proxy tracker.
4170 waitingForProxy = false;
4172 // Get the current theme status.
4173 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4175 // Update the user interface and reload the WebViews if requested.
4176 switch (proxyMode) {
4177 case ProxyHelper.NONE:
4178 // Initialize a color background typed value.
4179 TypedValue colorBackgroundTypedValue = new TypedValue();
4181 // Get the color background from the theme.
4182 getTheme().resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true);
4184 // Get the color background int from the typed value.
4185 int colorBackgroundInt = colorBackgroundTypedValue.data;
4187 // Set the default app bar layout background.
4188 appBarLayout.setBackgroundColor(colorBackgroundInt);
4191 case ProxyHelper.TOR:
4192 // Set the app bar background to indicate proxying through Orbot is enabled.
4193 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4194 appBarLayout.setBackgroundResource(R.color.blue_50);
4196 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4199 // Check to see if Orbot is installed.
4201 // Get the package manager.
4202 PackageManager packageManager = getPackageManager();
4204 // 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.
4205 packageManager.getPackageInfo("org.torproject.android", 0);
4207 // Check to see if the proxy is ready.
4208 if (!orbotStatus.equals(ProxyHelper.ORBOT_STATUS_ON)) { // Orbot is not ready.
4209 // Set the waiting for proxy status.
4210 waitingForProxy = true;
4212 // Show the waiting for proxy dialog if it isn't already displayed.
4213 if (getSupportFragmentManager().findFragmentByTag(getString(R.string.waiting_for_proxy_dialog)) == null) {
4214 // Get a handle for the waiting for proxy alert dialog.
4215 DialogFragment waitingForProxyDialogFragment = new WaitingForProxyDialog();
4217 // Try to show the dialog. Sometimes the window is not yet active if returning from Settings.
4219 // Show the waiting for proxy alert dialog.
4220 waitingForProxyDialogFragment.show(getSupportFragmentManager(), getString(R.string.waiting_for_proxy_dialog));
4221 } catch (Exception waitingForTorException) {
4222 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
4223 pendingDialogsArrayList.add(new PendingDialog(waitingForProxyDialogFragment, getString(R.string.waiting_for_proxy_dialog)));
4227 } catch (PackageManager.NameNotFoundException exception) { // Orbot is not installed.
4228 // Show the Orbot not installed dialog if it is not already displayed.
4229 if (getSupportFragmentManager().findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
4230 // Get a handle for the Orbot not installed alert dialog.
4231 DialogFragment orbotNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode);
4233 // Try to show the dialog. Sometimes the window is not yet active if returning from Settings.
4235 // Display the Orbot not installed alert dialog.
4236 orbotNotInstalledDialogFragment.show(getSupportFragmentManager(), getString(R.string.proxy_not_installed_dialog));
4237 } catch (Exception orbotNotInstalledException) {
4238 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
4239 pendingDialogsArrayList.add(new PendingDialog(orbotNotInstalledDialogFragment, getString(R.string.proxy_not_installed_dialog)));
4245 case ProxyHelper.I2P:
4246 // Set the app bar background to indicate proxying through Orbot is enabled.
4247 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4248 appBarLayout.setBackgroundResource(R.color.blue_50);
4250 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4253 // Check to see if I2P is installed.
4255 // Get the package manager.
4256 PackageManager packageManager = getPackageManager();
4258 // 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.
4259 packageManager.getPackageInfo("net.i2p.android.router", 0);
4260 } catch (PackageManager.NameNotFoundException exception) { // I2P is not installed.
4261 // Sow the I2P not installed dialog if it is not already displayed.
4262 if (getSupportFragmentManager().findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
4263 // Get a handle for the waiting for proxy alert dialog.
4264 DialogFragment i2pNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode);
4266 // Try to show the dialog. Sometimes the window is not yet active if returning from Settings.
4268 // Display the I2P not installed alert dialog.
4269 i2pNotInstalledDialogFragment.show(getSupportFragmentManager(), getString(R.string.proxy_not_installed_dialog));
4270 } catch (Exception i2pNotInstalledException) {
4271 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
4272 pendingDialogsArrayList.add(new PendingDialog(i2pNotInstalledDialogFragment, getString(R.string.proxy_not_installed_dialog)));
4278 case ProxyHelper.CUSTOM:
4279 // Set the app bar background to indicate proxying through Orbot is enabled.
4280 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4281 appBarLayout.setBackgroundResource(R.color.blue_50);
4283 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4288 // Reload the WebViews if requested and not waiting for the proxy.
4289 if (reloadWebViews && !waitingForProxy) {
4290 // Reload the WebViews.
4291 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4292 // Get the WebView tab fragment.
4293 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4295 // Get the fragment view.
4296 View fragmentView = webViewTabFragment.getView();
4298 // Only reload the WebViews if they exist.
4299 if (fragmentView != null) {
4300 // Get the nested scroll WebView from the tab fragment.
4301 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4303 // Reload the WebView.
4304 nestedScrollWebView.reload();
4310 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
4311 // Only update the privacy icons if the options menu and the current WebView have already been populated.
4312 if ((optionsMenu != null) && (currentWebView != null)) {
4313 // Update the privacy icon.
4314 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is enabled.
4315 optionsPrivacyMenuItem.setIcon(R.drawable.javascript_enabled);
4316 } else if (currentWebView.getAcceptCookies()) { // JavaScript is disabled but cookies are enabled.
4317 optionsPrivacyMenuItem.setIcon(R.drawable.warning);
4318 } else { // All the dangerous features are disabled.
4319 optionsPrivacyMenuItem.setIcon(R.drawable.privacy_mode);
4322 // Update the cookies icon.
4323 if (currentWebView.getAcceptCookies()) {
4324 optionsCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
4326 optionsCookiesMenuItem.setIcon(R.drawable.cookies_disabled);
4329 // Update the refresh icon.
4330 if (optionsRefreshMenuItem.getTitle() == getString(R.string.refresh)) { // The refresh icon is displayed.
4331 // Set the icon. Once the minimum API is >= 26, the blue and black icons can be combined with a tint list.
4332 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled);
4333 } else { // The stop icon is displayed.
4334 // Set the icon. Once the minimum API is >= 26, the blue and black icons can be combined with a tint list.
4335 optionsRefreshMenuItem.setIcon(R.drawable.close_blue);
4338 // `invalidateOptionsMenu()` calls `onPrepareOptionsMenu()` and redraws the icons in the app bar.
4339 if (runInvalidateOptionsMenu) {
4340 invalidateOptionsMenu();
4345 private void highlightUrlText() {
4346 // Only highlight the URL text if the box is not currently selected.
4347 if (!urlEditText.hasFocus()) {
4348 // Get the URL string.
4349 String urlString = urlEditText.getText().toString();
4351 // Highlight the URL according to the protocol.
4352 if (urlString.startsWith("file://") || urlString.startsWith("content://")) { // This is a file or content URL.
4353 // De-emphasize everything before the file name.
4354 urlEditText.getText().setSpan(initialGrayColorSpan, 0, urlString.lastIndexOf("/") + 1,Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4355 } else { // This is a web URL.
4356 // Get the index of the `/` immediately after the domain name.
4357 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
4359 // Create a base URL string.
4362 // Get the base URL.
4363 if (endOfDomainName > 0) { // There is at least one character after the base URL.
4364 // Get the base URL.
4365 baseUrl = urlString.substring(0, endOfDomainName);
4366 } else { // There are no characters after the base URL.
4367 // Set the base URL to be the entire URL string.
4368 baseUrl = urlString;
4371 // Get the index of the last `.` in the domain.
4372 int lastDotIndex = baseUrl.lastIndexOf(".");
4374 // Get the index of the penultimate `.` in the domain.
4375 int penultimateDotIndex = baseUrl.lastIndexOf(".", lastDotIndex - 1);
4377 // Markup the beginning of the URL.
4378 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
4379 urlEditText.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4381 // De-emphasize subdomains.
4382 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
4383 urlEditText.getText().setSpan(initialGrayColorSpan, 7, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4385 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
4386 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
4387 // De-emphasize the protocol and the additional subdomains.
4388 urlEditText.getText().setSpan(initialGrayColorSpan, 0, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4389 } else { // There is only one subdomain in the domain name.
4390 // De-emphasize only the protocol.
4391 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4395 // De-emphasize the text after the domain name.
4396 if (endOfDomainName > 0) {
4397 urlEditText.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4403 private void loadBookmarksFolder() {
4404 // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
4405 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
4407 // Populate the bookmarks cursor adapter.
4408 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
4410 public View newView(Context context, Cursor cursor, ViewGroup parent) {
4411 // Inflate the individual item layout.
4412 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
4416 public void bindView(View view, Context context, Cursor cursor) {
4417 // Get handles for the views.
4418 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
4419 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
4421 // Get the favorite icon byte array from the cursor.
4422 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.FAVORITE_ICON));
4424 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
4425 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
4427 // Display the bitmap in `bookmarkFavoriteIcon`.
4428 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
4430 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
4431 String bookmarkNameString = cursor.getString(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME));
4432 bookmarkNameTextView.setText(bookmarkNameString);
4434 // Make the font bold for folders.
4435 if (cursor.getInt(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
4436 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
4437 } else { // Reset the font to default for normal bookmarks.
4438 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
4443 // Get a handle for the bookmarks list view.
4444 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
4446 // Populate the list view with the adapter.
4447 bookmarksListView.setAdapter(bookmarksCursorAdapter);
4449 // Get a handle for the bookmarks title text view.
4450 TextView bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
4452 // Set the bookmarks drawer title.
4453 if (currentBookmarksFolder.isEmpty()) {
4454 bookmarksTitleTextView.setText(R.string.bookmarks);
4456 bookmarksTitleTextView.setText(currentBookmarksFolder);
4460 private void openWithApp(String url) {
4461 // Create an open with app intent with `ACTION_VIEW`.
4462 Intent openWithAppIntent = new Intent(Intent.ACTION_VIEW);
4464 // Set the URI but not the MIME type. This should open all available apps.
4465 openWithAppIntent.setData(Uri.parse(url));
4467 // Flag the intent to open in a new task.
4468 openWithAppIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4472 // Show the chooser.
4473 startActivity(openWithAppIntent);
4474 } catch (ActivityNotFoundException exception) { // There are no apps available to open the URL.
4475 // Show a snackbar with the error.
4476 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
4480 private void openWithBrowser(String url) {
4481 // Create an open with browser intent with `ACTION_VIEW`.
4482 Intent openWithBrowserIntent = new Intent(Intent.ACTION_VIEW);
4484 // Set the URI and the MIME type. `"text/html"` should load browser options.
4485 openWithBrowserIntent.setDataAndType(Uri.parse(url), "text/html");
4487 // Flag the intent to open in a new task.
4488 openWithBrowserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4492 // Show the chooser.
4493 startActivity(openWithBrowserIntent);
4494 } catch (ActivityNotFoundException exception) { // There are no browsers available to open the URL.
4495 // Show a snackbar with the error.
4496 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
4500 private String sanitizeUrl(String url) {
4501 // Sanitize Google Analytics.
4502 if (sanitizeGoogleAnalytics) {
4504 if (url.contains("?utm_")) {
4505 url = url.substring(0, url.indexOf("?utm_"));
4509 if (url.contains("&utm_")) {
4510 url = url.substring(0, url.indexOf("&utm_"));
4514 // Sanitize Facebook Click IDs.
4515 if (sanitizeFacebookClickIds) {
4516 // Remove `?fbclid=`.
4517 if (url.contains("?fbclid=")) {
4518 url = url.substring(0, url.indexOf("?fbclid="));
4521 // Remove `&fbclid=`.
4522 if (url.contains("&fbclid=")) {
4523 url = url.substring(0, url.indexOf("&fbclid="));
4526 // Remove `?fbadid=`.
4527 if (url.contains("?fbadid=")) {
4528 url = url.substring(0, url.indexOf("?fbadid="));
4531 // Remove `&fbadid=`.
4532 if (url.contains("&fbadid=")) {
4533 url = url.substring(0, url.indexOf("&fbadid="));
4537 // Sanitize Twitter AMP redirects.
4538 if (sanitizeTwitterAmpRedirects) {
4540 if (url.contains("?amp=1")) {
4541 url = url.substring(0, url.indexOf("?amp=1"));
4545 // Return the sanitized URL.
4549 public void finishedPopulatingBlocklists(ArrayList<ArrayList<List<String[]>>> combinedBlocklists) {
4550 // Store the blocklists.
4551 easyList = combinedBlocklists.get(0);
4552 easyPrivacy = combinedBlocklists.get(1);
4553 fanboysAnnoyanceList = combinedBlocklists.get(2);
4554 fanboysSocialList = combinedBlocklists.get(3);
4555 ultraList = combinedBlocklists.get(4);
4556 ultraPrivacy = combinedBlocklists.get(5);
4558 // Check to see if the activity has been restarted with a saved state.
4559 if ((savedStateArrayList == null) || (savedStateArrayList.size() == 0)) { // The activity has not been restarted or it was restarted on start to force the night theme.
4560 // Add the first tab.
4561 addNewTab("", true);
4562 } else { // The activity has been restarted.
4563 // Restore each tab. Once the minimum API >= 24, a `forEach()` command can be used.
4564 for (int i = 0; i < savedStateArrayList.size(); i++) {
4566 tabLayout.addTab(tabLayout.newTab());
4569 TabLayout.Tab newTab = tabLayout.getTabAt(i);
4571 // Remove the lint warning below that the current tab might be null.
4572 assert newTab != null;
4574 // Set a custom view on the new tab.
4575 newTab.setCustomView(R.layout.tab_custom_view);
4577 // Add the new page.
4578 webViewPagerAdapter.restorePage(savedStateArrayList.get(i), savedNestedScrollWebViewStateArrayList.get(i));
4581 // Reset the saved state variables.
4582 savedStateArrayList = null;
4583 savedNestedScrollWebViewStateArrayList = null;
4585 // Restore the selected tab position.
4586 if (savedTabPosition == 0) { // The first tab is selected.
4587 // Set the first page as the current WebView.
4588 setCurrentWebView(0);
4589 } else { // the first tab is not selected.
4590 // Move to the selected tab.
4591 webViewPager.setCurrentItem(savedTabPosition);
4594 // Get the intent that started the app.
4595 Intent intent = getIntent();
4597 // Reset the intent. This prevents a duplicate tab from being created on restart.
4598 setIntent(new Intent());
4600 // Get the information from the intent.
4601 String intentAction = intent.getAction();
4602 Uri intentUriData = intent.getData();
4603 String intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT);
4605 // Determine if this is a web search.
4606 boolean isWebSearch = ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH));
4608 // 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.
4609 if (intentUriData != null || intentStringExtra != null || isWebSearch) {
4610 // Get the shared preferences.
4611 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4613 // Create a URL string.
4616 // If the intent action is a web search, perform the search.
4617 if (isWebSearch) { // The intent is a web search.
4618 // Create an encoded URL string.
4619 String encodedUrlString;
4621 // Sanitize the search input and convert it to a search.
4623 encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
4624 } catch (UnsupportedEncodingException exception) {
4625 encodedUrlString = "";
4628 // Add the base search URL.
4629 url = searchURL + encodedUrlString;
4630 } else if (intentUriData != null) { // The intent contains a URL formatted as a URI.
4631 // Set the intent data as the URL.
4632 url = intentUriData.toString();
4633 } else { // The intent contains a string, which might be a URL.
4634 // Set the intent string as the URL.
4635 url = intentStringExtra;
4638 // Add a new tab if specified in the preferences.
4639 if (sharedPreferences.getBoolean("open_intents_in_new_tab", true)) { // Load the URL in a new tab.
4640 // Set the loading new intent flag.
4641 loadingNewIntent = true;
4644 addNewTab(url, true);
4645 } else { // Load the URL in the current tab.
4647 loadUrl(currentWebView, url);
4653 public void addTab(View view) {
4654 // Add a new tab with a blank URL.
4655 addNewTab("", true);
4658 private void addNewTab(String url, boolean moveToTab) {
4659 // Clear the focus from the URL edit text, so that it will be populated with the information from the new tab.
4660 urlEditText.clearFocus();
4662 // Get the new page number. The page numbers are 0 indexed, so the new page number will match the current count.
4663 int newTabNumber = tabLayout.getTabCount();
4666 tabLayout.addTab(tabLayout.newTab());
4669 TabLayout.Tab newTab = tabLayout.getTabAt(newTabNumber);
4671 // Remove the lint warning below that the current tab might be null.
4672 assert newTab != null;
4674 // Set a custom view on the new tab.
4675 newTab.setCustomView(R.layout.tab_custom_view);
4677 // Add the new WebView page.
4678 webViewPagerAdapter.addPage(newTabNumber, webViewPager, url, moveToTab);
4680 // Show the app bar if it is at the bottom of the screen and the new tab is taking focus.
4681 if (bottomAppBar && moveToTab && (appBarLayout.getTranslationY() != 0)) {
4682 // Animate the bottom app bar onto the screen.
4683 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0);
4686 objectAnimator.start();
4690 public void closeTab(View view) {
4691 // Run the command according to the number of tabs.
4692 if (tabLayout.getTabCount() > 1) { // There is more than one tab open.
4693 // Close the current tab.
4695 } else { // There is only one tab open.
4700 private void closeCurrentTab() {
4701 // Get the current tab number.
4702 int currentTabNumber = tabLayout.getSelectedTabPosition();
4704 // Delete the current tab.
4705 tabLayout.removeTabAt(currentTabNumber);
4707 // 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,
4708 // meaning that the current WebView must be reset. Otherwise it will happen automatically as the selected tab number changes.
4709 if (webViewPagerAdapter.deletePage(currentTabNumber, webViewPager)) {
4710 setCurrentWebView(currentTabNumber);
4714 private void exitFullScreenVideo() {
4715 // Re-enable the screen timeout.
4716 fullScreenVideoFrameLayout.setKeepScreenOn(false);
4718 // Unset the full screen video flag.
4719 displayingFullScreenVideo = false;
4721 // Remove all the views from the full screen video frame layout.
4722 fullScreenVideoFrameLayout.removeAllViews();
4724 // Hide the full screen video frame layout.
4725 fullScreenVideoFrameLayout.setVisibility(View.GONE);
4727 // Enable the sliding drawers.
4728 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
4730 // Show the coordinator layout.
4731 coordinatorLayout.setVisibility(View.VISIBLE);
4733 // Apply the appropriate full screen mode flags.
4734 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
4735 // Hide the app bar if specified.
4737 // Hide the tab linear layout.
4738 tabsLinearLayout.setVisibility(View.GONE);
4740 // Hide the action bar.
4744 /* Hide the system bars.
4745 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4746 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4747 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4748 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4750 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
4751 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
4752 } else { // Switch to normal viewing mode.
4753 // Remove the `SYSTEM_UI` flags from the root frame layout.
4754 rootFrameLayout.setSystemUiVisibility(0);
4758 private void clearAndExit() {
4759 // Get a handle for the shared preferences.
4760 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4762 // Close the bookmarks cursor and database.
4763 bookmarksCursor.close();
4764 bookmarksDatabaseHelper.close();
4766 // Get the status of the clear everything preference.
4767 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
4769 // Get a handle for the runtime.
4770 Runtime runtime = Runtime.getRuntime();
4772 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
4773 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
4774 String privateDataDirectoryString = getApplicationInfo().dataDir;
4777 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
4778 // Request the cookies be deleted.
4779 CookieManager.getInstance().removeAllCookies(null);
4781 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4783 // Two commands must be used because `Runtime.exec()` does not like `*`.
4784 Process deleteCookiesProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
4785 Process deleteCookiesJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
4787 // Wait until the processes have finished.
4788 deleteCookiesProcess.waitFor();
4789 deleteCookiesJournalProcess.waitFor();
4790 } catch (Exception exception) {
4791 // Do nothing if an error is thrown.
4795 // Clear DOM storage.
4796 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
4797 // Ask `WebStorage` to clear the DOM storage.
4798 WebStorage webStorage = WebStorage.getInstance();
4799 webStorage.deleteAllData();
4801 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4803 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4804 Process deleteLocalStorageProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
4806 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
4807 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
4808 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
4809 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
4810 Process deleteDatabaseProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
4812 // Wait until the processes have finished.
4813 deleteLocalStorageProcess.waitFor();
4814 deleteIndexProcess.waitFor();
4815 deleteQuotaManagerProcess.waitFor();
4816 deleteQuotaManagerJournalProcess.waitFor();
4817 deleteDatabaseProcess.waitFor();
4818 } catch (Exception exception) {
4819 // Do nothing if an error is thrown.
4823 // Clear form data if the API < 26.
4824 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
4825 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
4826 webViewDatabase.clearFormData();
4828 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4830 // A string array must be used because the database contains a space and `Runtime.exec` will not otherwise escape the string correctly.
4831 Process deleteWebDataProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
4832 Process deleteWebDataJournalProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
4834 // Wait until the processes have finished.
4835 deleteWebDataProcess.waitFor();
4836 deleteWebDataJournalProcess.waitFor();
4837 } catch (Exception exception) {
4838 // Do nothing if an error is thrown.
4842 // Clear the logcat.
4843 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_logcat_key), true)) {
4845 // Clear the logcat. `-c` clears the logcat. `-b all` clears all the buffers (instead of just crash, main, and system).
4846 Process process = Runtime.getRuntime().exec("logcat -b all -c");
4848 // Wait for the process to finish.
4850 } catch (IOException|InterruptedException exception) {
4856 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
4857 // Clear the cache from each WebView.
4858 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4859 // Get the WebView tab fragment.
4860 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4862 // Get the WebView fragment view.
4863 View webViewFragmentView = webViewTabFragment.getView();
4865 // Only clear the cache if the WebView exists.
4866 if (webViewFragmentView != null) {
4867 // Get the nested scroll WebView from the tab fragment.
4868 NestedScrollWebView nestedScrollWebView = webViewFragmentView.findViewById(R.id.nestedscroll_webview);
4870 // Clear the cache for this WebView.
4871 nestedScrollWebView.clearCache(true);
4875 // Manually delete the cache directories.
4877 // Delete the main cache directory.
4878 Process deleteCacheProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/cache");
4880 // Delete the secondary `Service Worker` cache directory.
4881 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4882 Process deleteServiceWorkerProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
4884 // Wait until the processes have finished.
4885 deleteCacheProcess.waitFor();
4886 deleteServiceWorkerProcess.waitFor();
4887 } catch (Exception exception) {
4888 // Do nothing if an error is thrown.
4892 // Wipe out each WebView.
4893 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4894 // Get the WebView tab fragment.
4895 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4897 // Get the WebView frame layout.
4898 FrameLayout webViewFrameLayout = (FrameLayout) webViewTabFragment.getView();
4900 // Only wipe out the WebView if it exists.
4901 if (webViewFrameLayout != null) {
4902 // Get the nested scroll WebView from the tab fragment.
4903 NestedScrollWebView nestedScrollWebView = webViewFrameLayout.findViewById(R.id.nestedscroll_webview);
4905 // Clear SSL certificate preferences for this WebView.
4906 nestedScrollWebView.clearSslPreferences();
4908 // Clear the back/forward history for this WebView.
4909 nestedScrollWebView.clearHistory();
4911 // Remove all the views from the frame layout.
4912 webViewFrameLayout.removeAllViews();
4914 // Destroy the internal state of the WebView.
4915 nestedScrollWebView.destroy();
4919 // Clear the custom headers.
4920 customHeaders.clear();
4922 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
4923 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
4924 if (clearEverything) {
4926 // Delete the folder.
4927 Process deleteAppWebviewProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
4929 // Wait until the process has finished.
4930 deleteAppWebviewProcess.waitFor();
4931 } catch (Exception exception) {
4932 // Do nothing if an error is thrown.
4936 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
4937 finishAndRemoveTask();
4939 // Remove the terminated program from RAM. The status code is `0`.
4943 public void bookmarksBack(View view) {
4944 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
4945 // close the bookmarks drawer.
4946 drawerLayout.closeDrawer(GravityCompat.END);
4947 } else { // A subfolder is displayed.
4948 // Place the former parent folder in `currentFolder`.
4949 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolderName(currentBookmarksFolder);
4951 // Load the new folder.
4952 loadBookmarksFolder();
4956 private void setCurrentWebView(int pageNumber) {
4957 // Stop the swipe to refresh indicator if it is running
4958 swipeRefreshLayout.setRefreshing(false);
4960 // Get the WebView tab fragment.
4961 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(pageNumber);
4963 // Get the fragment view.
4964 View webViewFragmentView = webViewTabFragment.getView();
4966 // Set the current WebView if the fragment view is not null.
4967 if (webViewFragmentView != null) { // The fragment has been populated.
4968 // Store the current WebView.
4969 currentWebView = webViewFragmentView.findViewById(R.id.nestedscroll_webview);
4971 // Update the status of swipe to refresh.
4972 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
4973 // Enable the swipe refresh layout if the WebView is scrolled all the way to the top. It is updated every time the scroll changes.
4974 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
4975 } else { // Swipe to refresh is disabled.
4976 // Disable the swipe refresh layout.
4977 swipeRefreshLayout.setEnabled(false);
4980 // Get a handle for the cookie manager.
4981 CookieManager cookieManager = CookieManager.getInstance();
4983 // Set the cookie status.
4984 cookieManager.setAcceptCookie(currentWebView.getAcceptCookies());
4986 // Update the privacy icons. `true` redraws the icons in the app bar.
4987 updatePrivacyIcons(true);
4989 // Get a handle for the input method manager.
4990 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
4992 // Remove the lint warning below that the input method manager might be null.
4993 assert inputMethodManager != null;
4995 // Get the current URL.
4996 String url = currentWebView.getUrl();
4998 // Update the URL edit text if not loading a new intent. Otherwise, this will be handled by `onPageStarted()` (if called) and `onPageFinished()`.
4999 if (!loadingNewIntent) { // A new intent is not being loaded.
5000 if ((url == null) || url.equals("about:blank")) { // The WebView is blank.
5001 // Display the hint in the URL edit text.
5002 urlEditText.setText("");
5004 // Request focus for the URL text box.
5005 urlEditText.requestFocus();
5007 // Display the keyboard.
5008 inputMethodManager.showSoftInput(urlEditText, 0);
5009 } else { // The WebView has a loaded URL.
5010 // Clear the focus from the URL text box.
5011 urlEditText.clearFocus();
5013 // Hide the soft keyboard.
5014 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
5016 // Display the current URL in the URL text box.
5017 urlEditText.setText(url);
5019 // Highlight the URL text.
5022 } else { // A new intent is being loaded.
5023 // Reset the loading new intent tracker.
5024 loadingNewIntent = false;
5027 // Set the background to indicate the domain settings status.
5028 if (currentWebView.getDomainSettingsApplied()) {
5029 // Set a background on the URL relative layout to indicate that custom domain settings are being used.
5030 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.domain_settings_url_background, null));
5032 // Remove any background on the URL relative layout.
5033 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.color.transparent, null));
5035 } else { // The fragment has not been populated. Try again in 100 milliseconds.
5036 // Create a handler to set the current WebView.
5037 Handler setCurrentWebViewHandler = new Handler();
5039 // Create a runnable to set the current WebView.
5040 Runnable setCurrentWebWebRunnable = () -> {
5041 // Set the current WebView.
5042 setCurrentWebView(pageNumber);
5045 // Try setting the current WebView again after 100 milliseconds.
5046 setCurrentWebViewHandler.postDelayed(setCurrentWebWebRunnable, 100);
5050 @SuppressLint("ClickableViewAccessibility")
5052 public void initializeWebView(NestedScrollWebView nestedScrollWebView, int pageNumber, ProgressBar progressBar, String url, Boolean restoringState) {
5053 // Get a handle for the shared preferences.
5054 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
5056 // Get the WebView theme.
5057 String webViewTheme = sharedPreferences.getString("webview_theme", getString(R.string.webview_theme_default_value));
5059 // Get the WebView theme entry values string array.
5060 String[] webViewThemeEntryValuesStringArray = getResources().getStringArray(R.array.webview_theme_entry_values);
5062 // Apply the WebView theme if supported by the installed WebView.
5063 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
5064 // Set the WebView theme. A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
5065 if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) { // The light theme is selected.
5066 // Turn off the WebView dark mode.
5067 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
5069 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
5070 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
5071 nestedScrollWebView.setVisibility(View.VISIBLE);
5072 } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) { // The dark theme is selected.
5073 // Turn on the WebView dark mode.
5074 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
5075 } else { // The system default theme is selected.
5076 // Get the current system theme status.
5077 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
5079 // Set the WebView theme according to the current system theme status.
5080 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) { // The system is in day mode.
5081 // Turn off the WebView dark mode.
5082 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
5084 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
5085 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
5086 nestedScrollWebView.setVisibility(View.VISIBLE);
5087 } else { // The system is in night mode.
5088 // Turn on the WebView dark mode.
5089 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
5094 // Get a handle for the activity
5095 Activity activity = this;
5097 // Get a handle for the input method manager.
5098 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
5100 // Instantiate the blocklist helper.
5101 BlocklistHelper blocklistHelper = new BlocklistHelper();
5103 // Remove the lint warning below that the input method manager might be null.
5104 assert inputMethodManager != null;
5106 // Set the app bar scrolling.
5107 nestedScrollWebView.setNestedScrollingEnabled(scrollAppBar);
5109 // Allow pinch to zoom.
5110 nestedScrollWebView.getSettings().setBuiltInZoomControls(true);
5112 // Hide zoom controls.
5113 nestedScrollWebView.getSettings().setDisplayZoomControls(false);
5115 // Don't allow mixed content (HTTP and HTTPS) on the same website.
5116 nestedScrollWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW);
5118 // Set the WebView to load in overview mode (zoomed out to the maximum width).
5119 nestedScrollWebView.getSettings().setLoadWithOverviewMode(true);
5121 // Explicitly disable geolocation.
5122 nestedScrollWebView.getSettings().setGeolocationEnabled(false);
5124 // Allow loading of file:// URLs. This is necessary for opening MHT web archives, which are copies into a temporary cache location.
5125 nestedScrollWebView.getSettings().setAllowFileAccess(true);
5127 // Create a double-tap gesture detector to toggle full-screen mode.
5128 GestureDetector doubleTapGestureDetector = new GestureDetector(getApplicationContext(), new GestureDetector.SimpleOnGestureListener() {
5129 // Override `onDoubleTap()`. All other events are handled using the default settings.
5131 public boolean onDoubleTap(MotionEvent event) {
5132 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
5133 // Toggle the full screen browsing mode tracker.
5134 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
5136 // Toggle the full screen browsing mode.
5137 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
5138 // Hide the app bar if specified.
5139 if (hideAppBar) { // The app bar is hidden.
5140 // Close the find on page bar if it is visible.
5141 closeFindOnPage(null);
5143 // Hide the tab linear layout.
5144 tabsLinearLayout.setVisibility(View.GONE);
5146 // Hide the action bar.
5149 // Set layout and scrolling parameters according to the position of the app bar.
5150 if (bottomAppBar) { // The app bar is at the bottom.
5151 // Reset the WebView padding to fill the available space.
5152 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5153 } else { // The app bar is at the top.
5154 // Check to see if the app bar is normally scrolled.
5155 if (scrollAppBar) { // The app bar is scrolled when it is displayed.
5156 // Get the swipe refresh layout parameters.
5157 CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
5159 // Remove the off-screen scrolling layout.
5160 swipeRefreshLayoutParams.setBehavior(null);
5161 } else { // The app bar is not scrolled when it is displayed.
5162 // Remove the padding from the top of the swipe refresh layout.
5163 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5165 // The swipe refresh circle must be moved above the now removed status bar location.
5166 swipeRefreshLayout.setProgressViewOffset(false, -200, defaultProgressViewEndOffset);
5169 } else { // The app bar is not hidden.
5170 // Adjust the UI for the bottom app bar.
5172 // Adjust the UI according to the scrolling of the app bar.
5174 // Reset the WebView padding to fill the available space.
5175 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5177 // Move the WebView above the app bar layout.
5178 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight);
5183 /* Hide the system bars.
5184 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5185 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5186 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5187 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5189 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5190 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5191 } else { // Switch to normal viewing mode.
5192 // Show the app bar if it was hidden.
5194 // Show the tab linear layout.
5195 tabsLinearLayout.setVisibility(View.VISIBLE);
5197 // Show the action bar.
5201 // Set layout and scrolling parameters according to the position of the app bar.
5202 if (bottomAppBar) { // The app bar is at the bottom.
5205 // Reset the WebView padding to fill the available space.
5206 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5208 // Move the WebView above the app bar layout.
5209 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight);
5211 } else { // The app bar is at the top.
5212 // Check to see if the app bar is normally scrolled.
5213 if (scrollAppBar) { // The app bar is scrolled when it is displayed.
5214 // Get the swipe refresh layout parameters.
5215 CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
5217 // Add the off-screen scrolling layout.
5218 swipeRefreshLayoutParams.setBehavior(new AppBarLayout.ScrollingViewBehavior());
5219 } else { // The app bar is not scrolled when it is displayed.
5220 // The swipe refresh layout must be manually moved below the app bar layout.
5221 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0);
5223 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5224 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight);
5228 // Remove the `SYSTEM_UI` flags from the root frame layout.
5229 rootFrameLayout.setSystemUiVisibility(0);
5232 // Consume the double-tap.
5234 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
5240 public boolean onFling(MotionEvent motionEvent1, MotionEvent motionEvent2, float velocityX, float velocityY) {
5241 // Scroll the bottom app bar if enabled.
5242 if (bottomAppBar && scrollAppBar && !objectAnimator.isRunning()) {
5243 // Calculate the Y change.
5244 float motionY = motionEvent2.getY() - motionEvent1.getY();
5246 // Scroll the app bar if the change is greater than 100 pixels.
5248 // Animate the bottom app bar onto the screen.
5249 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0);
5250 } else if (motionY < -50) {
5251 // Animate the bottom app bar off the screen.
5252 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", appBarLayout.getHeight());
5256 objectAnimator.start();
5259 // Do not consume the event.
5264 // Pass all touch events on the WebView through the double-tap gesture detector.
5265 nestedScrollWebView.setOnTouchListener((View view, MotionEvent event) -> {
5266 // Call `performClick()` on the view, which is required for accessibility.
5267 view.performClick();
5269 // Send the event to the gesture detector.
5270 return doubleTapGestureDetector.onTouchEvent(event);
5273 // Register the WebView for a context menu. This is used to see link targets and download images.
5274 registerForContextMenu(nestedScrollWebView);
5276 // Allow the downloading of files.
5277 nestedScrollWebView.setDownloadListener((String downloadUrl, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
5278 // Check the download preference.
5279 if (downloadWithExternalApp) { // Download with an external app.
5280 downloadUrlWithExternalApp(downloadUrl);
5281 } else { // Handle the download inside of Privacy Browser.
5282 // Define a formatted file size string.
5283 String formattedFileSizeString;
5285 // Process the content length if it contains data.
5286 if (contentLength > 0) { // The content length is greater than 0.
5287 // Format the content length as a string.
5288 formattedFileSizeString = NumberFormat.getInstance().format(contentLength) + " " + getString(R.string.bytes);
5289 } else { // The content length is not greater than 0.
5290 // Set the formatted file size string to be `unknown size`.
5291 formattedFileSizeString = getString(R.string.unknown_size);
5294 // Get the file name from the content disposition.
5295 String fileNameString = PrepareSaveDialog.getFileNameFromHeaders(this, contentDisposition, mimetype, downloadUrl);
5297 // Instantiate the save dialog.
5298 DialogFragment saveDialogFragment = SaveDialog.saveUrl(downloadUrl, formattedFileSizeString, fileNameString, userAgent,
5299 nestedScrollWebView.getAcceptCookies());
5301 // 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.
5303 // Show the save dialog. It must be named `save_dialog` so that the file picker can update the file name.
5304 saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
5305 } catch (Exception exception) { // The dialog could not be shown.
5306 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
5307 pendingDialogsArrayList.add(new PendingDialog(saveDialogFragment, getString(R.string.save_dialog)));
5312 // Update the find on page count.
5313 nestedScrollWebView.setFindListener(new WebView.FindListener() {
5314 // Get a handle for `findOnPageCountTextView`.
5315 final TextView findOnPageCountTextView = findViewById(R.id.find_on_page_count_textview);
5318 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
5319 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
5320 // Set `findOnPageCountTextView` to `0/0`.
5321 findOnPageCountTextView.setText(R.string.zero_of_zero);
5322 } else if (isDoneCounting) { // There are matches.
5323 // `activeMatchOrdinal` is zero-based.
5324 int activeMatch = activeMatchOrdinal + 1;
5326 // Build the match string.
5327 String matchString = activeMatch + "/" + numberOfMatches;
5329 // Set `findOnPageCountTextView`.
5330 findOnPageCountTextView.setText(matchString);
5335 // Process scroll changes.
5336 nestedScrollWebView.setOnScrollChangeListener((view, scrollX, scrollY, oldScrollX, oldScrollY) -> {
5337 // Set the swipe to refresh status.
5338 if (nestedScrollWebView.getSwipeToRefresh()) {
5339 // Only enable swipe to refresh if the WebView is scrolled to the top.
5340 swipeRefreshLayout.setEnabled(nestedScrollWebView.getScrollY() == 0);
5342 // Disable swipe to refresh.
5343 swipeRefreshLayout.setEnabled(false);
5346 // Reinforce the system UI visibility flags if in full screen browsing mode.
5347 // This hides the status and navigation bars, which are displayed if other elements are shown, like dialog boxes, the options menu, or the keyboard.
5348 if (inFullScreenBrowsingMode) {
5349 /* Hide the system bars.
5350 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5351 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5352 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5353 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5355 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5356 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5360 // Set the web chrome client.
5361 nestedScrollWebView.setWebChromeClient(new WebChromeClient() {
5362 // Update the progress bar when a page is loading.
5364 public void onProgressChanged(WebView view, int progress) {
5365 // Update the progress bar.
5366 progressBar.setProgress(progress);
5368 // Set the visibility of the progress bar.
5369 if (progress < 100) {
5370 // Show the progress bar.
5371 progressBar.setVisibility(View.VISIBLE);
5373 // Hide the progress bar.
5374 progressBar.setVisibility(View.GONE);
5376 //Stop the swipe to refresh indicator if it is running
5377 swipeRefreshLayout.setRefreshing(false);
5379 // 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.
5380 nestedScrollWebView.setVisibility(View.VISIBLE);
5384 // Set the favorite icon when it changes.
5386 public void onReceivedIcon(WebView view, Bitmap icon) {
5387 // Only update the favorite icon if the website has finished loading.
5388 if (progressBar.getVisibility() == View.GONE) {
5389 // Store the new favorite icon.
5390 nestedScrollWebView.setFavoriteOrDefaultIcon(icon);
5392 // Get the current page position.
5393 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5395 // Get the current tab.
5396 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
5398 // Check to see if the tab has been populated.
5400 // Get the custom view from the tab.
5401 View tabView = tab.getCustomView();
5403 // Check to see if the custom tab view has been populated.
5404 if (tabView != null) {
5405 // Get the favorite icon image view from the tab.
5406 ImageView tabFavoriteIconImageView = tabView.findViewById(R.id.favorite_icon_imageview);
5408 // Display the favorite icon in the tab.
5409 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
5415 // Save a copy of the title when it changes.
5417 public void onReceivedTitle(WebView view, String title) {
5418 // Get the current page position.
5419 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5421 // Get the current tab.
5422 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
5424 // Only populate the title text view if the tab has been fully created.
5426 // Get the custom view from the tab.
5427 View tabView = tab.getCustomView();
5429 // Only populate the title text view if the tab view has been fully populated.
5430 if (tabView != null) {
5431 // Get the title text view from the tab.
5432 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
5434 // Set the title according to the URL.
5435 if (title.equals("about:blank")) {
5436 // Set the title to indicate a new tab.
5437 tabTitleTextView.setText(R.string.new_tab);
5439 // Set the title as the tab text.
5440 tabTitleTextView.setText(title);
5446 // Enter full screen video.
5448 public void onShowCustomView(View video, CustomViewCallback callback) {
5449 // Set the full screen video flag.
5450 displayingFullScreenVideo = true;
5452 // Hide the keyboard.
5453 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
5455 // Hide the coordinator layout.
5456 coordinatorLayout.setVisibility(View.GONE);
5458 /* Hide the system bars.
5459 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5460 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5461 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5462 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5464 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5465 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5467 // Disable the sliding drawers.
5468 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
5470 // Add the video view to the full screen video frame layout.
5471 fullScreenVideoFrameLayout.addView(video);
5473 // Show the full screen video frame layout.
5474 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
5476 // Disable the screen timeout while the video is playing. YouTube does this automatically, but not all other videos do.
5477 fullScreenVideoFrameLayout.setKeepScreenOn(true);
5480 // Exit full screen video.
5482 public void onHideCustomView() {
5483 // Exit the full screen video.
5484 exitFullScreenVideo();
5489 public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
5490 // Store the file path callback.
5491 fileChooserCallback = filePathCallback;
5493 // Create an intent to open a chooser based on the file chooser parameters.
5494 Intent fileChooserIntent = fileChooserParams.createIntent();
5496 // Get a handle for the package manager.
5497 PackageManager packageManager = getPackageManager();
5499 // Check to see if the file chooser intent resolves to an installed package.
5500 if (fileChooserIntent.resolveActivity(packageManager) != null) { // The file chooser intent is fine.
5501 // Start the file chooser intent.
5502 startActivityForResult(fileChooserIntent, BROWSE_FILE_UPLOAD_REQUEST_CODE);
5503 } else { // The file chooser intent will cause a crash.
5504 // Create a generic intent to open a chooser.
5505 Intent genericFileChooserIntent = new Intent(Intent.ACTION_GET_CONTENT);
5507 // Request an openable file.
5508 genericFileChooserIntent.addCategory(Intent.CATEGORY_OPENABLE);
5510 // Set the file type to everything.
5511 genericFileChooserIntent.setType("*/*");
5513 // Start the generic file chooser intent.
5514 startActivityForResult(genericFileChooserIntent, BROWSE_FILE_UPLOAD_REQUEST_CODE);
5520 nestedScrollWebView.setWebViewClient(new WebViewClient() {
5521 // `shouldOverrideUrlLoading` makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
5522 // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
5524 public boolean shouldOverrideUrlLoading(WebView view, String url) {
5525 // Sanitize the url.
5526 url = sanitizeUrl(url);
5528 // Handle the URL according to the type.
5529 if (url.startsWith("http")) { // Load the URL in Privacy Browser.
5530 // Load the URL. By using `loadUrl()`, instead of `loadUrlFromBase()`, the Referer header will never be sent.
5531 loadUrl(nestedScrollWebView, url);
5533 // Returning true indicates that Privacy Browser is manually handling the loading of the URL.
5534 // Custom headers cannot be added if false is returned and the WebView handles the loading of the URL.
5536 } else if (url.startsWith("mailto:")) { // Load the email address in an external email program.
5537 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
5538 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
5540 // Parse the url and set it as the data for the intent.
5541 emailIntent.setData(Uri.parse(url));
5543 // Open the email program in a new task instead of as part of Privacy Browser.
5544 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5548 startActivity(emailIntent);
5549 } catch (ActivityNotFoundException exception) {
5550 // Display a snackbar.
5551 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
5555 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5557 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
5558 // Open the dialer and load the phone number, but wait for the user to place the call.
5559 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
5561 // Add the phone number to the intent.
5562 dialIntent.setData(Uri.parse(url));
5564 // Open the dialer in a new task instead of as part of Privacy Browser.
5565 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5569 startActivity(dialIntent);
5570 } catch (ActivityNotFoundException exception) {
5571 // Display a snackbar.
5572 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
5575 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5577 } else { // Load a system chooser to select an app that can handle the URL.
5578 // Open an app that can handle the URL.
5579 Intent genericIntent = new Intent(Intent.ACTION_VIEW);
5581 // Add the URL to the intent.
5582 genericIntent.setData(Uri.parse(url));
5584 // List all apps that can handle the URL instead of just opening the first one.
5585 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
5587 // Open the app in a new task instead of as part of Privacy Browser.
5588 genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5590 // Start the app or display a snackbar if no app is available to handle the URL.
5592 startActivity(genericIntent);
5593 } catch (ActivityNotFoundException exception) {
5594 Snackbar.make(nestedScrollWebView, getString(R.string.unrecognized_url) + " " + url, Snackbar.LENGTH_SHORT).show();
5597 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5602 // Check requests against the block lists. The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
5604 public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest webResourceRequest) {
5606 String url = webResourceRequest.getUrl().toString();
5608 // Check to see if the resource request is for the main URL.
5609 if (url.equals(nestedScrollWebView.getCurrentUrl())) {
5610 // `return null` loads the resource request, which should never be blocked if it is the main URL.
5614 // 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.
5615 while (ultraPrivacy == null) {
5616 // The wait must be synchronized, which only lets one thread run on it at a time, or `java.lang.IllegalMonitorStateException` is thrown.
5617 synchronized (this) {
5619 // Check to see if the blocklists have been populated after 100 ms.
5621 } catch (InterruptedException exception) {
5627 // Create an empty web resource response to be used if the resource request is blocked.
5628 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
5630 // Reset the whitelist results tracker.
5631 String[] whitelistResultStringArray = null;
5633 // Initialize the third party request tracker.
5634 boolean isThirdPartyRequest = false;
5636 // Get the current URL. `.getUrl()` throws an error because operations on the WebView cannot be made from this thread.
5637 String currentBaseDomain = nestedScrollWebView.getCurrentDomainName();
5639 // Store a copy of the current domain for use in later requests.
5640 String currentDomain = currentBaseDomain;
5642 // Get the request host name.
5643 String requestBaseDomain = webResourceRequest.getUrl().getHost();
5645 // Only check for third-party requests if the current base domain is not empty and the request domain is not null.
5646 if (!currentBaseDomain.isEmpty() && (requestBaseDomain != null)) {
5647 // Determine the current base domain.
5648 while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
5649 // Remove the first subdomain.
5650 currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
5653 // Determine the request base domain.
5654 while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
5655 // Remove the first subdomain.
5656 requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
5659 // Update the third party request tracker.
5660 isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
5663 // Get the current WebView page position.
5664 int webViewPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5666 // Determine if the WebView is currently displayed.
5667 boolean webViewDisplayed = (webViewPagePosition == tabLayout.getSelectedTabPosition());
5669 // Block third-party requests if enabled.
5670 if (isThirdPartyRequest && nestedScrollWebView.getBlockAllThirdPartyRequests()) {
5671 // Add the result to the resource requests.
5672 nestedScrollWebView.addResourceRequest(new String[]{BlocklistHelper.REQUEST_THIRD_PARTY, url});
5674 // Increment the blocked requests counters.
5675 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5676 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS);
5678 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5679 if (webViewDisplayed) {
5680 // Updating the UI must be run from the UI thread.
5681 activity.runOnUiThread(() -> {
5682 // Update the menu item titles.
5683 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5685 // Update the options menu if it has been populated.
5686 if (optionsMenu != null) {
5687 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5688 optionsBlockAllThirdPartyRequestsMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " +
5689 getString(R.string.block_all_third_party_requests));
5694 // Return an empty web resource response.
5695 return emptyWebResourceResponse;
5698 // Check UltraList if it is enabled.
5699 if (nestedScrollWebView.getUltraListEnabled()) {
5700 // Check the URL against UltraList.
5701 String[] ultraListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraList);
5703 // Process the UltraList results.
5704 if (ultraListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched UltraList's blacklist.
5705 // Add the result to the resource requests.
5706 nestedScrollWebView.addResourceRequest(new String[] {ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]});
5708 // Increment the blocked requests counters.
5709 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5710 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRALIST);
5712 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5713 if (webViewDisplayed) {
5714 // Updating the UI must be run from the UI thread.
5715 activity.runOnUiThread(() -> {
5716 // Update the menu item titles.
5717 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5719 // Update the options menu if it has been populated.
5720 if (optionsMenu != null) {
5721 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5722 optionsUltraListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRALIST) + " - " + getString(R.string.ultralist));
5727 // The resource request was blocked. Return an empty web resource response.
5728 return emptyWebResourceResponse;
5729 } else if (ultraListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched UltraList's whitelist.
5730 // Add a whitelist entry to the resource requests array.
5731 nestedScrollWebView.addResourceRequest(new String[] {ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]});
5733 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
5738 // Check UltraPrivacy if it is enabled.
5739 if (nestedScrollWebView.getUltraPrivacyEnabled()) {
5740 // Check the URL against UltraPrivacy.
5741 String[] ultraPrivacyResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraPrivacy);
5743 // Process the UltraPrivacy results.
5744 if (ultraPrivacyResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched UltraPrivacy's blacklist.
5745 // Add the result to the resource requests.
5746 nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5747 ultraPrivacyResults[5]});
5749 // Increment the blocked requests counters.
5750 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5751 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRAPRIVACY);
5753 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5754 if (webViewDisplayed) {
5755 // Updating the UI must be run from the UI thread.
5756 activity.runOnUiThread(() -> {
5757 // Update the menu item titles.
5758 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5760 // Update the options menu if it has been populated.
5761 if (optionsMenu != null) {
5762 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5763 optionsUltraPrivacyMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRAPRIVACY) + " - " + getString(R.string.ultraprivacy));
5768 // The resource request was blocked. Return an empty web resource response.
5769 return emptyWebResourceResponse;
5770 } else if (ultraPrivacyResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched UltraPrivacy's whitelist.
5771 // Add a whitelist entry to the resource requests array.
5772 nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5773 ultraPrivacyResults[5]});
5775 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
5780 // Check EasyList if it is enabled.
5781 if (nestedScrollWebView.getEasyListEnabled()) {
5782 // Check the URL against EasyList.
5783 String[] easyListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyList);
5785 // Process the EasyList results.
5786 if (easyListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched EasyList's blacklist.
5787 // Add the result to the resource requests.
5788 nestedScrollWebView.addResourceRequest(new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]});
5790 // Increment the blocked requests counters.
5791 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5792 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASYLIST);
5794 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5795 if (webViewDisplayed) {
5796 // Updating the UI must be run from the UI thread.
5797 activity.runOnUiThread(() -> {
5798 // Update the menu item titles.
5799 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5801 // Update the options menu if it has been populated.
5802 if (optionsMenu != null) {
5803 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5804 optionsEasyListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASYLIST) + " - " + getString(R.string.easylist));
5809 // The resource request was blocked. Return an empty web resource response.
5810 return emptyWebResourceResponse;
5811 } else if (easyListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched EasyList's whitelist.
5812 // Update the whitelist result string array tracker.
5813 whitelistResultStringArray = new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]};
5817 // Check EasyPrivacy if it is enabled.
5818 if (nestedScrollWebView.getEasyPrivacyEnabled()) {
5819 // Check the URL against EasyPrivacy.
5820 String[] easyPrivacyResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyPrivacy);
5822 // Process the EasyPrivacy results.
5823 if (easyPrivacyResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched EasyPrivacy's blacklist.
5824 // Add the result to the resource requests.
5825 nestedScrollWebView.addResourceRequest(new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4],
5826 easyPrivacyResults[5]});
5828 // Increment the blocked requests counters.
5829 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5830 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASYPRIVACY);
5832 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5833 if (webViewDisplayed) {
5834 // Updating the UI must be run from the UI thread.
5835 activity.runOnUiThread(() -> {
5836 // Update the menu item titles.
5837 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5839 // Update the options menu if it has been populated.
5840 if (optionsMenu != null) {
5841 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5842 optionsEasyPrivacyMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASYPRIVACY) + " - " + getString(R.string.easyprivacy));
5847 // The resource request was blocked. Return an empty web resource response.
5848 return emptyWebResourceResponse;
5849 } else if (easyPrivacyResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched EasyPrivacy's whitelist.
5850 // Update the whitelist result string array tracker.
5851 whitelistResultStringArray = new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5]};
5855 // Check Fanboy’s Annoyance List if it is enabled.
5856 if (nestedScrollWebView.getFanboysAnnoyanceListEnabled()) {
5857 // Check the URL against Fanboy's Annoyance List.
5858 String[] fanboysAnnoyanceListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList);
5860 // Process the Fanboy's Annoyance List results.
5861 if (fanboysAnnoyanceListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched Fanboy's Annoyance List's blacklist.
5862 // Add the result to the resource requests.
5863 nestedScrollWebView.addResourceRequest(new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5864 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]});
5866 // Increment the blocked requests counters.
5867 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5868 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST);
5870 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5871 if (webViewDisplayed) {
5872 // Updating the UI must be run from the UI thread.
5873 activity.runOnUiThread(() -> {
5874 // Update the menu item titles.
5875 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5877 // Update the options menu if it has been populated.
5878 if (optionsMenu != null) {
5879 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5880 optionsFanboysAnnoyanceListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " +
5881 getString(R.string.fanboys_annoyance_list));
5886 // The resource request was blocked. Return an empty web resource response.
5887 return emptyWebResourceResponse;
5888 } else if (fanboysAnnoyanceListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)){ // The resource request matched Fanboy's Annoyance List's whitelist.
5889 // Update the whitelist result string array tracker.
5890 whitelistResultStringArray = new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5891 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]};
5893 } else if (nestedScrollWebView.getFanboysSocialBlockingListEnabled()) { // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
5894 // Check the URL against Fanboy's Annoyance List.
5895 String[] fanboysSocialListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysSocialList);
5897 // Process the Fanboy's Social Blocking List results.
5898 if (fanboysSocialListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched Fanboy's Social Blocking List's blacklist.
5899 // Add the result to the resource requests.
5900 nestedScrollWebView.addResourceRequest(new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5901 fanboysSocialListResults[4], fanboysSocialListResults[5]});
5903 // Increment the blocked requests counters.
5904 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5905 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST);
5907 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5908 if (webViewDisplayed) {
5909 // Updating the UI must be run from the UI thread.
5910 activity.runOnUiThread(() -> {
5911 // Update the menu item titles.
5912 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5914 // Update the options menu if it has been populated.
5915 if (optionsMenu != null) {
5916 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5917 optionsFanboysSocialBlockingListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " +
5918 getString(R.string.fanboys_social_blocking_list));
5923 // The resource request was blocked. Return an empty web resource response.
5924 return emptyWebResourceResponse;
5925 } else if (fanboysSocialListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched Fanboy's Social Blocking List's whitelist.
5926 // Update the whitelist result string array tracker.
5927 whitelistResultStringArray = new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5928 fanboysSocialListResults[4], fanboysSocialListResults[5]};
5932 // Add the request to the log because it hasn't been processed by any of the previous checks.
5933 if (whitelistResultStringArray != null) { // The request was processed by a whitelist.
5934 nestedScrollWebView.addResourceRequest(whitelistResultStringArray);
5935 } else { // The request didn't match any blocklist entry. Log it as a default request.
5936 nestedScrollWebView.addResourceRequest(new String[]{BlocklistHelper.REQUEST_DEFAULT, url});
5939 // The resource request has not been blocked. `return null` loads the requested resource.
5943 // Handle HTTP authentication requests.
5945 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
5946 // Store the handler.
5947 nestedScrollWebView.setHttpAuthHandler(handler);
5949 // Instantiate an HTTP authentication dialog.
5950 DialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm, nestedScrollWebView.getWebViewFragmentId());
5952 // Show the HTTP authentication dialog.
5953 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
5957 public void onPageStarted(WebView view, String url, Bitmap favicon) {
5958 // Get the app bar layout height. This can't be done in `applyAppSettings()` because the app bar is not yet populated there.
5959 // This should only be populated if it is greater than 0 because otherwise it will be reset to 0 if the app bar is hidden in full screen browsing mode.
5960 if (appBarLayout.getHeight() > 0) appBarHeight = appBarLayout.getHeight();
5962 // Set the padding and layout settings according to the position of the app bar.
5963 if (bottomAppBar) { // The app bar is on the bottom.
5965 if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) { // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
5966 // Reset the WebView padding to fill the available space.
5967 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5968 } else { // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
5969 // Move the WebView above the app bar layout.
5970 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight);
5972 } else { // The app bar is on the top.
5973 // 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.
5974 if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) {
5975 // No padding is needed because it will automatically be placed below the app bar layout due to the scrolling layout behavior.
5976 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5978 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5979 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10, defaultProgressViewEndOffset);
5981 // The swipe refresh layout must be manually moved below the app bar layout.
5982 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0);
5984 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5985 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight);
5989 // Reset the list of resource requests.
5990 nestedScrollWebView.clearResourceRequests();
5992 // Reset the requests counters.
5993 nestedScrollWebView.resetRequestsCounters();
5995 // Get the current page position.
5996 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5998 // Update the URL text bar if the page is currently selected and the URL edit text is not currently being edited.
5999 if ((tabLayout.getSelectedTabPosition() == currentPagePosition) && !urlEditText.hasFocus()) {
6000 // Display the formatted URL text.
6001 urlEditText.setText(url);
6003 // Apply text highlighting to the URL text box.
6006 // Hide the keyboard.
6007 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
6010 // Reset the list of host IP addresses.
6011 nestedScrollWebView.setCurrentIpAddresses("");
6013 // Get a URI for the current URL.
6014 Uri currentUri = Uri.parse(url);
6016 // Get the IP addresses for the host.
6017 new GetHostIpAddresses(activity, getSupportFragmentManager(), nestedScrollWebView).execute(currentUri.getHost());
6019 // Replace Refresh with Stop if the options menu has been created. (The first WebView typically begins loading before the menu items are instantiated.)
6020 if (optionsMenu != null) {
6022 optionsRefreshMenuItem.setTitle(R.string.stop);
6024 // Get the app bar and theme preferences.
6025 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean(getString(R.string.display_additional_app_bar_icons_key), false);
6027 // Set the icon if it is displayed in the AppBar. Once the minimum API is >= 26, the blue and black icons can be combined with a tint list.
6028 if (displayAdditionalAppBarIcons) {
6029 optionsRefreshMenuItem.setIcon(R.drawable.close_blue);
6035 public void onPageFinished(WebView view, String url) {
6036 // Flush any cookies to persistent storage. The cookie manager has become very lazy about flushing cookies in recent versions.
6037 if (nestedScrollWebView.getAcceptCookies()) {
6038 CookieManager.getInstance().flush();
6041 // Update the Refresh menu item if the options menu has been created.
6042 if (optionsMenu != null) {
6043 // Reset the Refresh title.
6044 optionsRefreshMenuItem.setTitle(R.string.refresh);
6046 // Get the app bar and theme preferences.
6047 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean(getString(R.string.display_additional_app_bar_icons_key), false);
6049 // If the icon is displayed in the app bar, reset it according to the theme.
6050 if (displayAdditionalAppBarIcons) {
6052 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled);
6056 // Clear the cache, history, and logcat if Incognito Mode is enabled.
6057 if (incognitoModeEnabled) {
6058 // Clear the cache. `true` includes disk files.
6059 nestedScrollWebView.clearCache(true);
6061 // Clear the back/forward history.
6062 nestedScrollWebView.clearHistory();
6064 // Manually delete cache folders.
6066 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
6067 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
6068 String privateDataDirectoryString = getApplicationInfo().dataDir;
6070 // Delete the main cache directory.
6071 Runtime.getRuntime().exec("rm -rf " + privateDataDirectoryString + "/cache");
6073 // Delete the secondary `Service Worker` cache directory.
6074 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
6075 Runtime.getRuntime().exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
6076 } catch (IOException exception) {
6077 // Do nothing if an error is thrown.
6080 // Clear the logcat.
6082 // Clear the logcat. `-c` clears the logcat. `-b all` clears all the buffers (instead of just crash, main, and system).
6083 Runtime.getRuntime().exec("logcat -b all -c");
6084 } catch (IOException exception) {
6089 // Get the current page position.
6090 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
6092 // 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.
6093 String currentUrl = nestedScrollWebView.getUrl();
6095 // Get the current tab.
6096 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
6098 // Update the URL text bar if the page is currently selected and the user is not currently typing in the URL edit text.
6099 // Crash records show that, in some crazy way, it is possible for the current URL to be blank at this point.
6100 // Probably some sort of race condition when Privacy Browser is being resumed.
6101 if ((tabLayout.getSelectedTabPosition() == currentPagePosition) && !urlEditText.hasFocus() && (currentUrl != null)) {
6102 // Check to see if the URL is `about:blank`.
6103 if (currentUrl.equals("about:blank")) { // The WebView is blank.
6104 // Display the hint in the URL edit text.
6105 urlEditText.setText("");
6107 // Request focus for the URL text box.
6108 urlEditText.requestFocus();
6110 // Display the keyboard.
6111 inputMethodManager.showSoftInput(urlEditText, 0);
6113 // Apply the domain settings. This clears any settings from the previous domain.
6114 applyDomainSettings(nestedScrollWebView, "", true, false, false);
6116 // Only populate the title text view if the tab has been fully created.
6118 // Get the custom view from the tab.
6119 View tabView = tab.getCustomView();
6121 // Remove the incorrect warning below that the current tab view might be null.
6122 assert tabView != null;
6124 // Get the title text view from the tab.
6125 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
6127 // Set the title as the tab text.
6128 tabTitleTextView.setText(R.string.new_tab);
6130 } else { // The WebView has loaded a webpage.
6131 // Update the URL edit text if it is not currently being edited.
6132 if (!urlEditText.hasFocus()) {
6133 // 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.
6134 String sanitizedUrl = sanitizeUrl(currentUrl);
6136 // Display the final URL. Getting the URL from the WebView instead of using the one provided by `onPageFinished()` makes websites like YouTube function correctly.
6137 urlEditText.setText(sanitizedUrl);
6139 // Apply text highlighting to the URL.
6143 // Only populate the title text view if the tab has been fully created.
6145 // Get the custom view from the tab.
6146 View tabView = tab.getCustomView();
6148 // Remove the incorrect warning below that the current tab view might be null.
6149 assert tabView != null;
6151 // Get the title text view from the tab.
6152 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
6154 // Set the title as the tab text. Sometimes `onReceivedTitle()` is not called, especially when navigating history.
6155 tabTitleTextView.setText(nestedScrollWebView.getTitle());
6161 // Handle SSL Certificate errors. Suppress the lint warning that ignoring the error might be dangerous.
6162 @SuppressLint("WebViewClientOnReceivedSslError")
6164 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
6165 // Get the current website SSL certificate.
6166 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
6168 // Extract the individual pieces of information from the current website SSL certificate.
6169 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
6170 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
6171 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
6172 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
6173 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
6174 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
6175 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
6176 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
6178 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
6179 if (nestedScrollWebView.hasPinnedSslCertificate()) {
6180 // Get the pinned SSL certificate.
6181 Pair<String[], Date[]> pinnedSslCertificatePair = nestedScrollWebView.getPinnedSslCertificate();
6183 // Extract the arrays from the array list.
6184 String[] pinnedSslCertificateStringArray = pinnedSslCertificatePair.getFirst();
6185 Date[] pinnedSslCertificateDateArray = pinnedSslCertificatePair.getSecond();
6187 // Check if the current SSL certificate matches the pinned certificate.
6188 if (currentWebsiteIssuedToCName.equals(pinnedSslCertificateStringArray[0]) && currentWebsiteIssuedToOName.equals(pinnedSslCertificateStringArray[1]) &&
6189 currentWebsiteIssuedToUName.equals(pinnedSslCertificateStringArray[2]) && currentWebsiteIssuedByCName.equals(pinnedSslCertificateStringArray[3]) &&
6190 currentWebsiteIssuedByOName.equals(pinnedSslCertificateStringArray[4]) && currentWebsiteIssuedByUName.equals(pinnedSslCertificateStringArray[5]) &&
6191 currentWebsiteSslStartDate.equals(pinnedSslCertificateDateArray[0]) && currentWebsiteSslEndDate.equals(pinnedSslCertificateDateArray[1])) {
6193 // An SSL certificate is pinned and matches the current domain certificate. Proceed to the website without displaying an error.
6196 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
6197 // Store the SSL error handler.
6198 nestedScrollWebView.setSslErrorHandler(handler);
6200 // Instantiate an SSL certificate error alert dialog.
6201 DialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error, nestedScrollWebView.getWebViewFragmentId());
6203 // 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.
6205 // Show the SSL certificate error dialog.
6206 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
6207 } catch (Exception exception) {
6208 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
6209 pendingDialogsArrayList.add(new PendingDialog(sslCertificateErrorDialogFragment, getString(R.string.ssl_certificate_error)));
6215 // Check to see if the state is being restored.
6216 if (restoringState) { // The state is being restored.
6217 // Resume the nested scroll WebView JavaScript timers.
6218 nestedScrollWebView.resumeTimers();
6219 } else if (pageNumber == 0) { // The first page is being loaded.
6220 // Set this nested scroll WebView as the current WebView.
6221 currentWebView = nestedScrollWebView;
6223 // Initialize the URL to load string.
6224 String urlToLoadString;
6226 // Get the intent that started the app.
6227 Intent launchingIntent = getIntent();
6229 // Reset the intent. This prevents a duplicate tab from being created on restart.
6230 setIntent(new Intent());
6232 // Get the information from the intent.
6233 String launchingIntentAction = launchingIntent.getAction();
6234 Uri launchingIntentUriData = launchingIntent.getData();
6235 String launchingIntentStringExtra = launchingIntent.getStringExtra(Intent.EXTRA_TEXT);
6237 // Parse the launching intent URL.
6238 if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) { // The intent contains a search string.
6239 // Create an encoded URL string.
6240 String encodedUrlString;
6242 // Sanitize the search input and convert it to a search.
6244 encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
6245 } catch (UnsupportedEncodingException exception) {
6246 encodedUrlString = "";
6249 // Store the web search as the URL to load.
6250 urlToLoadString = searchURL + encodedUrlString;
6251 } else if (launchingIntentUriData != null) { // The launching intent contains a URL formatted as a URI.
6252 // Store the URI as a URL.
6253 urlToLoadString = launchingIntentUriData.toString();
6254 } else if (launchingIntentStringExtra != null) { // The launching intent contains text that might be a URL.
6256 urlToLoadString = launchingIntentStringExtra;
6257 } else if (!url.equals("")) { // The activity has been restarted.
6258 // Load the saved URL.
6259 urlToLoadString = url;
6260 } else { // The is no URL in the intent.
6261 // Store the homepage to be loaded.
6262 urlToLoadString = sharedPreferences.getString("homepage", getString(R.string.homepage_default_value));
6265 // Load the website if not waiting for the proxy.
6266 if (waitingForProxy) { // Store the URL to be loaded in the Nested Scroll WebView.
6267 nestedScrollWebView.setWaitingForProxyUrlString(urlToLoadString);
6268 } else { // Load the URL.
6269 loadUrl(nestedScrollWebView, urlToLoadString);
6272 // 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.
6273 // 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.
6274 setIntent(new Intent());
6275 } else { // This is not the first tab.
6277 loadUrl(nestedScrollWebView, url);
6279 // Set the focus and display the keyboard if the URL is blank.
6280 if (url.equals("")) {
6281 // Request focus for the URL text box.
6282 urlEditText.requestFocus();
6284 // Create a display keyboard handler.
6285 Handler displayKeyboardHandler = new Handler();
6287 // Create a display keyboard runnable.
6288 Runnable displayKeyboardRunnable = () -> {
6289 // Display the keyboard.
6290 inputMethodManager.showSoftInput(urlEditText, 0);
6293 // Display the keyboard after 100 milliseconds, which leaves enough time for the tab to transition.
6294 displayKeyboardHandler.postDelayed(displayKeyboardRunnable, 100);