2 * Copyright © 2015-2019 Soren Stoutner <soren@stoutner.com>.
4 * Download cookie code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
6 * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
8 * Privacy Browser is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
13 * Privacy Browser is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with Privacy Browser. If not, see <http://www.gnu.org/licenses/>.
22 package com.stoutner.privacybrowser.activities;
24 import android.Manifest;
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.Build;
50 import android.os.Bundle;
51 import android.os.Environment;
52 import android.os.Handler;
53 import android.preference.PreferenceManager;
54 import android.print.PrintDocumentAdapter;
55 import android.print.PrintManager;
56 import android.text.Editable;
57 import android.text.Spanned;
58 import android.text.TextWatcher;
59 import android.text.style.ForegroundColorSpan;
60 import android.util.Patterns;
61 import android.view.ContextMenu;
62 import android.view.GestureDetector;
63 import android.view.KeyEvent;
64 import android.view.Menu;
65 import android.view.MenuItem;
66 import android.view.MotionEvent;
67 import android.view.View;
68 import android.view.ViewGroup;
69 import android.view.WindowManager;
70 import android.view.inputmethod.InputMethodManager;
71 import android.webkit.CookieManager;
72 import android.webkit.HttpAuthHandler;
73 import android.webkit.SslErrorHandler;
74 import android.webkit.ValueCallback;
75 import android.webkit.WebChromeClient;
76 import android.webkit.WebResourceResponse;
77 import android.webkit.WebSettings;
78 import android.webkit.WebStorage;
79 import android.webkit.WebView;
80 import android.webkit.WebViewClient;
81 import android.webkit.WebViewDatabase;
82 import android.widget.ArrayAdapter;
83 import android.widget.CursorAdapter;
84 import android.widget.EditText;
85 import android.widget.FrameLayout;
86 import android.widget.ImageView;
87 import android.widget.LinearLayout;
88 import android.widget.ListView;
89 import android.widget.ProgressBar;
90 import android.widget.RadioButton;
91 import android.widget.RelativeLayout;
92 import android.widget.TextView;
94 import androidx.annotation.NonNull;
95 import androidx.appcompat.app.ActionBar;
96 import androidx.appcompat.app.ActionBarDrawerToggle;
97 import androidx.appcompat.app.AppCompatActivity;
98 import androidx.appcompat.widget.Toolbar;
99 import androidx.coordinatorlayout.widget.CoordinatorLayout;
100 import androidx.core.app.ActivityCompat;
101 import androidx.core.content.ContextCompat;
102 import androidx.core.view.GravityCompat;
103 import androidx.drawerlayout.widget.DrawerLayout;
104 import androidx.fragment.app.DialogFragment;
105 import androidx.fragment.app.FragmentManager;
106 import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
107 import androidx.viewpager.widget.ViewPager;
109 import com.google.android.material.appbar.AppBarLayout;
110 import com.google.android.material.floatingactionbutton.FloatingActionButton;
111 import com.google.android.material.navigation.NavigationView;
112 import com.google.android.material.snackbar.Snackbar;
113 import com.google.android.material.tabs.TabLayout;
115 import com.stoutner.privacybrowser.BuildConfig;
116 import com.stoutner.privacybrowser.R;
117 import com.stoutner.privacybrowser.adapters.WebViewPagerAdapter;
118 import com.stoutner.privacybrowser.asynctasks.GetHostIpAddresses;
119 import com.stoutner.privacybrowser.asynctasks.PopulateBlocklists;
120 import com.stoutner.privacybrowser.asynctasks.SaveWebpageImage;
121 import com.stoutner.privacybrowser.dialogs.AdConsentDialog;
122 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
123 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
124 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
125 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
126 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
127 import com.stoutner.privacybrowser.dialogs.DownloadLocationPermissionDialog;
128 import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
129 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
130 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
131 import com.stoutner.privacybrowser.dialogs.SaveWebpageImageDialog;
132 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
133 import com.stoutner.privacybrowser.dialogs.StoragePermissionDialog;
134 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
135 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
136 import com.stoutner.privacybrowser.fragments.WebViewTabFragment;
137 import com.stoutner.privacybrowser.helpers.AdHelper;
138 import com.stoutner.privacybrowser.helpers.BlocklistHelper;
139 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
140 import com.stoutner.privacybrowser.helpers.CheckPinnedMismatchHelper;
141 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
142 import com.stoutner.privacybrowser.helpers.FileNameHelper;
143 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
144 import com.stoutner.privacybrowser.views.NestedScrollWebView;
146 import java.io.ByteArrayInputStream;
147 import java.io.ByteArrayOutputStream;
149 import java.io.IOException;
150 import java.io.UnsupportedEncodingException;
151 import java.net.MalformedURLException;
153 import java.net.URLDecoder;
154 import java.net.URLEncoder;
155 import java.util.ArrayList;
156 import java.util.Date;
157 import java.util.HashMap;
158 import java.util.HashSet;
159 import java.util.List;
160 import java.util.Map;
161 import java.util.Set;
163 // AppCompatActivity from android.support.v7.app.AppCompatActivity must be used to have access to the SupportActionBar until the minimum API is >= 21.
164 public class MainWebViewActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener,
165 DownloadFileDialog.DownloadFileListener, DownloadImageDialog.DownloadImageListener, DownloadLocationPermissionDialog.DownloadLocationPermissionDialogListener, EditBookmarkDialog.EditBookmarkListener,
166 EditBookmarkFolderDialog.EditBookmarkFolderListener, NavigationView.OnNavigationItemSelectedListener, PopulateBlocklists.PopulateBlocklistsListener, SaveWebpageImageDialog.SaveWebpageImageListener,
167 StoragePermissionDialog.StoragePermissionDialogListener, WebViewTabFragment.NewTabListener {
169 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`, `onResume()`, and `applyProxyThroughOrbot()`.
170 public static String orbotStatus;
172 // The WebView pager adapter is accessed from `HttpAuthenticationDialog`, `PinnedMismatchDialog`, and `SslCertificateErrorDialog`. It is also used in `onCreate()`, `onResume()`, and `addTab()`.
173 public static WebViewPagerAdapter webViewPagerAdapter;
175 // The load URL on restart variables are public static so they can be accessed from `BookmarksActivity`. They are used in `onRestart()`.
176 public static boolean loadUrlOnRestart;
177 public static String urlToLoadOnRestart;
179 // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onRestart()`.
180 public static boolean restartFromBookmarksActivity;
182 // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`,
183 // `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
184 public static String currentBookmarksFolder;
186 // The user agent constants are public static so they can be accessed from `SettingsFragment`, `DomainsActivity`, and `DomainSettingsFragment`.
187 public final static int UNRECOGNIZED_USER_AGENT = -1;
188 public final static int SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1;
189 public final static int SETTINGS_CUSTOM_USER_AGENT = 12;
190 public final static int DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0;
191 public final static int DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2;
192 public final static int DOMAINS_CUSTOM_USER_AGENT = 13;
194 // Start activity for result request codes.
195 private final int FILE_UPLOAD_REQUEST_CODE = 0;
196 public final static int BROWSE_SAVE_WEBPAGE_IMAGE_REQUEST_CODE = 1;
199 // The current WebView is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
200 // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, `applyProxyThroughOrbot()`, and `applyDomainSettings()`.
201 private NestedScrollWebView currentWebView;
203 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
204 private final Map<String, String> customHeaders = new HashMap<>();
206 // The search URL is set in `applyProxyThroughOrbot()` and used in `onCreate()`, `onNewIntent()`, `loadURLFromTextBox()`, and `initializeWebView()`.
207 private String searchURL;
209 // The options menu is set in `onCreateOptionsMenu()` and used in `onOptionsItemSelected()`, `updatePrivacyIcons()`, and `initializeWebView()`.
210 private Menu optionsMenu;
212 // The blocklists are populated in `finishedPopulatingBlocklists()` and accessed from `initializeWebView()`.
213 private ArrayList<List<String[]>> easyList;
214 private ArrayList<List<String[]>> easyPrivacy;
215 private ArrayList<List<String[]>> fanboysAnnoyanceList;
216 private ArrayList<List<String[]>> fanboysSocialList;
217 private ArrayList<List<String[]>> ultraPrivacy;
219 // `webViewDefaultUserAgent` is used in `onCreate()` and `onPrepareOptionsMenu()`.
220 private String webViewDefaultUserAgent;
222 // `proxyThroughOrbot` is used in `onRestart()`, `onOptionsItemSelected()`, `applyAppSettings()`, and `applyProxyThroughOrbot()`.
223 private boolean proxyThroughOrbot;
225 // The incognito mode is set in `applyAppSettings()` and used in `initializeWebView()`.
226 private boolean incognitoModeEnabled;
228 // The full screen browsing mode tracker is set it `applyAppSettings()` and used in `initializeWebView()`.
229 private boolean fullScreenBrowsingModeEnabled;
231 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
232 private boolean inFullScreenBrowsingMode;
234 // The app bar trackers are set in `applyAppSettings()` and used in `initializeWebView()`.
235 private boolean hideAppBar;
236 private boolean scrollAppBar;
238 // The loading new intent tracker is set in `onNewIntent()` and used in `setCurrentWebView()`.
239 private boolean loadingNewIntent;
241 // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
242 private boolean reapplyDomainSettingsOnRestart;
244 // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
245 private boolean reapplyAppSettingsOnRestart;
247 // `displayingFullScreenVideo` is used in `onCreate()` and `onResume()`.
248 private boolean displayingFullScreenVideo;
250 // `orbotStatusBroadcastReceiver` is used in `onCreate()` and `onDestroy()`.
251 private BroadcastReceiver orbotStatusBroadcastReceiver;
253 // `waitingForOrbot` is used in `onCreate()`, `onResume()`, and `applyProxyThroughOrbot()`.
254 private boolean waitingForOrbot;
256 // The action bar drawer toggle is initialized in `onCreate()` and used in `onResume()`.
257 private ActionBarDrawerToggle actionBarDrawerToggle;
259 // The color spans are used in `onCreate()` and `highlightUrlText()`.
260 private ForegroundColorSpan redColorSpan;
261 private ForegroundColorSpan initialGrayColorSpan;
262 private ForegroundColorSpan finalGrayColorSpan;
264 // The drawer header padding variables are used in `onCreate()` and `onConfigurationChanged()`.
265 private int drawerHeaderPaddingLeftAndRight;
266 private int drawerHeaderPaddingTop;
267 private int drawerHeaderPaddingBottom;
269 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onDestroy`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`,
270 // and `loadBookmarksFolder()`.
271 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
273 // `bookmarksCursor` is used in `onDestroy()`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
274 private Cursor bookmarksCursor;
276 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
277 private CursorAdapter bookmarksCursorAdapter;
279 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
280 private String oldFolderNameString;
282 // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
283 private ValueCallback<Uri[]> fileChooserCallback;
285 // The default progress view offsets are set in `onCreate()` and used in `initializeWebView()`.
286 private int defaultProgressViewStartOffset;
287 private int defaultProgressViewEndOffset;
289 // The swipe refresh layout top padding is used when exiting full screen browsing mode. It is used in an inner class in `initializeWebView()`.
290 private int swipeRefreshLayoutPaddingTop;
292 // The URL sanitizers are set in `applyAppSettings()` and used in `sanitizeUrl()`.
293 private boolean sanitizeGoogleAnalytics;
294 private boolean sanitizeFacebookClickIds;
295 private boolean sanitizeTwitterAmpRedirects;
297 // The download strings are used in `onCreate()`, `onRequestPermissionResult()` and `initializeWebView()`.
298 private String downloadUrl;
299 private String downloadContentDisposition;
300 private long downloadContentLength;
302 // `downloadImageUrl` is used in `onCreateContextMenu()` and `onRequestPermissionResult()`.
303 private String downloadImageUrl;
305 // The save website image file path string is used in `onSaveWebpageImage()` and `onRequestPermissionResult()`
306 private String saveWebsiteImageFilePath;
308 // The permission result request codes are used in `onCreateContextMenu()`, `onCloseDownloadLocationPermissionDialog()`, `onRequestPermissionResult()`, `onSaveWebpageImage()`,
309 // `onCloseStoragePermissionDialog()`, and `initializeWebView()`.
310 private final int DOWNLOAD_FILE_REQUEST_CODE = 1;
311 private final int DOWNLOAD_IMAGE_REQUEST_CODE = 2;
312 private final int SAVE_WEBPAGE_IMAGE_REQUEST_CODE = 3;
315 // Remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
316 @SuppressLint("ClickableViewAccessibility")
317 protected void onCreate(Bundle savedInstanceState) {
318 if (Build.VERSION.SDK_INT >= 21) {
319 WebView.enableSlowWholeDocumentDraw();
322 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
323 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
325 // Get a handle for the shared preferences.
326 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
328 // Get the theme and screenshot preferences.
329 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
330 boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
332 // Disable screenshots if not allowed.
333 if (!allowScreenshots) {
334 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
337 // Set the activity theme.
339 setTheme(R.style.PrivacyBrowserDark);
341 setTheme(R.style.PrivacyBrowserLight);
344 // Run the default commands.
345 super.onCreate(savedInstanceState);
347 // Set the content view.
348 setContentView(R.layout.main_framelayout);
350 // Get handles for the views that need to be modified.
351 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
352 Toolbar toolbar = findViewById(R.id.toolbar);
353 ViewPager webViewPager = findViewById(R.id.webviewpager);
355 // Set the action bar. `SupportActionBar` must be used until the minimum API is >= 21.
356 setSupportActionBar(toolbar);
358 // Get a handle for the action bar.
359 ActionBar actionBar = getSupportActionBar();
361 // This is needed to get rid of the Android Studio warning that the action bar might be null.
362 assert actionBar != null;
364 // Add the custom layout, which shows the URL text bar.
365 actionBar.setCustomView(R.layout.url_app_bar);
366 actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
368 // Initially disable the sliding drawers. They will be enabled once the blocklists are loaded.
369 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
371 // Create the hamburger icon at the start of the AppBar.
372 actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
374 // Initialize the web view pager adapter.
375 webViewPagerAdapter = new WebViewPagerAdapter(getSupportFragmentManager());
377 // Set the pager adapter on the web view pager.
378 webViewPager.setAdapter(webViewPagerAdapter);
380 // Store up to 100 tabs in memory.
381 webViewPager.setOffscreenPageLimit(100);
383 // Populate the blocklists.
384 new PopulateBlocklists(this, this).execute();
388 protected void onNewIntent(Intent intent) {
389 // Replace the intent that started the app with this one.
392 // Process the intent here if Privacy Browser is fully initialized. If the process has been killed by the system while sitting in the background, this will be handled in `initializeWebView()`.
393 if (ultraPrivacy != null) {
394 // Get the information from the intent.
395 String intentAction = intent.getAction();
396 Uri intentUriData = intent.getData();
398 // Determine if this is a web search.
399 boolean isWebSearch = ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH));
401 // 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.
402 if (intentUriData != null || isWebSearch) {
403 // Get the shared preferences.
404 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
406 // Create a URL string.
409 // If the intent action is a web search, perform the search.
411 // Create an encoded URL string.
412 String encodedUrlString;
414 // Sanitize the search input and convert it to a search.
416 encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
417 } catch (UnsupportedEncodingException exception) {
418 encodedUrlString = "";
421 // Add the base search URL.
422 url = searchURL + encodedUrlString;
423 } else { // The intent should contain a URL.
424 // Set the intent data as the URL.
425 url = intentUriData.toString();
428 // Add a new tab if specified in the preferences.
429 if (sharedPreferences.getBoolean("open_intents_in_new_tab", true)) { // Load the URL in a new tab.
430 // Set the loading new intent flag.
431 loadingNewIntent = true;
435 } else { // Load the URL in the current tab.
440 // Get a handle for the drawer layout.
441 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
443 // Close the navigation drawer if it is open.
444 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
445 drawerLayout.closeDrawer(GravityCompat.START);
448 // Close the bookmarks drawer if it is open.
449 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
450 drawerLayout.closeDrawer(GravityCompat.END);
457 public void onRestart() {
458 // Run the default commands.
461 // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
462 if (proxyThroughOrbot) {
463 // Request Orbot to start. If Orbot is already running no hard will be caused by this request.
464 Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
466 // Send the intent to the Orbot package.
467 orbotIntent.setPackage("org.torproject.android");
470 sendBroadcast(orbotIntent);
473 // Apply the app settings if returning from the Settings activity.
474 if (reapplyAppSettingsOnRestart) {
475 // Reset the reapply app settings on restart tracker.
476 reapplyAppSettingsOnRestart = false;
478 // Apply the app settings.
482 // Apply the domain settings if returning from the settings or domains activity.
483 if (reapplyDomainSettingsOnRestart) {
484 // Reset the reapply domain settings on restart tracker.
485 reapplyDomainSettingsOnRestart = false;
487 // Reapply the domain settings for each tab.
488 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
489 // Get the WebView tab fragment.
490 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
492 // Get the fragment view.
493 View fragmentView = webViewTabFragment.getView();
495 // Only reload the WebViews if they exist.
496 if (fragmentView != null) {
497 // Get the nested scroll WebView from the tab fragment.
498 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
500 // Reset the current domain name so the domain settings will be reapplied.
501 nestedScrollWebView.resetCurrentDomainName();
503 // Reapply the domain settings if the URL is not null, which can happen if an empty tab is active when returning from settings.
504 if (nestedScrollWebView.getUrl() != null) {
505 applyDomainSettings(nestedScrollWebView, nestedScrollWebView.getUrl(), false, true);
511 // Load the URL on restart (used when loading a bookmark).
512 if (loadUrlOnRestart) {
513 // Load the specified URL.
514 loadUrl(urlToLoadOnRestart);
516 // Reset the load on restart tracker.
517 loadUrlOnRestart = false;
520 // Update the bookmarks drawer if returning from the Bookmarks activity.
521 if (restartFromBookmarksActivity) {
522 // Get a handle for the drawer layout.
523 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
525 // Close the bookmarks drawer.
526 drawerLayout.closeDrawer(GravityCompat.END);
528 // Reload the bookmarks drawer.
529 loadBookmarksFolder();
531 // Reset `restartFromBookmarksActivity`.
532 restartFromBookmarksActivity = false;
535 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
536 updatePrivacyIcons(true);
539 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
541 public void onResume() {
542 // Run the default commands.
545 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
546 // Get the WebView tab fragment.
547 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
549 // Get the fragment view.
550 View fragmentView = webViewTabFragment.getView();
552 // Only resume the WebViews if they exist (they won't when the app is first created).
553 if (fragmentView != null) {
554 // Get the nested scroll WebView from the tab fragment.
555 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
557 // Resume the nested scroll WebView JavaScript timers.
558 nestedScrollWebView.resumeTimers();
560 // Resume the nested scroll WebView.
561 nestedScrollWebView.onResume();
565 // Display a message to the user if waiting for Orbot.
566 if (waitingForOrbot && !orbotStatus.equals("ON")) {
567 // Disable the wide view port so that the waiting for Orbot text is displayed correctly.
568 currentWebView.getSettings().setUseWideViewPort(false);
570 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
571 currentWebView.loadData("<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>", "text/html", null);
574 if (displayingFullScreenVideo || inFullScreenBrowsingMode) {
575 // Get a handle for the root frame layouts.
576 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
578 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
579 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
581 /* Hide the system bars.
582 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
583 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
584 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
585 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
587 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
588 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
589 } else if (BuildConfig.FLAVOR.contentEquals("free")) { // Resume the adView for the free flavor.
591 AdHelper.resumeAd(findViewById(R.id.adview));
596 public void onPause() {
597 // Run the default commands.
600 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
601 // Get the WebView tab fragment.
602 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
604 // Get the fragment view.
605 View fragmentView = webViewTabFragment.getView();
607 // Only pause the WebViews if they exist (they won't when the app is first created).
608 if (fragmentView != null) {
609 // Get the nested scroll WebView from the tab fragment.
610 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
612 // Pause the nested scroll WebView.
613 nestedScrollWebView.onPause();
615 // Pause the nested scroll WebView JavaScript timers.
616 nestedScrollWebView.pauseTimers();
620 // Pause the ad or it will continue to consume resources in the background on the free flavor.
621 if (BuildConfig.FLAVOR.contentEquals("free")) {
623 AdHelper.pauseAd(findViewById(R.id.adview));
628 public void onDestroy() {
629 // Unregister the Orbot status broadcast receiver.
630 this.unregisterReceiver(orbotStatusBroadcastReceiver);
632 // Close the bookmarks cursor and database.
633 bookmarksCursor.close();
634 bookmarksDatabaseHelper.close();
636 // Run the default commands.
641 public boolean onCreateOptionsMenu(Menu menu) {
642 // Inflate the menu. This adds items to the action bar if it is present.
643 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
645 // Store a handle for the options menu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons()`.
648 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
649 updatePrivacyIcons(false);
651 // Get handles for the menu items.
652 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
653 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
654 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
655 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
656 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
657 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
658 MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
660 // Only display third-party cookies if API >= 21
661 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
663 // Only display the form data menu items if the API < 26.
664 toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
665 clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
667 // Disable the clear form data menu item if the API >= 26 so that the status of the main Clear Data is calculated correctly.
668 clearFormDataMenuItem.setEnabled(Build.VERSION.SDK_INT < 26);
670 // Only show Ad Consent if this is the free flavor.
671 adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
673 // Get the shared preferences.
674 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
676 // Get the dark theme and app bar preferences..
677 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
678 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
680 // 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.
681 if (displayAdditionalAppBarIcons) {
682 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
683 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
684 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
685 } else { //Do not display the additional icons.
686 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
687 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
688 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
691 // Replace Refresh with Stop if a URL is already loading.
692 if (currentWebView != null && currentWebView.getProgress() != 100) {
694 refreshMenuItem.setTitle(R.string.stop);
696 // If the icon is displayed in the AppBar, set it according to the theme.
697 if (displayAdditionalAppBarIcons) {
699 refreshMenuItem.setIcon(R.drawable.close_dark);
701 refreshMenuItem.setIcon(R.drawable.close_light);
711 public boolean onPrepareOptionsMenu(Menu menu) {
712 // Get handles for the menu items.
713 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
714 MenuItem firstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
715 MenuItem thirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
716 MenuItem domStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
717 MenuItem saveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
718 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
719 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
720 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
721 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
722 MenuItem blocklistsMenuItem = menu.findItem(R.id.blocklists);
723 MenuItem easyListMenuItem = menu.findItem(R.id.easylist);
724 MenuItem easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
725 MenuItem fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
726 MenuItem fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
727 MenuItem ultraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
728 MenuItem blockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
729 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
730 MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
731 MenuItem wideViewportMenuItem = menu.findItem(R.id.wide_viewport);
732 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
733 MenuItem nightModeMenuItem = menu.findItem(R.id.night_mode);
734 MenuItem proxyThroughOrbotMenuItem = menu.findItem(R.id.proxy_through_orbot);
736 // Get a handle for the cookie manager.
737 CookieManager cookieManager = CookieManager.getInstance();
739 // Initialize the current user agent string and the font size.
740 String currentUserAgent = getString(R.string.user_agent_privacy_browser);
743 // 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.
744 if (currentWebView != null) {
745 // Set the add or edit domain text.
746 if (currentWebView.getDomainSettingsApplied()) {
747 addOrEditDomain.setTitle(R.string.edit_domain_settings);
749 addOrEditDomain.setTitle(R.string.add_domain_settings);
752 // Get the current user agent from the WebView.
753 currentUserAgent = currentWebView.getSettings().getUserAgentString();
755 // Get the current font size from the
756 fontSize = currentWebView.getSettings().getTextZoom();
758 // Set the status of the menu item checkboxes.
759 domStorageMenuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
760 saveFormDataMenuItem.setChecked(currentWebView.getSettings().getSaveFormData()); // Form data can be removed once the minimum API >= 26.
761 easyListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST));
762 easyPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY));
763 fanboysAnnoyanceListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
764 fanboysSocialBlockingListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
765 ultraPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY));
766 blockAllThirdPartyRequestsMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
767 swipeToRefreshMenuItem.setChecked(currentWebView.getSwipeToRefresh());
768 wideViewportMenuItem.setChecked(currentWebView.getSettings().getUseWideViewPort());
769 displayImagesMenuItem.setChecked(currentWebView.getSettings().getLoadsImagesAutomatically());
770 nightModeMenuItem.setChecked(currentWebView.getNightMode());
772 // Initialize the display names for the blocklists with the number of blocked requests.
773 blocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
774 easyListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASY_LIST) + " - " + getString(R.string.easylist));
775 easyPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASY_PRIVACY) + " - " + getString(R.string.easyprivacy));
776 fanboysAnnoyanceListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " + getString(R.string.fanboys_annoyance_list));
777 fanboysSocialBlockingListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " + getString(R.string.fanboys_social_blocking_list));
778 ultraPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRA_PRIVACY) + " - " + getString(R.string.ultraprivacy));
779 blockAllThirdPartyRequestsMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " + getString(R.string.block_all_third_party_requests));
781 // Only modify third-party cookies if the API >= 21.
782 if (Build.VERSION.SDK_INT >= 21) {
783 // Set the status of the third-party cookies checkbox.
784 thirdPartyCookiesMenuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
786 // Enable third-party cookies if first-party cookies are enabled.
787 thirdPartyCookiesMenuItem.setEnabled(cookieManager.acceptCookie());
790 // Enable DOM Storage if JavaScript is enabled.
791 domStorageMenuItem.setEnabled(currentWebView.getSettings().getJavaScriptEnabled());
794 // Set the status of the menu item checkboxes.
795 firstPartyCookiesMenuItem.setChecked(cookieManager.acceptCookie());
796 proxyThroughOrbotMenuItem.setChecked(proxyThroughOrbot);
798 // Enable Clear Cookies if there are any.
799 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
801 // 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`.
802 String privateDataDirectoryString = getApplicationInfo().dataDir;
804 // Get a count of the number of files in the Local Storage directory.
805 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
806 int localStorageDirectoryNumberOfFiles = 0;
807 if (localStorageDirectory.exists()) {
808 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
811 // Get a count of the number of files in the IndexedDB directory.
812 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
813 int indexedDBDirectoryNumberOfFiles = 0;
814 if (indexedDBDirectory.exists()) {
815 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
818 // Enable Clear DOM Storage if there is any.
819 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
821 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
822 if (Build.VERSION.SDK_INT < 26) {
823 // Get the WebView database.
824 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
826 // Enable the clear form data menu item if there is anything to clear.
827 clearFormDataMenuItem.setEnabled(webViewDatabase.hasFormData());
830 // Enable Clear Data if any of the submenu items are enabled.
831 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
833 // Disable Fanboy's Social Blocking List menu item if Fanboy's Annoyance List is checked.
834 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListMenuItem.isChecked());
836 // Select the current user agent menu item. A switch statement cannot be used because the user agents are not compile time constants.
837 if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) { // Privacy Browser.
838 menu.findItem(R.id.user_agent_privacy_browser).setChecked(true);
839 } else if (currentUserAgent.equals(webViewDefaultUserAgent)) { // WebView Default.
840 menu.findItem(R.id.user_agent_webview_default).setChecked(true);
841 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) { // Firefox on Android.
842 menu.findItem(R.id.user_agent_firefox_on_android).setChecked(true);
843 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) { // Chrome on Android.
844 menu.findItem(R.id.user_agent_chrome_on_android).setChecked(true);
845 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) { // Safari on iOS.
846 menu.findItem(R.id.user_agent_safari_on_ios).setChecked(true);
847 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) { // Firefox on Linux.
848 menu.findItem(R.id.user_agent_firefox_on_linux).setChecked(true);
849 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) { // Chromium on Linux.
850 menu.findItem(R.id.user_agent_chromium_on_linux).setChecked(true);
851 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) { // Firefox on Windows.
852 menu.findItem(R.id.user_agent_firefox_on_windows).setChecked(true);
853 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) { // Chrome on Windows.
854 menu.findItem(R.id.user_agent_chrome_on_windows).setChecked(true);
855 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) { // Edge on Windows.
856 menu.findItem(R.id.user_agent_edge_on_windows).setChecked(true);
857 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) { // Internet Explorer on Windows.
858 menu.findItem(R.id.user_agent_internet_explorer_on_windows).setChecked(true);
859 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) { // Safari on macOS.
860 menu.findItem(R.id.user_agent_safari_on_macos).setChecked(true);
861 } else { // Custom user agent.
862 menu.findItem(R.id.user_agent_custom).setChecked(true);
865 // Instantiate the font size title and the selected font size menu item.
866 String fontSizeTitle;
867 MenuItem selectedFontSizeMenuItem;
869 // Prepare the font size title and current size menu item.
872 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
873 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
877 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
878 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
882 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
883 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
887 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
888 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
892 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
893 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
897 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
898 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
902 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
903 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
907 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
908 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
912 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
913 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
917 // Set the font size title and select the current size menu item.
918 fontSizeMenuItem.setTitle(fontSizeTitle);
919 selectedFontSizeMenuItem.setChecked(true);
921 // Run all the other default commands.
922 super.onPrepareOptionsMenu(menu);
929 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
930 @SuppressLint("SetJavaScriptEnabled")
931 public boolean onOptionsItemSelected(MenuItem menuItem) {
932 // Reenter full screen browsing mode if it was interrupted by the options menu. <https://redmine.stoutner.com/issues/389>
933 if (inFullScreenBrowsingMode) {
934 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
935 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
937 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
939 /* Hide the system bars.
940 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
941 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
942 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
943 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
945 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
946 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
949 // Get the selected menu item ID.
950 int menuItemId = menuItem.getItemId();
952 // Get a handle for the shared preferences.
953 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
955 // Get a handle for the cookie manager.
956 CookieManager cookieManager = CookieManager.getInstance();
958 // Run the commands that correlate to the selected menu item.
959 switch (menuItemId) {
960 case R.id.toggle_javascript:
961 // Toggle the JavaScript status.
962 currentWebView.getSettings().setJavaScriptEnabled(!currentWebView.getSettings().getJavaScriptEnabled());
964 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
965 updatePrivacyIcons(true);
967 // Display a `Snackbar`.
968 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScrip is enabled.
969 Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
970 } else if (cookieManager.acceptCookie()) { // JavaScript is disabled, but first-party cookies are enabled.
971 Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
972 } else { // Privacy mode.
973 Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
976 // Reload the current WebView.
977 currentWebView.reload();
979 // Consume the event.
982 case R.id.add_or_edit_domain:
983 if (currentWebView.getDomainSettingsApplied()) { // Edit the current domain settings.
984 // Reapply the domain settings on returning to `MainWebViewActivity`.
985 reapplyDomainSettingsOnRestart = true;
987 // Create an intent to launch the domains activity.
988 Intent domainsIntent = new Intent(this, DomainsActivity.class);
990 // Add the extra information to the intent.
991 domainsIntent.putExtra("load_domain", currentWebView.getDomainSettingsDatabaseId());
992 domainsIntent.putExtra("close_on_back", true);
993 domainsIntent.putExtra("current_url", currentWebView.getUrl());
995 // Get the current certificate.
996 SslCertificate sslCertificate = currentWebView.getCertificate();
998 // Check to see if the SSL certificate is populated.
999 if (sslCertificate != null) {
1000 // Extract the certificate to strings.
1001 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1002 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1003 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1004 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1005 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1006 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1007 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1008 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1010 // Add the certificate to the intent.
1011 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1012 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1013 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1014 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1015 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1016 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1017 domainsIntent.putExtra("ssl_start_date", startDateLong);
1018 domainsIntent.putExtra("ssl_end_date", endDateLong);
1021 // Check to see if the current IP addresses have been received.
1022 if (currentWebView.hasCurrentIpAddresses()) {
1023 // Add the current IP addresses to the intent.
1024 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1028 startActivity(domainsIntent);
1029 } else { // Add a new domain.
1030 // Apply the new domain settings on returning to `MainWebViewActivity`.
1031 reapplyDomainSettingsOnRestart = true;
1033 // Get the current domain
1034 Uri currentUri = Uri.parse(currentWebView.getUrl());
1035 String currentDomain = currentUri.getHost();
1037 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1038 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1040 // Create the domain and store the database ID.
1041 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1043 // Create an intent to launch the domains activity.
1044 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1046 // Add the extra information to the intent.
1047 domainsIntent.putExtra("load_domain", newDomainDatabaseId);
1048 domainsIntent.putExtra("close_on_back", true);
1049 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1051 // Get the current certificate.
1052 SslCertificate sslCertificate = currentWebView.getCertificate();
1054 // Check to see if the SSL certificate is populated.
1055 if (sslCertificate != null) {
1056 // Extract the certificate to strings.
1057 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1058 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1059 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1060 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1061 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1062 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1063 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1064 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1066 // Add the certificate to the intent.
1067 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1068 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1069 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1070 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1071 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1072 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1073 domainsIntent.putExtra("ssl_start_date", startDateLong);
1074 domainsIntent.putExtra("ssl_end_date", endDateLong);
1077 // Check to see if the current IP addresses have been received.
1078 if (currentWebView.hasCurrentIpAddresses()) {
1079 // Add the current IP addresses to the intent.
1080 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1084 startActivity(domainsIntent);
1087 // Consume the event.
1090 case R.id.toggle_first_party_cookies:
1091 // Switch the first-party cookie status.
1092 cookieManager.setAcceptCookie(!cookieManager.acceptCookie());
1094 // Store the first-party cookie status.
1095 currentWebView.setAcceptFirstPartyCookies(cookieManager.acceptCookie());
1097 // Update the menu checkbox.
1098 menuItem.setChecked(cookieManager.acceptCookie());
1100 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1101 updatePrivacyIcons(true);
1103 // Display a snackbar.
1104 if (cookieManager.acceptCookie()) { // First-party cookies are enabled.
1105 Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1106 } else if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is still enabled.
1107 Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1108 } else { // Privacy mode.
1109 Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1112 // Reload the current WebView.
1113 currentWebView.reload();
1115 // Consume the event.
1118 case R.id.toggle_third_party_cookies:
1119 if (Build.VERSION.SDK_INT >= 21) {
1120 // Switch the status of thirdPartyCookiesEnabled.
1121 cookieManager.setAcceptThirdPartyCookies(currentWebView, !cookieManager.acceptThirdPartyCookies(currentWebView));
1123 // Update the menu checkbox.
1124 menuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
1126 // Display a snackbar.
1127 if (cookieManager.acceptThirdPartyCookies(currentWebView)) {
1128 Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1130 Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1133 // Reload the current WebView.
1134 currentWebView.reload();
1135 } // Else do nothing because SDK < 21.
1137 // Consume the event.
1140 case R.id.toggle_dom_storage:
1141 // Toggle the status of domStorageEnabled.
1142 currentWebView.getSettings().setDomStorageEnabled(!currentWebView.getSettings().getDomStorageEnabled());
1144 // Update the menu checkbox.
1145 menuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1147 // Update the privacy icon. `true` refreshes the app bar icons.
1148 updatePrivacyIcons(true);
1150 // Display a snackbar.
1151 if (currentWebView.getSettings().getDomStorageEnabled()) {
1152 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1154 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1157 // Reload the current WebView.
1158 currentWebView.reload();
1160 // Consume the event.
1163 // Form data can be removed once the minimum API >= 26.
1164 case R.id.toggle_save_form_data:
1165 // Switch the status of saveFormDataEnabled.
1166 currentWebView.getSettings().setSaveFormData(!currentWebView.getSettings().getSaveFormData());
1168 // Update the menu checkbox.
1169 menuItem.setChecked(currentWebView.getSettings().getSaveFormData());
1171 // Display a snackbar.
1172 if (currentWebView.getSettings().getSaveFormData()) {
1173 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1175 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1178 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1179 updatePrivacyIcons(true);
1181 // Reload the current WebView.
1182 currentWebView.reload();
1184 // Consume the event.
1187 case R.id.clear_cookies:
1188 Snackbar.make(findViewById(R.id.webviewpager), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1189 .setAction(R.string.undo, v -> {
1190 // Do nothing because everything will be handled by `onDismissed()` below.
1192 .addCallback(new Snackbar.Callback() {
1193 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1195 public void onDismissed(Snackbar snackbar, int event) {
1196 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1197 // Delete the cookies, which command varies by SDK.
1198 if (Build.VERSION.SDK_INT < 21) {
1199 cookieManager.removeAllCookie();
1201 cookieManager.removeAllCookies(null);
1208 // Consume the event.
1211 case R.id.clear_dom_storage:
1212 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1213 .setAction(R.string.undo, v -> {
1214 // Do nothing because everything will be handled by `onDismissed()` below.
1216 .addCallback(new Snackbar.Callback() {
1217 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1219 public void onDismissed(Snackbar snackbar, int event) {
1220 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1221 // Delete the DOM Storage.
1222 WebStorage webStorage = WebStorage.getInstance();
1223 webStorage.deleteAllData();
1225 // Initialize a handler to manually delete the DOM storage files and directories.
1226 Handler deleteDomStorageHandler = new Handler();
1228 // Setup a runnable to manually delete the DOM storage files and directories.
1229 Runnable deleteDomStorageRunnable = () -> {
1231 // Get a handle for the runtime.
1232 Runtime runtime = Runtime.getRuntime();
1234 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
1235 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
1236 String privateDataDirectoryString = getApplicationInfo().dataDir;
1238 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1239 Process deleteLocalStorageProcess = runtime.exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1241 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1242 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1243 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1244 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1245 Process deleteDatabasesProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1247 // Wait for the processes to finish.
1248 deleteLocalStorageProcess.waitFor();
1249 deleteIndexProcess.waitFor();
1250 deleteQuotaManagerProcess.waitFor();
1251 deleteQuotaManagerJournalProcess.waitFor();
1252 deleteDatabasesProcess.waitFor();
1253 } catch (Exception exception) {
1254 // Do nothing if an error is thrown.
1258 // Manually delete the DOM storage files after 200 milliseconds.
1259 deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200);
1265 // Consume the event.
1268 // Form data can be remove once the minimum API >= 26.
1269 case R.id.clear_form_data:
1270 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1271 .setAction(R.string.undo, v -> {
1272 // Do nothing because everything will be handled by `onDismissed()` below.
1274 .addCallback(new Snackbar.Callback() {
1275 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1277 public void onDismissed(Snackbar snackbar, int event) {
1278 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1279 // Delete the form data.
1280 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1281 mainWebViewDatabase.clearFormData();
1287 // Consume the event.
1291 // Toggle the EasyList status.
1292 currentWebView.enableBlocklist(NestedScrollWebView.EASY_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST));
1294 // Update the menu checkbox.
1295 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST));
1297 // Reload the current WebView.
1298 currentWebView.reload();
1300 // Consume the event.
1303 case R.id.easyprivacy:
1304 // Toggle the EasyPrivacy status.
1305 currentWebView.enableBlocklist(NestedScrollWebView.EASY_PRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY));
1307 // Update the menu checkbox.
1308 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY));
1310 // Reload the current WebView.
1311 currentWebView.reload();
1313 // Consume the event.
1316 case R.id.fanboys_annoyance_list:
1317 // Toggle Fanboy's Annoyance List status.
1318 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1320 // Update the menu checkbox.
1321 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1323 // Update the staus of Fanboy's Social Blocking List.
1324 MenuItem fanboysSocialBlockingListMenuItem = optionsMenu.findItem(R.id.fanboys_social_blocking_list);
1325 fanboysSocialBlockingListMenuItem.setEnabled(!currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1327 // Reload the current WebView.
1328 currentWebView.reload();
1330 // Consume the event.
1333 case R.id.fanboys_social_blocking_list:
1334 // Toggle Fanboy's Social Blocking List status.
1335 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1337 // Update the menu checkbox.
1338 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1340 // Reload the current WebView.
1341 currentWebView.reload();
1343 // Consume the event.
1346 case R.id.ultraprivacy:
1347 // Toggle the UltraPrivacy status.
1348 currentWebView.enableBlocklist(NestedScrollWebView.ULTRA_PRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY));
1350 // Update the menu checkbox.
1351 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY));
1353 // Reload the current WebView.
1354 currentWebView.reload();
1356 // Consume the event.
1359 case R.id.block_all_third_party_requests:
1360 //Toggle the third-party requests blocker status.
1361 currentWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, !currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1363 // Update the menu checkbox.
1364 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1366 // Reload the current WebView.
1367 currentWebView.reload();
1369 // Consume the event.
1372 case R.id.user_agent_privacy_browser:
1373 // Update the user agent.
1374 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
1376 // Reload the current WebView.
1377 currentWebView.reload();
1379 // Consume the event.
1382 case R.id.user_agent_webview_default:
1383 // Update the user agent.
1384 currentWebView.getSettings().setUserAgentString("");
1386 // Reload the current WebView.
1387 currentWebView.reload();
1389 // Consume the event.
1392 case R.id.user_agent_firefox_on_android:
1393 // Update the user agent.
1394 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
1396 // Reload the current WebView.
1397 currentWebView.reload();
1399 // Consume the event.
1402 case R.id.user_agent_chrome_on_android:
1403 // Update the user agent.
1404 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
1406 // Reload the current WebView.
1407 currentWebView.reload();
1409 // Consume the event.
1412 case R.id.user_agent_safari_on_ios:
1413 // Update the user agent.
1414 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
1416 // Reload the current WebView.
1417 currentWebView.reload();
1419 // Consume the event.
1422 case R.id.user_agent_firefox_on_linux:
1423 // Update the user agent.
1424 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
1426 // Reload the current WebView.
1427 currentWebView.reload();
1429 // Consume the event.
1432 case R.id.user_agent_chromium_on_linux:
1433 // Update the user agent.
1434 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
1436 // Reload the current WebView.
1437 currentWebView.reload();
1439 // Consume the event.
1442 case R.id.user_agent_firefox_on_windows:
1443 // Update the user agent.
1444 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
1446 // Reload the current WebView.
1447 currentWebView.reload();
1449 // Consume the event.
1452 case R.id.user_agent_chrome_on_windows:
1453 // Update the user agent.
1454 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
1456 // Reload the current WebView.
1457 currentWebView.reload();
1459 // Consume the event.
1462 case R.id.user_agent_edge_on_windows:
1463 // Update the user agent.
1464 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
1466 // Reload the current WebView.
1467 currentWebView.reload();
1469 // Consume the event.
1472 case R.id.user_agent_internet_explorer_on_windows:
1473 // Update the user agent.
1474 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
1476 // Reload the current WebView.
1477 currentWebView.reload();
1479 // Consume the event.
1482 case R.id.user_agent_safari_on_macos:
1483 // Update the user agent.
1484 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
1486 // Reload the current WebView.
1487 currentWebView.reload();
1489 // Consume the event.
1492 case R.id.user_agent_custom:
1493 // Update the user agent.
1494 currentWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
1496 // Reload the current WebView.
1497 currentWebView.reload();
1499 // Consume the event.
1502 case R.id.font_size_twenty_five_percent:
1503 // Set the font size.
1504 currentWebView.getSettings().setTextZoom(25);
1506 // Consume the event.
1509 case R.id.font_size_fifty_percent:
1510 // Set the font size.
1511 currentWebView.getSettings().setTextZoom(50);
1513 // Consume the event.
1516 case R.id.font_size_seventy_five_percent:
1517 // Set the font size.
1518 currentWebView.getSettings().setTextZoom(75);
1520 // Consume the event.
1523 case R.id.font_size_one_hundred_percent:
1524 // Set the font size.
1525 currentWebView.getSettings().setTextZoom(100);
1527 // Consume the event.
1530 case R.id.font_size_one_hundred_twenty_five_percent:
1531 // Set the font size.
1532 currentWebView.getSettings().setTextZoom(125);
1534 // Consume the event.
1537 case R.id.font_size_one_hundred_fifty_percent:
1538 // Set the font size.
1539 currentWebView.getSettings().setTextZoom(150);
1541 // Consume the event.
1544 case R.id.font_size_one_hundred_seventy_five_percent:
1545 // Set the font size.
1546 currentWebView.getSettings().setTextZoom(175);
1548 // Consume the event.
1551 case R.id.font_size_two_hundred_percent:
1552 // Set the font size.
1553 currentWebView.getSettings().setTextZoom(200);
1555 // Consume the event.
1558 case R.id.swipe_to_refresh:
1559 // Toggle the stored status of swipe to refresh.
1560 currentWebView.setSwipeToRefresh(!currentWebView.getSwipeToRefresh());
1562 // Get a handle for the swipe refresh layout.
1563 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
1565 // Update the swipe refresh layout.
1566 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
1567 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
1568 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
1569 } else { // Swipe to refresh is disabled.
1570 // Disable the swipe refresh layout.
1571 swipeRefreshLayout.setEnabled(false);
1574 // Consume the event.
1577 case R.id.wide_viewport:
1578 // Toggle the viewport.
1579 currentWebView.getSettings().setUseWideViewPort(!currentWebView.getSettings().getUseWideViewPort());
1581 // Consume the event.
1584 case R.id.display_images:
1585 if (currentWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1586 // Disable loading of images.
1587 currentWebView.getSettings().setLoadsImagesAutomatically(false);
1589 // Reload the website to remove existing images.
1590 currentWebView.reload();
1591 } else { // Images are not currently loaded automatically.
1592 // Enable loading of images. Missing images will be loaded without the need for a reload.
1593 currentWebView.getSettings().setLoadsImagesAutomatically(true);
1596 // Consume the event.
1599 case R.id.night_mode:
1600 // Toggle night mode.
1601 currentWebView.setNightMode(!currentWebView.getNightMode());
1603 // Enable or disable JavaScript according to night mode, the global preference, and any domain settings.
1604 if (currentWebView.getNightMode()) { // Night mode is enabled, which requires JavaScript.
1605 // Enable JavaScript.
1606 currentWebView.getSettings().setJavaScriptEnabled(true);
1607 } else if (currentWebView.getDomainSettingsApplied()) { // Night mode is disabled and domain settings are applied. Set JavaScript according to the domain settings.
1608 // Apply the JavaScript preference that was stored the last time domain settings were loaded.
1609 currentWebView.getSettings().setJavaScriptEnabled(currentWebView.getDomainSettingsJavaScriptEnabled());
1610 } else { // Night mode is disabled and domain settings are not applied. Set JavaScript according to the global preference.
1611 // Apply the JavaScript preference.
1612 currentWebView.getSettings().setJavaScriptEnabled(sharedPreferences.getBoolean("javascript", false));
1615 // Update the privacy icons.
1616 updatePrivacyIcons(false);
1618 // Reload the website.
1619 currentWebView.reload();
1621 // Consume the event.
1624 case R.id.find_on_page:
1625 // Get a handle for the views.
1626 Toolbar toolbar = findViewById(R.id.toolbar);
1627 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
1628 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
1630 // Set the minimum height of the find on page linear layout to match the toolbar.
1631 findOnPageLinearLayout.setMinimumHeight(toolbar.getHeight());
1633 // Hide the toolbar.
1634 toolbar.setVisibility(View.GONE);
1636 // Show the find on page linear layout.
1637 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1639 // Display the keyboard. The app must wait 200 ms before running the command to work around a bug in Android.
1640 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1641 findOnPageEditText.postDelayed(() -> {
1642 // Set the focus on `findOnPageEditText`.
1643 findOnPageEditText.requestFocus();
1645 // Get a handle for the input method manager.
1646 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1648 // Remove the lint warning below that the input method manager might be null.
1649 assert inputMethodManager != null;
1651 // Display the keyboard. `0` sets no input flags.
1652 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1655 // Consume the event.
1659 // Get a print manager instance.
1660 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1662 // Remove the lint error below that print manager might be null.
1663 assert printManager != null;
1665 // Create a print document adapter from the current WebView.
1666 PrintDocumentAdapter printDocumentAdapter = currentWebView.createPrintDocumentAdapter();
1668 // Print the document.
1669 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1671 // Consume the event.
1674 case R.id.save_as_image:
1675 // Instantiate the save webpage image dialog.
1676 DialogFragment saveWebpageImageDialogFragment = new SaveWebpageImageDialog();
1678 // Show the save webpage image dialog.
1679 saveWebpageImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_as_image));
1681 // Consume the event.
1684 case R.id.add_to_homescreen:
1685 // Instantiate the create home screen shortcut dialog.
1686 DialogFragment createHomeScreenShortcutDialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView.getTitle(), currentWebView.getUrl(),
1687 currentWebView.getFavoriteOrDefaultIcon());
1689 // Show the create home screen shortcut dialog.
1690 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
1692 // Consume the event.
1695 case R.id.view_source:
1696 // Create an intent to launch the view source activity.
1697 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
1699 // Add the variables to the intent.
1700 viewSourceIntent.putExtra("user_agent", currentWebView.getSettings().getUserAgentString());
1701 viewSourceIntent.putExtra("current_url", currentWebView.getUrl());
1704 startActivity(viewSourceIntent);
1706 // Consume the event.
1709 case R.id.share_url:
1710 // Setup the share string.
1711 String shareString = currentWebView.getTitle() + " – " + currentWebView.getUrl();
1713 // Create the share intent.
1714 Intent shareIntent = new Intent(Intent.ACTION_SEND);
1715 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1716 shareIntent.setType("text/plain");
1719 startActivity(Intent.createChooser(shareIntent, getString(R.string.share_url)));
1721 // Consume the event.
1724 case R.id.open_with_app:
1725 // Open the URL with an outside app.
1726 openWithApp(currentWebView.getUrl());
1728 // Consume the event.
1731 case R.id.open_with_browser:
1732 // Open the URL with an outside browser.
1733 openWithBrowser(currentWebView.getUrl());
1735 // Consume the event.
1738 case R.id.proxy_through_orbot:
1739 // Toggle the proxy through Orbot variable.
1740 proxyThroughOrbot = !proxyThroughOrbot;
1742 // Apply the proxy through Orbot settings.
1743 applyProxyThroughOrbot(true);
1745 // Consume the event.
1749 if (menuItem.getTitle().equals(getString(R.string.refresh))) { // The refresh button was pushed.
1750 // Reload the current WebView.
1751 currentWebView.reload();
1752 } else { // The stop button was pushed.
1753 // Stop the loading of the WebView.
1754 currentWebView.stopLoading();
1757 // Consume the event.
1760 case R.id.ad_consent:
1761 // Instantiate the ad consent dialog.
1762 DialogFragment adConsentDialogFragment = new AdConsentDialog();
1764 // Display the ad consent dialog.
1765 adConsentDialogFragment.show(getSupportFragmentManager(), getString(R.string.ad_consent));
1767 // Consume the event.
1771 // Don't consume the event.
1772 return super.onOptionsItemSelected(menuItem);
1776 // removeAllCookies is deprecated, but it is required for API < 21.
1778 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1779 // Get the menu item ID.
1780 int menuItemId = menuItem.getItemId();
1782 // Get a handle for the shared preferences.
1783 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1785 // Run the commands that correspond to the selected menu item.
1786 switch (menuItemId) {
1787 case R.id.clear_and_exit:
1788 // Clear and exit Privacy Browser.
1793 // Select the homepage based on the proxy through Orbot status.
1794 if (proxyThroughOrbot) {
1795 // Load the Tor homepage.
1796 loadUrl(sharedPreferences.getString("tor_homepage", getString(R.string.tor_homepage_default_value)));
1798 // Load the normal homepage.
1799 loadUrl(sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
1804 if (currentWebView.canGoBack()) {
1805 // Reset the current domain name so that navigation works if third-party requests are blocked.
1806 currentWebView.resetCurrentDomainName();
1808 // Set navigating history so that the domain settings are applied when the new URL is loaded.
1809 currentWebView.setNavigatingHistory(true);
1811 // Load the previous website in the history.
1812 currentWebView.goBack();
1817 if (currentWebView.canGoForward()) {
1818 // Reset the current domain name so that navigation works if third-party requests are blocked.
1819 currentWebView.resetCurrentDomainName();
1821 // Set navigating history so that the domain settings are applied when the new URL is loaded.
1822 currentWebView.setNavigatingHistory(true);
1824 // Load the next website in the history.
1825 currentWebView.goForward();
1830 // Instantiate the URL history dialog.
1831 DialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(currentWebView.getWebViewFragmentId());
1833 // Show the URL history dialog.
1834 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
1838 // Populate the resource requests.
1839 RequestsActivity.resourceRequests = currentWebView.getResourceRequests();
1841 // Create an intent to launch the Requests activity.
1842 Intent requestsIntent = new Intent(this, RequestsActivity.class);
1844 // Add the block third-party requests status to the intent.
1845 requestsIntent.putExtra("block_all_third_party_requests", currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1848 startActivity(requestsIntent);
1851 case R.id.downloads:
1852 // Launch the system Download Manager.
1853 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1855 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1856 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1858 startActivity(downloadManagerIntent);
1862 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
1863 reapplyDomainSettingsOnRestart = true;
1865 // Launch the domains activity.
1866 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1868 // Add the extra information to the intent.
1869 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1871 // Get the current certificate.
1872 SslCertificate sslCertificate = currentWebView.getCertificate();
1874 // Check to see if the SSL certificate is populated.
1875 if (sslCertificate != null) {
1876 // Extract the certificate to strings.
1877 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1878 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1879 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1880 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1881 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1882 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1883 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1884 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1886 // Add the certificate to the intent.
1887 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1888 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1889 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1890 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1891 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1892 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1893 domainsIntent.putExtra("ssl_start_date", startDateLong);
1894 domainsIntent.putExtra("ssl_end_date", endDateLong);
1897 // Check to see if the current IP addresses have been received.
1898 if (currentWebView.hasCurrentIpAddresses()) {
1899 // Add the current IP addresses to the intent.
1900 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1904 startActivity(domainsIntent);
1908 // Set the flag to reapply app settings on restart when returning from Settings.
1909 reapplyAppSettingsOnRestart = true;
1911 // Set the flag to reapply the domain settings on restart when returning from Settings.
1912 reapplyDomainSettingsOnRestart = true;
1914 // Launch the settings activity.
1915 Intent settingsIntent = new Intent(this, SettingsActivity.class);
1916 startActivity(settingsIntent);
1919 case R.id.import_export:
1920 // Launch the import/export activity.
1921 Intent importExportIntent = new Intent (this, ImportExportActivity.class);
1922 startActivity(importExportIntent);
1926 // Launch the logcat activity.
1927 Intent logcatIntent = new Intent(this, LogcatActivity.class);
1928 startActivity(logcatIntent);
1932 // Launch `GuideActivity`.
1933 Intent guideIntent = new Intent(this, GuideActivity.class);
1934 startActivity(guideIntent);
1938 // Create an intent to launch the about activity.
1939 Intent aboutIntent = new Intent(this, AboutActivity.class);
1941 // Create a string array for the blocklist versions.
1942 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],
1943 ultraPrivacy.get(0).get(0)[0]};
1945 // Add the blocklist versions to the intent.
1946 aboutIntent.putExtra("blocklist_versions", blocklistVersions);
1949 startActivity(aboutIntent);
1953 // Get a handle for the drawer layout.
1954 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
1956 // Close the navigation drawer.
1957 drawerLayout.closeDrawer(GravityCompat.START);
1962 public void onPostCreate(Bundle savedInstanceState) {
1963 // Run the default commands.
1964 super.onPostCreate(savedInstanceState);
1966 // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished. This creates the navigation drawer icon.
1967 actionBarDrawerToggle.syncState();
1971 public void onConfigurationChanged(Configuration newConfig) {
1972 // Run the default commands.
1973 super.onConfigurationChanged(newConfig);
1975 // Get the status bar pixel size.
1976 int statusBarResourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
1977 int statusBarPixelSize = getResources().getDimensionPixelSize(statusBarResourceId);
1979 // Get the resource density.
1980 float screenDensity = getResources().getDisplayMetrics().density;
1982 // Recalculate the drawer header padding.
1983 drawerHeaderPaddingLeftAndRight = (int) (15 * screenDensity);
1984 drawerHeaderPaddingTop = statusBarPixelSize + (int) (4 * screenDensity);
1985 drawerHeaderPaddingBottom = (int) (8 * screenDensity);
1987 // Reload the ad for the free flavor if not in full screen mode.
1988 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
1989 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1990 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
1993 // `invalidateOptionsMenu` should recalculate the number of action buttons from the menu to display on the app bar, but it doesn't because of the this bug:
1994 // https://code.google.com/p/android/issues/detail?id=20493#c8
1995 // ActivityCompat.invalidateOptionsMenu(this);
1999 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2000 // Store the hit test result.
2001 final WebView.HitTestResult hitTestResult = currentWebView.getHitTestResult();
2003 // Create the URL strings.
2004 final String imageUrl;
2005 final String linkUrl;
2007 // Get handles for the system managers.
2008 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2009 FragmentManager fragmentManager = getSupportFragmentManager();
2010 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2012 // Remove the lint errors below that the clipboard manager might be null.
2013 assert clipboardManager != null;
2015 // Process the link according to the type.
2016 switch (hitTestResult.getType()) {
2017 // `SRC_ANCHOR_TYPE` is a link.
2018 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2019 // Get the target URL.
2020 linkUrl = hitTestResult.getExtra();
2022 // Set the target URL as the title of the `ContextMenu`.
2023 menu.setHeaderTitle(linkUrl);
2025 // Add an Open in New Tab entry.
2026 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2027 // Load the link URL in a new tab.
2032 // Add an Open with App entry.
2033 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2034 openWithApp(linkUrl);
2038 // Add an Open with Browser entry.
2039 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2040 openWithBrowser(linkUrl);
2044 // Add a Copy URL entry.
2045 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2046 // Save the link URL in a `ClipData`.
2047 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2049 // Set the `ClipData` as the clipboard's primary clip.
2050 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2054 // Add a Download URL entry.
2055 menu.add(R.string.download_url).setOnMenuItemClickListener((MenuItem item) -> {
2056 // Check if the download should be processed by an external app.
2057 if (sharedPreferences.getBoolean("download_with_external_app", false)) { // Download with an external app.
2058 openUrlWithExternalApp(linkUrl);
2059 } else { // Download with Android's download manager.
2060 // Check to see if the storage permission has already been granted.
2061 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission needs to be requested.
2062 // Store the variables for future use by `onRequestPermissionsResult()`.
2063 downloadUrl = linkUrl;
2064 downloadContentDisposition = "none";
2065 downloadContentLength = -1;
2067 // Show a dialog if the user has previously denied the permission.
2068 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2069 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
2070 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
2072 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
2073 downloadLocationPermissionDialogFragment.show(fragmentManager, getString(R.string.download_location));
2074 } else { // Show the permission request directly.
2075 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
2076 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2078 } else { // The storage permission has already been granted.
2079 // Get a handle for the download file alert dialog.
2080 DialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(linkUrl, "none", -1);
2082 // Show the download file alert dialog.
2083 downloadFileDialogFragment.show(fragmentManager, getString(R.string.download));
2089 // Add a Cancel entry, which by default closes the context menu.
2090 menu.add(R.string.cancel);
2093 case WebView.HitTestResult.EMAIL_TYPE:
2094 // Get the target URL.
2095 linkUrl = hitTestResult.getExtra();
2097 // Set the target URL as the title of the `ContextMenu`.
2098 menu.setHeaderTitle(linkUrl);
2100 // Add a Write Email entry.
2101 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2102 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2103 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2105 // Parse the url and set it as the data for the `Intent`.
2106 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2108 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2109 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2112 startActivity(emailIntent);
2116 // Add a Copy Email Address entry.
2117 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2118 // Save the email address in a `ClipData`.
2119 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2121 // Set the `ClipData` as the clipboard's primary clip.
2122 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2126 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2127 menu.add(R.string.cancel);
2130 // `IMAGE_TYPE` is an image. `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link. Privacy Browser processes them the same.
2131 case WebView.HitTestResult.IMAGE_TYPE:
2132 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2133 // Get the image URL.
2134 imageUrl = hitTestResult.getExtra();
2136 // Set the image URL as the title of the context menu.
2137 menu.setHeaderTitle(imageUrl);
2139 // Add an Open in New Tab entry.
2140 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2141 // Load the image URL in a new tab.
2142 addNewTab(imageUrl);
2146 // Add a View Image entry.
2147 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2152 // Add a `Download Image` entry.
2153 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2154 // Check if the download should be processed by an external app.
2155 if (sharedPreferences.getBoolean("download_with_external_app", false)) { // Download with an external app.
2156 openUrlWithExternalApp(imageUrl);
2157 } else { // Download with Android's download manager.
2158 // Check to see if the storage permission has already been granted.
2159 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission needs to be requested.
2160 // Store the image URL for use by `onRequestPermissionResult()`.
2161 downloadImageUrl = imageUrl;
2163 // Show a dialog if the user has previously denied the permission.
2164 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2165 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2166 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2168 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
2169 downloadLocationPermissionDialogFragment.show(fragmentManager, getString(R.string.download_location));
2170 } else { // Show the permission request directly.
2171 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
2172 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2174 } else { // The storage permission has already been granted.
2175 // Get a handle for the download image alert dialog.
2176 DialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2178 // Show the download image alert dialog.
2179 downloadImageDialogFragment.show(fragmentManager, getString(R.string.download));
2185 // Add a `Copy URL` entry.
2186 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2187 // Save the image URL in a `ClipData`.
2188 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2190 // Set the `ClipData` as the clipboard's primary clip.
2191 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2195 // Add an Open with App entry.
2196 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2197 openWithApp(imageUrl);
2201 // Add an Open with Browser entry.
2202 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2203 openWithBrowser(imageUrl);
2207 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2208 menu.add(R.string.cancel);
2214 public void onCreateBookmark(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2215 // Get a handle for the bookmarks list view.
2216 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2218 // Get the views from the dialog fragment.
2219 EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
2220 EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
2222 // Extract the strings from the edit texts.
2223 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2224 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2226 // Create a favorite icon byte array output stream.
2227 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2229 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2230 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2232 // Convert the favorite icon byte array stream to a byte array.
2233 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2235 // Display the new bookmark below the current items in the (0 indexed) list.
2236 int newBookmarkDisplayOrder = bookmarksListView.getCount();
2238 // Create the bookmark.
2239 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2241 // Update the bookmarks cursor with the current contents of this folder.
2242 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2244 // Update the list view.
2245 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2247 // Scroll to the new bookmark.
2248 bookmarksListView.setSelection(newBookmarkDisplayOrder);
2252 public void onCreateBookmarkFolder(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2253 // Get a handle for the bookmarks list view.
2254 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2256 // Get handles for the views in the dialog fragment.
2257 EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
2258 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
2259 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
2261 // Get new folder name string.
2262 String folderNameString = createFolderNameEditText.getText().toString();
2264 // Create a folder icon bitmap.
2265 Bitmap folderIconBitmap;
2267 // Set the folder icon bitmap according to the dialog.
2268 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
2269 // Get the default folder icon drawable.
2270 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2272 // Convert the folder icon drawable to a bitmap drawable.
2273 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2275 // Convert the folder icon bitmap drawable to a bitmap.
2276 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2277 } else { // Use the WebView favorite icon.
2278 // Copy the favorite icon bitmap to the folder icon bitmap.
2279 folderIconBitmap = favoriteIconBitmap;
2282 // Create a folder icon byte array output stream.
2283 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2285 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2286 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2288 // Convert the folder icon byte array stream to a byte array.
2289 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2291 // Move all the bookmarks down one in the display order.
2292 for (int i = 0; i < bookmarksListView.getCount(); i++) {
2293 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2294 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2297 // Create the folder, which will be placed at the top of the `ListView`.
2298 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2300 // Update the bookmarks cursor with the current contents of this folder.
2301 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2303 // Update the `ListView`.
2304 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2306 // Scroll to the new folder.
2307 bookmarksListView.setSelection(0);
2311 public void onSaveBookmark(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, Bitmap favoriteIconBitmap) {
2312 // Get handles for the views from `dialogFragment`.
2313 EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
2314 EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
2315 RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
2317 // Store the bookmark strings.
2318 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
2319 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
2321 // Update the bookmark.
2322 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
2323 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
2324 } else { // Update the bookmark using the `WebView` favorite icon.
2325 // Create a favorite icon byte array output stream.
2326 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2328 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2329 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
2331 // Convert the favorite icon byte array stream to a byte array.
2332 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
2334 // Update the bookmark and the favorite icon.
2335 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
2338 // Update the bookmarks cursor with the current contents of this folder.
2339 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2341 // Update the list view.
2342 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2346 public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId, Bitmap favoriteIconBitmap) {
2347 // Get handles for the views from `dialogFragment`.
2348 EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
2349 RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
2350 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
2351 ImageView defaultFolderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
2353 // Get the new folder name.
2354 String newFolderNameString = editFolderNameEditText.getText().toString();
2356 // Check if the favorite icon has changed.
2357 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
2358 // Update the name in the database.
2359 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2360 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
2361 // Create the new folder icon Bitmap.
2362 Bitmap folderIconBitmap;
2364 // Populate the new folder icon bitmap.
2365 if (defaultFolderIconRadioButton.isChecked()) {
2366 // Get the default folder icon drawable.
2367 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2369 // Convert the folder icon drawable to a bitmap drawable.
2370 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2372 // Convert the folder icon bitmap drawable to a bitmap.
2373 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2374 } else { // Use the `WebView` favorite icon.
2375 // Copy the favorite icon bitmap to the folder icon bitmap.
2376 folderIconBitmap = favoriteIconBitmap;
2379 // Create a folder icon byte array output stream.
2380 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2382 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2383 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2385 // Convert the folder icon byte array stream to a byte array.
2386 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2388 // Update the folder icon in the database.
2389 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, newFolderIconByteArray);
2390 } else { // The folder icon and the name have changed.
2391 // Get the new folder icon `Bitmap`.
2392 Bitmap folderIconBitmap;
2393 if (defaultFolderIconRadioButton.isChecked()) {
2394 // Get the default folder icon drawable.
2395 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2397 // Convert the folder icon drawable to a bitmap drawable.
2398 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2400 // Convert the folder icon bitmap drawable to a bitmap.
2401 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2402 } else { // Use the `WebView` favorite icon.
2403 // Copy the favorite icon bitmap to the folder icon bitmap.
2404 folderIconBitmap = favoriteIconBitmap;
2407 // Create a folder icon byte array output stream.
2408 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2410 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2411 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2413 // Convert the folder icon byte array stream to a byte array.
2414 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2416 // Update the folder name and icon in the database.
2417 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, newFolderIconByteArray);
2420 // Update the bookmarks cursor with the current contents of this folder.
2421 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2423 // Update the `ListView`.
2424 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2428 public void onCloseDownloadLocationPermissionDialog(int downloadType) {
2429 switch (downloadType) {
2430 case DownloadLocationPermissionDialog.DOWNLOAD_FILE:
2431 // Request the WRITE_EXTERNAL_STORAGE permission with a file request code.
2432 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2435 case DownloadLocationPermissionDialog.DOWNLOAD_IMAGE:
2436 // Request the WRITE_EXTERNAL_STORAGE permission with an image request code.
2437 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2443 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
2444 // Get a handle for the fragment manager.
2445 FragmentManager fragmentManager = getSupportFragmentManager();
2447 switch (requestCode) {
2448 case DOWNLOAD_FILE_REQUEST_CODE:
2449 // Show the download file alert dialog. When the dialog closes, the correct command will be used based on the permission status.
2450 DialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(downloadUrl, downloadContentDisposition, downloadContentLength);
2452 // On API 23, displaying the fragment must be delayed or the app will crash.
2453 if (Build.VERSION.SDK_INT == 23) {
2454 new Handler().postDelayed(() -> downloadFileDialogFragment.show(fragmentManager, getString(R.string.download)), 500);
2456 downloadFileDialogFragment.show(fragmentManager, getString(R.string.download));
2459 // Reset the download variables.
2461 downloadContentDisposition = "";
2462 downloadContentLength = 0;
2465 case DOWNLOAD_IMAGE_REQUEST_CODE:
2466 // Show the download image alert dialog. When the dialog closes, the correct command will be used based on the permission status.
2467 DialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(downloadImageUrl);
2469 // On API 23, displaying the fragment must be delayed or the app will crash.
2470 if (Build.VERSION.SDK_INT == 23) {
2471 new Handler().postDelayed(() -> downloadImageDialogFragment.show(fragmentManager, getString(R.string.download)), 500);
2473 downloadImageDialogFragment.show(fragmentManager, getString(R.string.download));
2476 // Reset the image URL variable.
2477 downloadImageUrl = "";
2480 case SAVE_WEBPAGE_IMAGE_REQUEST_CODE:
2481 // Check to see if the storage permission was granted. If the dialog was canceled the grant result will be empty.
2482 if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) { // The storage permission was granted.
2483 // Save the webpage image.
2484 new SaveWebpageImage(this, currentWebView).execute(saveWebsiteImageFilePath);
2485 } else { // The storage permission was not granted.
2486 // Display an error snackbar.
2487 Snackbar.make(currentWebView, getString(R.string.cannot_use_location), Snackbar.LENGTH_LONG).show();
2490 // Reset the save website image file path.
2491 saveWebsiteImageFilePath = "";
2497 public void onDownloadImage(DialogFragment dialogFragment, String imageUrl) {
2498 // Download the image if it has an HTTP or HTTPS URI.
2499 if (imageUrl.startsWith("http")) {
2500 // Get a handle for the system `DOWNLOAD_SERVICE`.
2501 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2503 // Parse `imageUrl`.
2504 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
2506 // Get a handle for the cookie manager.
2507 CookieManager cookieManager = CookieManager.getInstance();
2509 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
2510 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2511 if (cookieManager.acceptCookie()) {
2512 // Get the cookies for `imageUrl`.
2513 String cookies = cookieManager.getCookie(imageUrl);
2515 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2516 downloadRequest.addRequestHeader("Cookie", cookies);
2519 // Get the file name from the dialog fragment.
2520 EditText downloadImageNameEditText = dialogFragment.getDialog().findViewById(R.id.download_image_name);
2521 String imageName = downloadImageNameEditText.getText().toString();
2523 // Specify the download location.
2524 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
2525 // Download to the public download directory.
2526 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, imageName);
2527 } else { // External write permission denied.
2528 // Download to the app's external download directory.
2529 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, imageName);
2532 // Allow `MediaScanner` to index the download if it is a media file.
2533 downloadRequest.allowScanningByMediaScanner();
2535 // Add the URL as the description for the download.
2536 downloadRequest.setDescription(imageUrl);
2538 // Show the download notification after the download is completed.
2539 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2541 // Remove the lint warning below that `downloadManager` might be `null`.
2542 assert downloadManager != null;
2544 // Initiate the download.
2545 downloadManager.enqueue(downloadRequest);
2546 } else { // The image is not an HTTP or HTTPS URI.
2547 Snackbar.make(currentWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
2552 public void onDownloadFile(DialogFragment dialogFragment, String downloadUrl) {
2553 // Download the file if it has an HTTP or HTTPS URI.
2554 if (downloadUrl.startsWith("http")) {
2555 // Get a handle for the system `DOWNLOAD_SERVICE`.
2556 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2558 // Parse `downloadUrl`.
2559 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
2561 // Get a handle for the cookie manager.
2562 CookieManager cookieManager = CookieManager.getInstance();
2564 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
2565 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2566 if (cookieManager.acceptCookie()) {
2567 // Get the cookies for `downloadUrl`.
2568 String cookies = cookieManager.getCookie(downloadUrl);
2570 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2571 downloadRequest.addRequestHeader("Cookie", cookies);
2574 // Get the file name from the dialog fragment.
2575 EditText downloadFileNameEditText = dialogFragment.getDialog().findViewById(R.id.download_file_name);
2576 String fileName = downloadFileNameEditText.getText().toString();
2578 // Specify the download location.
2579 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
2580 // Download to the public download directory.
2581 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
2582 } else { // External write permission denied.
2583 // Download to the app's external download directory.
2584 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, fileName);
2587 // Allow `MediaScanner` to index the download if it is a media file.
2588 downloadRequest.allowScanningByMediaScanner();
2590 // Add the URL as the description for the download.
2591 downloadRequest.setDescription(downloadUrl);
2593 // Show the download notification after the download is completed.
2594 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2596 // Remove the lint warning below that `downloadManager` might be `null`.
2597 assert downloadManager != null;
2599 // Initiate the download.
2600 downloadManager.enqueue(downloadRequest);
2601 } else { // The download is not an HTTP or HTTPS URI.
2602 Snackbar.make(currentWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
2606 // Override `onBackPressed` to handle the navigation drawer and and the WebView.
2608 public void onBackPressed() {
2609 // Get a handle for the drawer layout and the tab layout.
2610 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
2611 TabLayout tabLayout = findViewById(R.id.tablayout);
2613 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
2614 // Close the navigation drawer.
2615 drawerLayout.closeDrawer(GravityCompat.START);
2616 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
2617 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
2618 // close the bookmarks drawer.
2619 drawerLayout.closeDrawer(GravityCompat.END);
2620 } else { // A subfolder is displayed.
2621 // Place the former parent folder in `currentFolder`.
2622 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolderName(currentBookmarksFolder);
2624 // Load the new folder.
2625 loadBookmarksFolder();
2627 } else if (currentWebView.canGoBack()) { // There is at least one item in the current WebView history.
2628 // Reset the current domain name so that navigation works if third-party requests are blocked.
2629 currentWebView.resetCurrentDomainName();
2631 // Set navigating history so that the domain settings are applied when the new URL is loaded.
2632 currentWebView.setNavigatingHistory(true);
2635 currentWebView.goBack();
2636 } else if (tabLayout.getTabCount() > 1) { // There are at least two tabs.
2637 // Close the current tab.
2639 } else { // There isn't anything to do in Privacy Browser.
2640 // Run the default commands.
2641 super.onBackPressed();
2643 // Manually kill Privacy Browser. Otherwise, it is glitchy when restarted.
2648 // Process the results of a file browse.
2650 public void onActivityResult(int requestCode, int resultCode, Intent data) {
2651 // Run the commands that correlate to the specified request code.
2652 switch (requestCode) {
2653 case FILE_UPLOAD_REQUEST_CODE:
2654 // File uploads only work on API >= 21.
2655 if (Build.VERSION.SDK_INT >= 21) {
2656 // Pass the file to the WebView.
2657 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
2661 case BROWSE_SAVE_WEBPAGE_IMAGE_REQUEST_CODE:
2662 // Don't do anything if the user pressed back from the file picker.
2663 if (resultCode == Activity.RESULT_OK) {
2664 // Get a handle for the save dialog fragment.
2665 DialogFragment saveWebpageImageDialogFragment= (DialogFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.save_as_image));
2667 // Only update the file name if the dialog still exists.
2668 if (saveWebpageImageDialogFragment != null) {
2669 // Get a handle for the save webpage image dialog.
2670 Dialog saveWebpageImageDialog = saveWebpageImageDialogFragment.getDialog();
2672 // Get a handle for the file name edit text.
2673 EditText fileNameEditText = saveWebpageImageDialog.findViewById(R.id.file_name_edittext);
2675 // Instantiate the file name helper.
2676 FileNameHelper fileNameHelper = new FileNameHelper();
2678 // Convert the file name URI to a file name path.
2679 String fileNamePath = fileNameHelper.convertUriToFileNamePath(data.getData());
2681 // Set the file name path as the text of the file name edit text.
2682 fileNameEditText.setText(fileNamePath);
2689 private void loadUrlFromTextBox() {
2690 // Get a handle for the URL edit text.
2691 EditText urlEditText = findViewById(R.id.url_edittext);
2693 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
2694 String unformattedUrlString = urlEditText.getText().toString().trim();
2696 // Initialize the formatted URL string.
2699 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
2700 if (unformattedUrlString.startsWith("content://")) { // This is a Content URL.
2701 // Load the entire content URL.
2702 url = unformattedUrlString;
2703 } else if (Patterns.WEB_URL.matcher(unformattedUrlString).matches() || unformattedUrlString.startsWith("http://") || unformattedUrlString.startsWith("https://") ||
2704 unformattedUrlString.startsWith("file://")) { // This is a standard URL.
2705 // Add `https://` at the beginning if there is no protocol. Otherwise the app will segfault.
2706 if (!unformattedUrlString.startsWith("http") && !unformattedUrlString.startsWith("file://") && !unformattedUrlString.startsWith("content://")) {
2707 unformattedUrlString = "https://" + unformattedUrlString;
2710 // Initialize `unformattedUrl`.
2711 URL unformattedUrl = null;
2713 // Convert `unformattedUrlString` to a `URL`, then to a `URI`, and then back to a `String`, which sanitizes the input and adds in any missing components.
2715 unformattedUrl = new URL(unformattedUrlString);
2716 } catch (MalformedURLException e) {
2717 e.printStackTrace();
2720 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2721 String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2722 String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2723 String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2724 String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2725 String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2728 Uri.Builder uri = new Uri.Builder();
2729 uri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2731 // Decode the URI as a UTF-8 string in.
2733 url = URLDecoder.decode(uri.build().toString(), "UTF-8");
2734 } catch (UnsupportedEncodingException exception) {
2735 // Do nothing. The formatted URL string will remain blank.
2737 } else if (!unformattedUrlString.isEmpty()){ // This is not a URL, but rather a search string.
2738 // Create an encoded URL String.
2739 String encodedUrlString;
2741 // Sanitize the search input.
2743 encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2744 } catch (UnsupportedEncodingException exception) {
2745 encodedUrlString = "";
2748 // Add the base search URL.
2749 url = searchURL + encodedUrlString;
2752 // 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.
2753 urlEditText.clearFocus();
2759 private void loadUrl(String url) {
2760 // Sanitize the URL.
2761 url = sanitizeUrl(url);
2763 // Apply the domain settings.
2764 applyDomainSettings(currentWebView, url, true, false);
2767 currentWebView.loadUrl(url, customHeaders);
2770 public void findPreviousOnPage(View view) {
2771 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
2772 currentWebView.findNext(false);
2775 public void findNextOnPage(View view) {
2776 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2777 currentWebView.findNext(true);
2780 public void closeFindOnPage(View view) {
2781 // Get a handle for the views.
2782 Toolbar toolbar = findViewById(R.id.toolbar);
2783 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
2784 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
2786 // Delete the contents of `find_on_page_edittext`.
2787 findOnPageEditText.setText(null);
2789 // Clear the highlighted phrases if the WebView is not null.
2790 if (currentWebView != null) {
2791 currentWebView.clearMatches();
2794 // Hide the find on page linear layout.
2795 findOnPageLinearLayout.setVisibility(View.GONE);
2797 // Show the toolbar.
2798 toolbar.setVisibility(View.VISIBLE);
2800 // Get a handle for the input method manager.
2801 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
2803 // Remove the lint warning below that the input method manager might be null.
2804 assert inputMethodManager != null;
2806 // Hide the keyboard.
2807 inputMethodManager.hideSoftInputFromWindow(toolbar.getWindowToken(), 0);
2811 public void onSaveWebpageImage(DialogFragment dialogFragment) {
2812 // Get a handle for the file name edit text.
2813 EditText fileNameEditText = dialogFragment.getDialog().findViewById(R.id.file_name_edittext);
2815 // Get the file path string.
2816 saveWebsiteImageFilePath = fileNameEditText.getText().toString();
2818 // Check to see if the storage permission is needed.
2819 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // The storage permission has been granted.
2820 // Save the webpage image.
2821 new SaveWebpageImage(this, currentWebView).execute(saveWebsiteImageFilePath);
2822 } else { // The storage permission has not been granted.
2823 // Get the external private directory `File`.
2824 File externalPrivateDirectoryFile = getExternalFilesDir(null);
2826 // Remove the incorrect lint error below that the file might be null.
2827 assert externalPrivateDirectoryFile != null;
2829 // Get the external private directory string.
2830 String externalPrivateDirectory = externalPrivateDirectoryFile.toString();
2832 // Check to see if the file path is in the external private directory.
2833 if (saveWebsiteImageFilePath.startsWith(externalPrivateDirectory)) { // The file path is in the external private directory.
2834 // Save the webpage image.
2835 new SaveWebpageImage(this, currentWebView).execute(saveWebsiteImageFilePath);
2836 } else { // The file path is in a public directory.
2837 // Check if the user has previously denied the storage permission.
2838 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2839 // Instantiate the storage permission alert dialog.
2840 DialogFragment storagePermissionDialogFragment = new StoragePermissionDialog();
2842 // Show the storage permission alert dialog. The permission will be requested when the dialog is closed.
2843 storagePermissionDialogFragment.show(getSupportFragmentManager(), getString(R.string.storage_permission));
2844 } else { // Show the permission request directly.
2845 // Request the write external storage permission. The webpage image will be saved when it finishes.
2846 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, SAVE_WEBPAGE_IMAGE_REQUEST_CODE);
2853 public void onCloseStoragePermissionDialog() {
2854 // Request the write external storage permission. The webpage image will be saved when it finishes.
2855 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, SAVE_WEBPAGE_IMAGE_REQUEST_CODE);
2858 private void applyAppSettings() {
2859 // Initialize the app if this is the first run. This is done here instead of in `onCreate()` to shorten the time that an unthemed background is displayed on app startup.
2860 if (webViewDefaultUserAgent == null) {
2864 // Get a handle for the shared preferences.
2865 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2867 // Store the values from the shared preferences in variables.
2868 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
2869 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
2870 sanitizeGoogleAnalytics = sharedPreferences.getBoolean("google_analytics", true);
2871 sanitizeFacebookClickIds = sharedPreferences.getBoolean("facebook_click_ids", true);
2872 sanitizeTwitterAmpRedirects = sharedPreferences.getBoolean("twitter_amp_redirects", true);
2873 proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
2874 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
2875 hideAppBar = sharedPreferences.getBoolean("hide_app_bar", true);
2876 scrollAppBar = sharedPreferences.getBoolean("scroll_app_bar", true);
2878 // Get handles for the views that need to be modified.
2879 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
2880 AppBarLayout appBarLayout = findViewById(R.id.appbar_layout);
2881 ActionBar actionBar = getSupportActionBar();
2882 Toolbar toolbar = findViewById(R.id.toolbar);
2883 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
2884 LinearLayout tabsLinearLayout = findViewById(R.id.tabs_linearlayout);
2885 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
2887 // Remove the incorrect lint warning below that the action bar might be null.
2888 assert actionBar != null;
2890 // Apply the proxy through Orbot settings.
2891 applyProxyThroughOrbot(false);
2893 // Set Do Not Track status.
2894 if (doNotTrackEnabled) {
2895 customHeaders.put("DNT", "1");
2897 customHeaders.remove("DNT");
2900 // Get the current layout parameters. Using coordinator layout parameters allows the `setBehavior()` command and using app bar layout parameters allows the `setScrollFlags()` command.
2901 CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
2902 AppBarLayout.LayoutParams toolbarLayoutParams = (AppBarLayout.LayoutParams) toolbar.getLayoutParams();
2903 AppBarLayout.LayoutParams findOnPageLayoutParams = (AppBarLayout.LayoutParams) findOnPageLinearLayout.getLayoutParams();
2904 AppBarLayout.LayoutParams tabsLayoutParams = (AppBarLayout.LayoutParams) tabsLinearLayout.getLayoutParams();
2906 // Add the scrolling behavior to the layout parameters.
2908 // Enable scrolling of the app bar.
2909 swipeRefreshLayoutParams.setBehavior(new AppBarLayout.ScrollingViewBehavior());
2910 toolbarLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
2911 findOnPageLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
2912 tabsLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
2914 // Disable scrolling of the app bar.
2915 swipeRefreshLayoutParams.setBehavior(null);
2916 toolbarLayoutParams.setScrollFlags(0);
2917 findOnPageLayoutParams.setScrollFlags(0);
2918 tabsLayoutParams.setScrollFlags(0);
2920 // Expand the app bar if it is currently collapsed.
2921 appBarLayout.setExpanded(true);
2924 // Apply the modified layout parameters.
2925 swipeRefreshLayout.setLayoutParams(swipeRefreshLayoutParams);
2926 toolbar.setLayoutParams(toolbarLayoutParams);
2927 findOnPageLinearLayout.setLayoutParams(findOnPageLayoutParams);
2928 tabsLinearLayout.setLayoutParams(tabsLayoutParams);
2930 // Set the app bar scrolling for each WebView.
2931 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
2932 // Get the WebView tab fragment.
2933 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
2935 // Get the fragment view.
2936 View fragmentView = webViewTabFragment.getView();
2938 // Only modify the WebViews if they exist.
2939 if (fragmentView != null) {
2940 // Get the nested scroll WebView from the tab fragment.
2941 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
2943 // Set the app bar scrolling.
2944 nestedScrollWebView.setNestedScrollingEnabled(scrollAppBar);
2948 // Update the full screen browsing mode settings.
2949 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
2950 // Update the visibility of the app bar, which might have changed in the settings.
2952 // Hide the tab linear layout.
2953 tabsLinearLayout.setVisibility(View.GONE);
2955 // Hide the action bar.
2958 // Show the tab linear layout.
2959 tabsLinearLayout.setVisibility(View.VISIBLE);
2961 // Show the action bar.
2965 // Hide the banner ad in the free flavor.
2966 if (BuildConfig.FLAVOR.contentEquals("free")) {
2967 AdHelper.hideAd(findViewById(R.id.adview));
2970 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
2971 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2973 /* Hide the system bars.
2974 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
2975 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
2976 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
2977 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
2979 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
2980 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
2981 } else { // Privacy Browser is not in full screen browsing mode.
2982 // 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.
2983 inFullScreenBrowsingMode = false;
2985 // Show the tab linear layout.
2986 tabsLinearLayout.setVisibility(View.VISIBLE);
2988 // Show the action bar.
2991 // Show the banner ad in the free flavor.
2992 if (BuildConfig.FLAVOR.contentEquals("free")) {
2993 // Initialize the ads. If this isn't the first run, `loadAd()` will be automatically called instead.
2994 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getSupportFragmentManager(), getString(R.string.google_app_id), getString(R.string.ad_unit_id));
2997 // Remove the `SYSTEM_UI` flags from the root frame layout.
2998 rootFrameLayout.setSystemUiVisibility(0);
3000 // Add the translucent status flag.
3001 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3005 private void initializeApp() {
3006 // Get a handle for the shared preferences.
3007 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3009 // Get the theme preference.
3010 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
3012 // Get a handle for the input method.
3013 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
3015 // Remove the lint warning below that the input method manager might be null.
3016 assert inputMethodManager != null;
3018 // Initialize the foreground color spans for highlighting the URLs. We have to use the deprecated `getColor()` until API >= 23.
3019 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
3020 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
3021 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
3023 // Get handles for the URL views.
3024 EditText urlEditText = findViewById(R.id.url_edittext);
3026 // Remove the formatting from the URL edit text when the user is editing the text.
3027 urlEditText.setOnFocusChangeListener((View v, boolean hasFocus) -> {
3028 if (hasFocus) { // The user is editing the URL text box.
3029 // Remove the highlighting.
3030 urlEditText.getText().removeSpan(redColorSpan);
3031 urlEditText.getText().removeSpan(initialGrayColorSpan);
3032 urlEditText.getText().removeSpan(finalGrayColorSpan);
3033 } else { // The user has stopped editing the URL text box.
3034 // Move to the beginning of the string.
3035 urlEditText.setSelection(0);
3037 // Reapply the highlighting.
3042 // Set the go button on the keyboard to load the URL in `urlTextBox`.
3043 urlEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
3044 // If the event is a key-down event on the `enter` button, load the URL.
3045 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
3046 // Load the URL into the mainWebView and consume the event.
3047 loadUrlFromTextBox();
3049 // If the enter key was pressed, consume the event.
3052 // If any other key was pressed, do not consume the event.
3057 // Initialize the Orbot status and the waiting for Orbot trackers.
3058 orbotStatus = "unknown";
3059 waitingForOrbot = false;
3061 // Create an Orbot status `BroadcastReceiver`.
3062 orbotStatusBroadcastReceiver = new BroadcastReceiver() {
3064 public void onReceive(Context context, Intent intent) {
3065 // Store the content of the status message in `orbotStatus`.
3066 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
3068 // If Privacy Browser is waiting on Orbot, load the website now that Orbot is connected.
3069 if (orbotStatus.equals("ON") && waitingForOrbot) {
3070 // Reset the waiting for Orbot status.
3071 waitingForOrbot = false;
3073 // Get the intent that started the app.
3074 Intent launchingIntent = getIntent();
3076 // Get the information from the intent.
3077 String launchingIntentAction = launchingIntent.getAction();
3078 Uri launchingIntentUriData = launchingIntent.getData();
3080 // If the intent action is a web search, perform the search.
3081 if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) {
3082 // Create an encoded URL string.
3083 String encodedUrlString;
3085 // Sanitize the search input and convert it to a search.
3087 encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
3088 } catch (UnsupportedEncodingException exception) {
3089 encodedUrlString = "";
3092 // Load the completed search URL.
3093 loadUrl(searchURL + encodedUrlString);
3094 } else if (launchingIntentUriData != null){ // Check to see if the intent contains a new URL.
3095 // Load the URL from the intent.
3096 loadUrl(launchingIntentUriData.toString());
3097 } else { // The is no URL in the intent.
3098 // Select the homepage based on the proxy through Orbot status.
3099 if (proxyThroughOrbot) {
3100 // Load the Tor homepage.
3101 loadUrl(sharedPreferences.getString("tor_homepage", getString(R.string.tor_homepage_default_value)));
3103 // Load the normal homepage.
3104 loadUrl(sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
3111 // Register `orbotStatusBroadcastReceiver` on `this` context.
3112 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
3114 // Get handles for views that need to be modified.
3115 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
3116 NavigationView navigationView = findViewById(R.id.navigationview);
3117 TabLayout tabLayout = findViewById(R.id.tablayout);
3118 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
3119 ViewPager webViewPager = findViewById(R.id.webviewpager);
3120 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
3121 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
3122 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
3123 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
3124 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
3126 // Listen for touches on the navigation menu.
3127 navigationView.setNavigationItemSelectedListener(this);
3129 // Get handles for the navigation menu and the back and forward menu items. The menu is zero-based.
3130 Menu navigationMenu = navigationView.getMenu();
3131 MenuItem navigationBackMenuItem = navigationMenu.getItem(2);
3132 MenuItem navigationForwardMenuItem = navigationMenu.getItem(3);
3133 MenuItem navigationHistoryMenuItem = navigationMenu.getItem(4);
3134 MenuItem navigationRequestsMenuItem = navigationMenu.getItem(5);
3136 // Update the web view pager every time a tab is modified.
3137 webViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
3139 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
3144 public void onPageSelected(int position) {
3145 // Close the find on page bar if it is open.
3146 closeFindOnPage(null);
3148 // Set the current WebView.
3149 setCurrentWebView(position);
3151 // Select the corresponding tab if it does not match the currently selected page. This will happen if the page was scrolled via swiping in the view pager or by creating a new tab.
3152 if (tabLayout.getSelectedTabPosition() != position) {
3153 // Create a handler to select the tab.
3154 Handler selectTabHandler = new Handler();
3156 // Create a runnable to select the tab.
3157 Runnable selectTabRunnable = () -> {
3158 // Get a handle for the tab.
3159 TabLayout.Tab tab = tabLayout.getTabAt(position);
3161 // Assert that the tab is not null.
3168 // Select the tab layout after 150 milliseconds, which leaves enough time for a new tab to be inflated.
3169 selectTabHandler.postDelayed(selectTabRunnable, 150);
3174 public void onPageScrollStateChanged(int state) {
3179 // Display the View SSL Certificate dialog when the currently selected tab is reselected.
3180 tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
3182 public void onTabSelected(TabLayout.Tab tab) {
3183 // Select the same page in the view pager.
3184 webViewPager.setCurrentItem(tab.getPosition());
3188 public void onTabUnselected(TabLayout.Tab tab) {
3193 public void onTabReselected(TabLayout.Tab tab) {
3194 // Instantiate the View SSL Certificate dialog.
3195 DialogFragment viewSslCertificateDialogFragment = ViewSslCertificateDialog.displayDialog(currentWebView.getWebViewFragmentId());
3197 // Display the View SSL Certificate dialog.
3198 viewSslCertificateDialogFragment.show(getSupportFragmentManager(), getString(R.string.view_ssl_certificate));
3202 // Set the bookmarks drawer resources according to the theme. This can't be done in the layout due to compatibility issues with the `DrawerLayout` support widget.
3203 // The deprecated `getResources().getDrawable()` must be used until the minimum API >= 21 and and `getResources().getColor()` must be used until the minimum API >= 23.
3205 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
3206 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
3207 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
3208 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
3210 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
3211 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
3212 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
3213 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
3216 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
3217 launchBookmarksActivityFab.setOnClickListener(v -> {
3218 // Get a copy of the favorite icon bitmap.
3219 Bitmap favoriteIconBitmap = currentWebView.getFavoriteOrDefaultIcon();
3221 // Create a favorite icon byte array output stream.
3222 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3224 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
3225 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
3227 // Convert the favorite icon byte array stream to a byte array.
3228 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
3230 // Create an intent to launch the bookmarks activity.
3231 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
3233 // Add the extra information to the intent.
3234 bookmarksIntent.putExtra("current_url", currentWebView.getUrl());
3235 bookmarksIntent.putExtra("current_title", currentWebView.getTitle());
3236 bookmarksIntent.putExtra("current_folder", currentBookmarksFolder);
3237 bookmarksIntent.putExtra("favorite_icon_byte_array", favoriteIconByteArray);
3240 startActivity(bookmarksIntent);
3243 // Set the create new bookmark folder FAB to display an alert dialog.
3244 createBookmarkFolderFab.setOnClickListener(v -> {
3245 // Create a create bookmark folder dialog.
3246 DialogFragment createBookmarkFolderDialog = CreateBookmarkFolderDialog.createBookmarkFolder(currentWebView.getFavoriteOrDefaultIcon());
3248 // Show the create bookmark folder dialog.
3249 createBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.create_folder));
3252 // Set the create new bookmark FAB to display an alert dialog.
3253 createBookmarkFab.setOnClickListener(view -> {
3254 // Instantiate the create bookmark dialog.
3255 DialogFragment createBookmarkDialog = CreateBookmarkDialog.createBookmark(currentWebView.getUrl(), currentWebView.getTitle(), currentWebView.getFavoriteOrDefaultIcon());
3257 // Display the create bookmark dialog.
3258 createBookmarkDialog.show(getSupportFragmentManager(), getString(R.string.create_bookmark));
3261 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
3262 findOnPageEditText.addTextChangedListener(new TextWatcher() {
3264 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
3269 public void onTextChanged(CharSequence s, int start, int before, int count) {
3274 public void afterTextChanged(Editable s) {
3275 // 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.
3276 if (currentWebView != null) {
3277 currentWebView.findAllAsync(findOnPageEditText.getText().toString());
3282 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
3283 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
3284 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
3285 // Hide the soft keyboard.
3286 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
3288 // Consume the event.
3290 } else { // A different key was pressed.
3291 // Do not consume the event.
3296 // Implement swipe to refresh.
3297 swipeRefreshLayout.setOnRefreshListener(() -> currentWebView.reload());
3299 // Store the default progress view offsets for use later in `initializeWebView()`.
3300 defaultProgressViewStartOffset = swipeRefreshLayout.getProgressViewStartOffset();
3301 defaultProgressViewEndOffset = swipeRefreshLayout.getProgressViewEndOffset();
3303 // Set the swipe to refresh color according to the theme.
3305 swipeRefreshLayout.setColorSchemeResources(R.color.blue_800);
3306 swipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.gray_850);
3308 swipeRefreshLayout.setColorSchemeResources(R.color.blue_500);
3311 // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
3312 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
3313 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
3315 // Initialize the bookmarks database helper. The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
3316 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
3318 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
3319 currentBookmarksFolder = "";
3321 // Load the home folder, which is `""` in the database.
3322 loadBookmarksFolder();
3324 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
3325 // Convert the id from long to int to match the format of the bookmarks database.
3326 int databaseID = (int) id;
3328 // Get the bookmark cursor for this ID and move it to the first row.
3329 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseID);
3330 bookmarkCursor.moveToFirst();
3332 // Act upon the bookmark according to the type.
3333 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
3334 // Store the new folder name in `currentBookmarksFolder`.
3335 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
3337 // Load the new folder.
3338 loadBookmarksFolder();
3339 } else { // The selected bookmark is not a folder.
3340 // Load the bookmark URL.
3341 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
3343 // Close the bookmarks drawer.
3344 drawerLayout.closeDrawer(GravityCompat.END);
3347 // Close the `Cursor`.
3348 bookmarkCursor.close();
3351 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
3352 // Convert the database ID from `long` to `int`.
3353 int databaseId = (int) id;
3355 // Find out if the selected bookmark is a folder.
3356 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
3359 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
3360 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
3362 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
3363 DialogFragment editBookmarkFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId, currentWebView.getFavoriteOrDefaultIcon());
3364 editBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.edit_folder));
3366 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
3367 DialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId, currentWebView.getFavoriteOrDefaultIcon());
3368 editBookmarkDialog.show(getSupportFragmentManager(), getString(R.string.edit_bookmark));
3371 // Consume the event.
3375 // Get the status bar pixel size.
3376 int statusBarResourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
3377 int statusBarPixelSize = getResources().getDimensionPixelSize(statusBarResourceId);
3379 // Get the resource density.
3380 float screenDensity = getResources().getDisplayMetrics().density;
3382 // Calculate the drawer header padding. This is used to move the text in the drawer headers below any cutouts.
3383 drawerHeaderPaddingLeftAndRight = (int) (15 * screenDensity);
3384 drawerHeaderPaddingTop = statusBarPixelSize + (int) (4 * screenDensity);
3385 drawerHeaderPaddingBottom = (int) (8 * screenDensity);
3387 // The drawer listener is used to update the navigation menu.`
3388 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
3390 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
3394 public void onDrawerOpened(@NonNull View drawerView) {
3398 public void onDrawerClosed(@NonNull View drawerView) {
3402 public void onDrawerStateChanged(int newState) {
3403 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // A drawer is opening or closing.
3404 // Get handles for the drawer headers.
3405 TextView navigationHeaderTextView = findViewById(R.id.navigationText);
3406 TextView bookmarksHeaderTextView = findViewById(R.id.bookmarks_title_textview);
3408 // Apply the navigation header paddings if the view is not null (sometimes it is null if another activity has already started). This moves the text in the header below any cutouts.
3409 if (navigationHeaderTextView != null) {
3410 navigationHeaderTextView.setPadding(drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingTop, drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingBottom);
3413 // Apply the bookmarks header paddings if the view is not null (sometimes it is null if another activity has already started). This moves the text in the header below any cutouts.
3414 if (bookmarksHeaderTextView != null) {
3415 bookmarksHeaderTextView.setPadding(drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingTop, drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingBottom);
3418 // Update the navigation menu items if the WebView is not null.
3419 if (currentWebView != null) {
3420 navigationBackMenuItem.setEnabled(currentWebView.canGoBack());
3421 navigationForwardMenuItem.setEnabled(currentWebView.canGoForward());
3422 navigationHistoryMenuItem.setEnabled((currentWebView.canGoBack() || currentWebView.canGoForward()));
3423 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
3425 // Hide the keyboard (if displayed).
3426 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
3429 // Clear the focus from from the URL text box and the WebView. This removes any text selection markers and context menus, which otherwise draw above the open drawers.
3430 urlEditText.clearFocus();
3431 currentWebView.clearFocus();
3436 // 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).
3437 customHeaders.put("X-Requested-With", "");
3439 // Inflate a bare WebView to get the default user agent. It is not used to render content on the screen.
3440 @SuppressLint("InflateParams") View webViewLayout = getLayoutInflater().inflate(R.layout.bare_webview, null, false);
3442 // Get a handle for the WebView.
3443 WebView bareWebView = webViewLayout.findViewById(R.id.bare_webview);
3445 // Store the default user agent.
3446 webViewDefaultUserAgent = bareWebView.getSettings().getUserAgentString();
3448 // Destroy the bare WebView.
3449 bareWebView.destroy();
3452 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
3453 @SuppressLint("SetJavaScriptEnabled")
3454 private boolean applyDomainSettings(NestedScrollWebView nestedScrollWebView, String url, boolean resetTab, boolean reloadWebsite) {
3455 // Store a copy of the current user agent to track changes for the return boolean.
3456 String initialUserAgent = nestedScrollWebView.getSettings().getUserAgentString();
3458 // Parse the URL into a URI.
3459 Uri uri = Uri.parse(url);
3461 // Extract the domain from `uri`.
3462 String newHostName = uri.getHost();
3464 // Strings don't like to be null.
3465 if (newHostName == null) {
3469 // 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.
3470 if (!nestedScrollWebView.getCurrentDomainName().equals(newHostName) || newHostName.equals("")) {
3471 // Set the new host name as the current domain name.
3472 nestedScrollWebView.setCurrentDomainName(newHostName);
3474 // Reset the ignoring of pinned domain information.
3475 nestedScrollWebView.setIgnorePinnedDomainInformation(false);
3477 // Clear any pinned SSL certificate or IP addresses.
3478 nestedScrollWebView.clearPinnedSslCertificate();
3479 nestedScrollWebView.clearPinnedIpAddresses();
3481 // Reset the favorite icon if specified.
3483 // Initialize the favorite icon.
3484 nestedScrollWebView.initializeFavoriteIcon();
3486 // Get the current page position.
3487 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
3489 // Get a handle for the tab layout.
3490 TabLayout tabLayout = findViewById(R.id.tablayout);
3492 // Get the corresponding tab.
3493 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
3495 // Update the tab if it isn't null, which sometimes happens when restarting from the background.
3497 // Get the tab custom view.
3498 View tabCustomView = tab.getCustomView();
3500 // Remove the warning below that the tab custom view might be null.
3501 assert tabCustomView != null;
3503 // Get the tab views.
3504 ImageView tabFavoriteIconImageView = tabCustomView.findViewById(R.id.favorite_icon_imageview);
3505 TextView tabTitleTextView = tabCustomView.findViewById(R.id.title_textview);
3507 // Set the default favorite icon as the favorite icon for this tab.
3508 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(nestedScrollWebView.getFavoriteOrDefaultIcon(), 64, 64, true));
3510 // Set the loading title text.
3511 tabTitleTextView.setText(R.string.loading);
3515 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3516 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3518 // Get a full cursor from `domainsDatabaseHelper`.
3519 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3521 // Initialize `domainSettingsSet`.
3522 Set<String> domainSettingsSet = new HashSet<>();
3524 // Get the domain name column index.
3525 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3527 // Populate `domainSettingsSet`.
3528 for (int i = 0; i < domainNameCursor.getCount(); i++) {
3529 // Move `domainsCursor` to the current row.
3530 domainNameCursor.moveToPosition(i);
3532 // Store the domain name in `domainSettingsSet`.
3533 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3536 // Close `domainNameCursor.
3537 domainNameCursor.close();
3539 // Initialize the domain name in database variable.
3540 String domainNameInDatabase = null;
3542 // Check the hostname against the domain settings set.
3543 if (domainSettingsSet.contains(newHostName)) { // The hostname is contained in the domain settings set.
3544 // Record the domain name in the database.
3545 domainNameInDatabase = newHostName;
3547 // Set the domain settings applied tracker to true.
3548 nestedScrollWebView.setDomainSettingsApplied(true);
3549 } else { // The hostname is not contained in the domain settings set.
3550 // Set the domain settings applied tracker to false.
3551 nestedScrollWebView.setDomainSettingsApplied(false);
3554 // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3555 while (!nestedScrollWebView.getDomainSettingsApplied() && newHostName.contains(".")) { // Stop checking if domain settings are already applied or there are no more `.` in the host name.
3556 if (domainSettingsSet.contains("*." + newHostName)) { // Check the host name prepended by `*.`.
3557 // Set the domain settings applied tracker to true.
3558 nestedScrollWebView.setDomainSettingsApplied(true);
3560 // Store the applied domain names as it appears in the database.
3561 domainNameInDatabase = "*." + newHostName;
3564 // Strip out the lowest subdomain of of the host name.
3565 newHostName = newHostName.substring(newHostName.indexOf(".") + 1);
3569 // Get a handle for the shared preferences.
3570 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3572 // Store the general preference information.
3573 String defaultFontSizeString = sharedPreferences.getString("font_size", getString(R.string.font_size_default_value));
3574 String defaultUserAgentName = sharedPreferences.getString("user_agent", getString(R.string.user_agent_default_value));
3575 boolean defaultSwipeToRefresh = sharedPreferences.getBoolean("swipe_to_refresh", true);
3576 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
3577 boolean wideViewport = sharedPreferences.getBoolean("wide_viewport", true);
3578 boolean displayWebpageImages = sharedPreferences.getBoolean("display_webpage_images", true);
3580 // Get a handle for the cookie manager.
3581 CookieManager cookieManager = CookieManager.getInstance();
3583 // Get handles for the views.
3584 RelativeLayout urlRelativeLayout = findViewById(R.id.url_relativelayout);
3585 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
3587 // Initialize the user agent array adapter and string array.
3588 ArrayAdapter<CharSequence> userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item);
3589 String[] userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
3591 if (nestedScrollWebView.getDomainSettingsApplied()) { // The url has custom domain settings.
3592 // Get a cursor for the current host and move it to the first position.
3593 Cursor currentDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3594 currentDomainSettingsCursor.moveToFirst();
3596 // Get the settings from the cursor.
3597 nestedScrollWebView.setDomainSettingsDatabaseId(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3598 nestedScrollWebView.setDomainSettingsJavaScriptEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3599 nestedScrollWebView.setAcceptFirstPartyCookies(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3600 boolean domainThirdPartyCookiesEnabled = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3601 nestedScrollWebView.getSettings().setDomStorageEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3602 // Form data can be removed once the minimum API >= 26.
3603 boolean saveFormData = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3604 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASY_LIST,
3605 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3606 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASY_PRIVACY,
3607 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3608 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST,
3609 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3610 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST,
3611 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3612 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRA_PRIVACY,
3613 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_ULTRAPRIVACY)) == 1);
3614 nestedScrollWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS,
3615 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
3616 String userAgentName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3617 int fontSize = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3618 int swipeToRefreshInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
3619 int nightModeInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
3620 int wideViewportInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.WIDE_VIEWPORT));
3621 int displayWebpageImagesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3622 boolean pinnedSslCertificate = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3623 String pinnedSslIssuedToCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3624 String pinnedSslIssuedToOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3625 String pinnedSslIssuedToUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3626 String pinnedSslIssuedByCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3627 String pinnedSslIssuedByOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3628 String pinnedSslIssuedByUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3629 boolean pinnedIpAddresses = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_IP_ADDRESSES)) == 1);
3630 String pinnedHostIpAddresses = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.IP_ADDRESSES));
3632 // Create the pinned SSL date variables.
3633 Date pinnedSslStartDate;
3634 Date pinnedSslEndDate;
3636 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0 because creating a new Date results in an error if the input is 0.
3637 if (currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
3638 pinnedSslStartDate = null;
3640 pinnedSslStartDate = new Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
3643 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0 because creating a new Date results in an error if the input is 0.
3644 if (currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
3645 pinnedSslEndDate = null;
3647 pinnedSslEndDate = new Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
3650 // If there is a pinned SSL certificate, store it in the WebView.
3651 if (pinnedSslCertificate) {
3652 nestedScrollWebView.setPinnedSslCertificate(pinnedSslIssuedToCName, pinnedSslIssuedToOName, pinnedSslIssuedToUName, pinnedSslIssuedByCName, pinnedSslIssuedByOName, pinnedSslIssuedByUName,
3653 pinnedSslStartDate, pinnedSslEndDate);
3656 // If there is a pinned IP address, store it in the WebView.
3657 if (pinnedIpAddresses) {
3658 nestedScrollWebView.setPinnedIpAddresses(pinnedHostIpAddresses);
3661 // Set night mode according to the night mode int.
3662 switch (nightModeInt) {
3663 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
3664 // Set night mode according to the current default.
3665 nestedScrollWebView.setNightMode(sharedPreferences.getBoolean("night_mode", false));
3668 case DomainsDatabaseHelper.ENABLED:
3669 // Enable night mode.
3670 nestedScrollWebView.setNightMode(true);
3673 case DomainsDatabaseHelper.DISABLED:
3674 // Disable night mode.
3675 nestedScrollWebView.setNightMode(false);
3679 // Enable JavaScript if night mode is enabled.
3680 if (nestedScrollWebView.getNightMode()) {
3681 // Enable JavaScript.
3682 nestedScrollWebView.getSettings().setJavaScriptEnabled(true);
3684 // Set JavaScript according to the domain settings.
3685 nestedScrollWebView.getSettings().setJavaScriptEnabled(nestedScrollWebView.getDomainSettingsJavaScriptEnabled());
3688 // Close the current host domain settings cursor.
3689 currentDomainSettingsCursor.close();
3691 // Apply the domain settings.
3692 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptFirstPartyCookies());
3694 // Set third-party cookies status if API >= 21.
3695 if (Build.VERSION.SDK_INT >= 21) {
3696 cookieManager.setAcceptThirdPartyCookies(nestedScrollWebView, domainThirdPartyCookiesEnabled);
3699 // Apply the form data setting if the API < 26.
3700 if (Build.VERSION.SDK_INT < 26) {
3701 nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
3704 // Apply the font size.
3705 if (fontSize == 0) { // Apply the default font size.
3706 nestedScrollWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3707 } else { // Apply the specified font size.
3708 nestedScrollWebView.getSettings().setTextZoom(fontSize);
3711 // Set the user agent.
3712 if (userAgentName.equals(getString(R.string.system_default_user_agent))) { // Use the system default user agent.
3713 // Get the array position of the default user agent name.
3714 int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3716 // Set the user agent according to the system default.
3717 switch (defaultUserAgentArrayPosition) {
3718 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
3719 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3720 nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
3723 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3724 // Set the user agent to `""`, which uses the default value.
3725 nestedScrollWebView.getSettings().setUserAgentString("");
3728 case SETTINGS_CUSTOM_USER_AGENT:
3729 // Set the default custom user agent.
3730 nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
3734 // Get the user agent string from the user agent data array
3735 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
3737 } else { // Set the user agent according to the stored name.
3738 // Get the array position of the user agent name.
3739 int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
3741 switch (userAgentArrayPosition) {
3742 case UNRECOGNIZED_USER_AGENT: // The user agent name contains a custom user agent.
3743 nestedScrollWebView.getSettings().setUserAgentString(userAgentName);
3746 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3747 // Set the user agent to `""`, which uses the default value.
3748 nestedScrollWebView.getSettings().setUserAgentString("");
3752 // Get the user agent string from the user agent data array.
3753 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3757 // Set swipe to refresh.
3758 switch (swipeToRefreshInt) {
3759 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
3760 // Store the swipe to refresh status in the nested scroll WebView.
3761 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
3763 // Apply swipe to refresh according to the default. This can be removed once the minimum API >= 23 because it is continuously set by an on scroll change listener.
3764 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
3767 case DomainsDatabaseHelper.ENABLED:
3768 // Store the swipe to refresh status in the nested scroll WebView.
3769 nestedScrollWebView.setSwipeToRefresh(true);
3771 // Enable swipe to refresh. This can be removed once the minimum API >= 23 because it is continuously set by an on scroll change listener.
3772 swipeRefreshLayout.setEnabled(true);
3775 case DomainsDatabaseHelper.DISABLED:
3776 // Store the swipe to refresh status in the nested scroll WebView.
3777 nestedScrollWebView.setSwipeToRefresh(false);
3779 // Disable swipe to refresh. This can be removed once the minimum API >= 23 because it is continuously set by an on scroll change listener.
3780 swipeRefreshLayout.setEnabled(false);
3783 // Set the viewport.
3784 switch (wideViewportInt) {
3785 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
3786 nestedScrollWebView.getSettings().setUseWideViewPort(wideViewport);
3789 case DomainsDatabaseHelper.ENABLED:
3790 nestedScrollWebView.getSettings().setUseWideViewPort(true);
3793 case DomainsDatabaseHelper.DISABLED:
3794 nestedScrollWebView.getSettings().setUseWideViewPort(false);
3798 // Set the loading of webpage images.
3799 switch (displayWebpageImagesInt) {
3800 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
3801 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
3804 case DomainsDatabaseHelper.ENABLED:
3805 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(true);
3808 case DomainsDatabaseHelper.DISABLED:
3809 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(false);
3813 // Set a green background on the URL relative layout to indicate that custom domain settings are being used. The deprecated `.getDrawable()` must be used until the minimum API >= 21.
3815 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
3817 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
3819 } else { // The new URL does not have custom domain settings. Load the defaults.
3820 // Store the values from the shared preferences.
3821 boolean defaultJavaScriptEnabled = sharedPreferences.getBoolean("javascript", false);
3822 nestedScrollWebView.setAcceptFirstPartyCookies(sharedPreferences.getBoolean("first_party_cookies", false));
3823 boolean defaultThirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies", false);
3824 nestedScrollWebView.getSettings().setDomStorageEnabled(sharedPreferences.getBoolean("dom_storage", false));
3825 boolean saveFormData = sharedPreferences.getBoolean("save_form_data", false); // Form data can be removed once the minimum API >= 26.
3826 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASY_LIST, sharedPreferences.getBoolean("easylist", true));
3827 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASY_PRIVACY, sharedPreferences.getBoolean("easyprivacy", true));
3828 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, sharedPreferences.getBoolean("fanboys_annoyance_list", true));
3829 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, sharedPreferences.getBoolean("fanboys_social_blocking_list", true));
3830 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRA_PRIVACY, sharedPreferences.getBoolean("ultraprivacy", true));
3831 nestedScrollWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, sharedPreferences.getBoolean("block_all_third_party_requests", false));
3832 nestedScrollWebView.setNightMode(sharedPreferences.getBoolean("night_mode", false));
3834 // Enable JavaScript if night mode is enabled.
3835 if (nestedScrollWebView.getNightMode()) {
3836 // Enable JavaScript.
3837 nestedScrollWebView.getSettings().setJavaScriptEnabled(true);
3839 // Set JavaScript according to the domain settings.
3840 nestedScrollWebView.getSettings().setJavaScriptEnabled(defaultJavaScriptEnabled);
3843 // Apply the default settings.
3844 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptFirstPartyCookies());
3845 nestedScrollWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3847 // Apply the form data setting if the API < 26.
3848 if (Build.VERSION.SDK_INT < 26) {
3849 nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
3852 // Store the swipe to refresh status in the nested scroll WebView.
3853 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
3855 // Apply swipe to refresh according to the default.
3856 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
3858 // Reset the pinned variables.
3859 nestedScrollWebView.setDomainSettingsDatabaseId(-1);
3861 // Set third-party cookies status if API >= 21.
3862 if (Build.VERSION.SDK_INT >= 21) {
3863 cookieManager.setAcceptThirdPartyCookies(nestedScrollWebView, defaultThirdPartyCookiesEnabled);
3866 // Get the array position of the user agent name.
3867 int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3869 // Set the user agent.
3870 switch (userAgentArrayPosition) {
3871 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
3872 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3873 nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
3876 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3877 // Set the user agent to `""`, which uses the default value.
3878 nestedScrollWebView.getSettings().setUserAgentString("");
3881 case SETTINGS_CUSTOM_USER_AGENT:
3882 // Set the default custom user agent.
3883 nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
3887 // Get the user agent string from the user agent data array
3888 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3891 // Set the viewport.
3892 nestedScrollWebView.getSettings().setUseWideViewPort(wideViewport);
3894 // Set the loading of webpage images.
3895 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
3897 // Set a transparent background on URL edit text. The deprecated `getResources().getDrawable()` must be used until the minimum API >= 21.
3898 urlRelativeLayout.setBackground(getResources().getDrawable(R.color.transparent));
3901 // Close the domains database helper.
3902 domainsDatabaseHelper.close();
3904 // Update the privacy icons.
3905 updatePrivacyIcons(true);
3908 // Reload the website if returning from the Domains activity.
3909 if (reloadWebsite) {
3910 nestedScrollWebView.reload();
3913 // Return the user agent changed status.
3914 return !nestedScrollWebView.getSettings().getUserAgentString().equals(initialUserAgent);
3917 private void applyProxyThroughOrbot(boolean reloadWebsite) {
3918 // Get a handle for the shared preferences.
3919 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3921 // Get the search and theme preferences.
3922 String torSearchString = sharedPreferences.getString("tor_search", getString(R.string.tor_search_default_value));
3923 String torSearchCustomUrlString = sharedPreferences.getString("tor_search_custom_url", getString(R.string.tor_search_custom_url_default_value));
3924 String searchString = sharedPreferences.getString("search", getString(R.string.search_default_value));
3925 String searchCustomUrlString = sharedPreferences.getString("search_custom_url", getString(R.string.search_custom_url_default_value));
3926 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
3928 // Get a handle for the app bar layout.
3929 AppBarLayout appBarLayout = findViewById(R.id.appbar_layout);
3931 // Set the homepage, search, and proxy options.
3932 if (proxyThroughOrbot) { // Set the Tor options.
3933 // Set the search URL.
3934 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
3935 searchURL = torSearchCustomUrlString;
3936 } else { // Use the string from the pre-built list.
3937 searchURL = torSearchString;
3940 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
3941 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
3943 // Set the app bar background to indicate proxying through Orbot is enabled.
3945 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
3947 appBarLayout.setBackgroundResource(R.color.blue_50);
3950 // Check to see if Orbot is ready.
3951 if (!orbotStatus.equals("ON")) { // Orbot is not ready.
3952 // Set `waitingForOrbot`.
3953 waitingForOrbot = true;
3955 // Disable the wide view port so that the waiting for Orbot text is displayed correctly.
3956 currentWebView.getSettings().setUseWideViewPort(false);
3958 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
3959 currentWebView.loadData("<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>", "text/html", null);
3960 } else if (reloadWebsite) { // Orbot is ready and the website should be reloaded.
3961 // Reload the website.
3962 currentWebView.reload();
3964 } else { // Set the non-Tor options.
3965 // Set the search URL.
3966 if (searchString.equals("Custom URL")) { // Get the custom URL string.
3967 searchURL = searchCustomUrlString;
3968 } else { // Use the string from the pre-built list.
3969 searchURL = searchString;
3972 // Reset the proxy to default. The host is `""` and the port is `"0"`.
3973 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
3975 // Set the default app bar layout background.
3977 appBarLayout.setBackgroundResource(R.color.gray_900);
3979 appBarLayout.setBackgroundResource(R.color.gray_100);
3982 // Reset `waitingForOrbot.
3983 waitingForOrbot = false;
3985 // Reload the WebViews if requested.
3986 if (reloadWebsite) {
3987 // Reload the WebViews.
3988 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3989 // Get the WebView tab fragment.
3990 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3992 // Get the fragment view.
3993 View fragmentView = webViewTabFragment.getView();
3995 // Only reload the WebViews if they exist.
3996 if (fragmentView != null) {
3997 // Get the nested scroll WebView from the tab fragment.
3998 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4000 // Reload the WebView.
4001 nestedScrollWebView.reload();
4008 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
4009 // Only update the privacy icons if the options menu and the current WebView have already been populated.
4010 if ((optionsMenu != null) && (currentWebView != null)) {
4011 // Get a handle for the shared preferences.
4012 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4014 // Get the theme and screenshot preferences.
4015 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
4017 // Get handles for the menu items.
4018 MenuItem privacyMenuItem = optionsMenu.findItem(R.id.toggle_javascript);
4019 MenuItem firstPartyCookiesMenuItem = optionsMenu.findItem(R.id.toggle_first_party_cookies);
4020 MenuItem domStorageMenuItem = optionsMenu.findItem(R.id.toggle_dom_storage);
4021 MenuItem refreshMenuItem = optionsMenu.findItem(R.id.refresh);
4023 // Update the privacy icon.
4024 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is enabled.
4025 privacyMenuItem.setIcon(R.drawable.javascript_enabled);
4026 } else if (currentWebView.getAcceptFirstPartyCookies()) { // JavaScript is disabled but cookies are enabled.
4027 privacyMenuItem.setIcon(R.drawable.warning);
4028 } else { // All the dangerous features are disabled.
4029 privacyMenuItem.setIcon(R.drawable.privacy_mode);
4032 // Update the first-party cookies icon.
4033 if (currentWebView.getAcceptFirstPartyCookies()) { // First-party cookies are enabled.
4034 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
4035 } else { // First-party cookies are disabled.
4037 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_dark);
4039 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_light);
4043 // Update the DOM storage icon.
4044 if (currentWebView.getSettings().getJavaScriptEnabled() && currentWebView.getSettings().getDomStorageEnabled()) { // Both JavaScript and DOM storage are enabled.
4045 domStorageMenuItem.setIcon(R.drawable.dom_storage_enabled);
4046 } else if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is enabled but DOM storage is disabled.
4048 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
4050 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
4052 } else { // JavaScript is disabled, so DOM storage is ghosted.
4054 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
4056 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
4060 // Update the refresh icon.
4062 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
4064 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
4067 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
4068 if (runInvalidateOptionsMenu) {
4069 invalidateOptionsMenu();
4074 private void openUrlWithExternalApp(String url) {
4075 // Create a download intent. Not specifying the action type will display the maximum number of options.
4076 Intent downloadIntent = new Intent();
4078 // Set the URI and the MIME type. Specifying `text/html` displays a good number of options.
4079 downloadIntent.setDataAndType(Uri.parse(url), "text/html");
4081 // Flag the intent to open in a new task.
4082 downloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4084 // Show the chooser.
4085 startActivity(Intent.createChooser(downloadIntent, getString(R.string.open_with)));
4088 private void highlightUrlText() {
4089 // Get a handle for the URL edit text.
4090 EditText urlEditText = findViewById(R.id.url_edittext);
4092 // Only highlight the URL text if the box is not currently selected.
4093 if (!urlEditText.hasFocus()) {
4094 // Get the URL string.
4095 String urlString = urlEditText.getText().toString();
4097 // Highlight the URL according to the protocol.
4098 if (urlString.startsWith("file://")) { // This is a file URL.
4099 // De-emphasize only the protocol.
4100 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4101 } else if (urlString.startsWith("content://")) {
4102 // De-emphasize only the protocol.
4103 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 10, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4104 } else { // This is a web URL.
4105 // Get the index of the `/` immediately after the domain name.
4106 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
4108 // Create a base URL string.
4111 // Get the base URL.
4112 if (endOfDomainName > 0) { // There is at least one character after the base URL.
4113 // Get the base URL.
4114 baseUrl = urlString.substring(0, endOfDomainName);
4115 } else { // There are no characters after the base URL.
4116 // Set the base URL to be the entire URL string.
4117 baseUrl = urlString;
4120 // Get the index of the last `.` in the domain.
4121 int lastDotIndex = baseUrl.lastIndexOf(".");
4123 // Get the index of the penultimate `.` in the domain.
4124 int penultimateDotIndex = baseUrl.lastIndexOf(".", lastDotIndex - 1);
4126 // Markup the beginning of the URL.
4127 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
4128 urlEditText.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4130 // De-emphasize subdomains.
4131 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
4132 urlEditText.getText().setSpan(initialGrayColorSpan, 7, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4134 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
4135 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
4136 // De-emphasize the protocol and the additional subdomains.
4137 urlEditText.getText().setSpan(initialGrayColorSpan, 0, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4138 } else { // There is only one subdomain in the domain name.
4139 // De-emphasize only the protocol.
4140 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4144 // De-emphasize the text after the domain name.
4145 if (endOfDomainName > 0) {
4146 urlEditText.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4152 private void loadBookmarksFolder() {
4153 // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
4154 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
4156 // Populate the bookmarks cursor adapter. `this` specifies the `Context`. `false` disables `autoRequery`.
4157 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
4159 public View newView(Context context, Cursor cursor, ViewGroup parent) {
4160 // Inflate the individual item layout. `false` does not attach it to the root.
4161 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
4165 public void bindView(View view, Context context, Cursor cursor) {
4166 // Get handles for the views.
4167 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
4168 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
4170 // Get the favorite icon byte array from the cursor.
4171 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
4173 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
4174 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
4176 // Display the bitmap in `bookmarkFavoriteIcon`.
4177 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
4179 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
4180 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
4181 bookmarkNameTextView.setText(bookmarkNameString);
4183 // Make the font bold for folders.
4184 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
4185 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
4186 } else { // Reset the font to default for normal bookmarks.
4187 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
4192 // Get a handle for the bookmarks list view.
4193 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
4195 // Populate the list view with the adapter.
4196 bookmarksListView.setAdapter(bookmarksCursorAdapter);
4198 // Get a handle for the bookmarks title text view.
4199 TextView bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
4201 // Set the bookmarks drawer title.
4202 if (currentBookmarksFolder.isEmpty()) {
4203 bookmarksTitleTextView.setText(R.string.bookmarks);
4205 bookmarksTitleTextView.setText(currentBookmarksFolder);
4209 private void openWithApp(String url) {
4210 // Create the open with intent with `ACTION_VIEW`.
4211 Intent openWithAppIntent = new Intent(Intent.ACTION_VIEW);
4213 // Set the URI but not the MIME type. This should open all available apps.
4214 openWithAppIntent.setData(Uri.parse(url));
4216 // Flag the intent to open in a new task.
4217 openWithAppIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4219 // Show the chooser.
4220 startActivity(openWithAppIntent);
4223 private void openWithBrowser(String url) {
4224 // Create the open with intent with `ACTION_VIEW`.
4225 Intent openWithBrowserIntent = new Intent(Intent.ACTION_VIEW);
4227 // Set the URI and the MIME type. `"text/html"` should load browser options.
4228 openWithBrowserIntent.setDataAndType(Uri.parse(url), "text/html");
4230 // Flag the intent to open in a new task.
4231 openWithBrowserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4233 // Show the chooser.
4234 startActivity(openWithBrowserIntent);
4237 private String sanitizeUrl(String url) {
4238 // Sanitize Google Analytics.
4239 if (sanitizeGoogleAnalytics) {
4241 if (url.contains("?utm_")) {
4242 url = url.substring(0, url.indexOf("?utm_"));
4246 if (url.contains("&utm_")) {
4247 url = url.substring(0, url.indexOf("&utm_"));
4251 // Sanitize Facebook Click IDs.
4252 if (sanitizeFacebookClickIds) {
4253 // Remove `?fbclid=`.
4254 if (url.contains("?fbclid=")) {
4255 url = url.substring(0, url.indexOf("?fbclid="));
4258 // Remove `&fbclid=`.
4259 if (url.contains("&fbclid=")) {
4260 url = url.substring(0, url.indexOf("&fbclid="));
4264 // Sanitize Twitter AMP redirects.
4265 if (sanitizeTwitterAmpRedirects) {
4267 if (url.contains("?amp=1")) {
4268 url = url.substring(0, url.indexOf("?amp=1"));
4272 // Return the sanitized URL.
4276 public void finishedPopulatingBlocklists(ArrayList<ArrayList<List<String[]>>> combinedBlocklists) {
4277 // Store the blocklists.
4278 easyList = combinedBlocklists.get(0);
4279 easyPrivacy = combinedBlocklists.get(1);
4280 fanboysAnnoyanceList = combinedBlocklists.get(2);
4281 fanboysSocialList = combinedBlocklists.get(3);
4282 ultraPrivacy = combinedBlocklists.get(4);
4284 // Add the first tab.
4288 public void addTab(View view) {
4289 // Add a new tab with a blank URL.
4293 private void addNewTab(String url) {
4294 // Sanitize the URL.
4295 url = sanitizeUrl(url);
4297 // Get a handle for the tab layout and the view pager.
4298 TabLayout tabLayout = findViewById(R.id.tablayout);
4299 ViewPager webViewPager = findViewById(R.id.webviewpager);
4301 // Get the new page number. The page numbers are 0 indexed, so the new page number will match the current count.
4302 int newTabNumber = tabLayout.getTabCount();
4305 tabLayout.addTab(tabLayout.newTab());
4308 TabLayout.Tab newTab = tabLayout.getTabAt(newTabNumber);
4310 // Remove the lint warning below that the current tab might be null.
4311 assert newTab != null;
4313 // Set a custom view on the new tab.
4314 newTab.setCustomView(R.layout.tab_custom_view);
4316 // Add the new WebView page.
4317 webViewPagerAdapter.addPage(newTabNumber, webViewPager, url);
4320 public void closeTab(View view) {
4321 // Get a handle for the tab layout.
4322 TabLayout tabLayout = findViewById(R.id.tablayout);
4324 // Run the command according to the number of tabs.
4325 if (tabLayout.getTabCount() > 1) { // There is more than one tab open.
4326 // Close the current tab.
4328 } else { // There is only one tab open.
4333 private void closeCurrentTab() {
4334 // Get handles for the views.
4335 AppBarLayout appBarLayout = findViewById(R.id.appbar_layout);
4336 TabLayout tabLayout = findViewById(R.id.tablayout);
4337 ViewPager webViewPager = findViewById(R.id.webviewpager);
4339 // Get the current tab number.
4340 int currentTabNumber = tabLayout.getSelectedTabPosition();
4342 // Delete the current tab.
4343 tabLayout.removeTabAt(currentTabNumber);
4345 // Delete the current page. If the selected page number did not change during the delete, it will return true, meaning that the current WebView must be reset.
4346 if (webViewPagerAdapter.deletePage(currentTabNumber, webViewPager)) {
4347 setCurrentWebView(currentTabNumber);
4350 // Expand the app bar if it is currently collapsed.
4351 appBarLayout.setExpanded(true);
4354 private void clearAndExit() {
4355 // Get a handle for the shared preferences.
4356 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4358 // Close the bookmarks cursor and database.
4359 bookmarksCursor.close();
4360 bookmarksDatabaseHelper.close();
4362 // Get the status of the clear everything preference.
4363 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
4365 // Get a handle for the runtime.
4366 Runtime runtime = Runtime.getRuntime();
4368 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
4369 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
4370 String privateDataDirectoryString = getApplicationInfo().dataDir;
4373 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
4374 // The command to remove cookies changed slightly in API 21.
4375 if (Build.VERSION.SDK_INT >= 21) {
4376 CookieManager.getInstance().removeAllCookies(null);
4378 CookieManager.getInstance().removeAllCookie();
4381 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4383 // Two commands must be used because `Runtime.exec()` does not like `*`.
4384 Process deleteCookiesProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
4385 Process deleteCookiesJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
4387 // Wait until the processes have finished.
4388 deleteCookiesProcess.waitFor();
4389 deleteCookiesJournalProcess.waitFor();
4390 } catch (Exception exception) {
4391 // Do nothing if an error is thrown.
4395 // Clear DOM storage.
4396 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
4397 // Ask `WebStorage` to clear the DOM storage.
4398 WebStorage webStorage = WebStorage.getInstance();
4399 webStorage.deleteAllData();
4401 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4403 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4404 Process deleteLocalStorageProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
4406 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
4407 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
4408 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
4409 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
4410 Process deleteDatabaseProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
4412 // Wait until the processes have finished.
4413 deleteLocalStorageProcess.waitFor();
4414 deleteIndexProcess.waitFor();
4415 deleteQuotaManagerProcess.waitFor();
4416 deleteQuotaManagerJournalProcess.waitFor();
4417 deleteDatabaseProcess.waitFor();
4418 } catch (Exception exception) {
4419 // Do nothing if an error is thrown.
4423 // Clear form data if the API < 26.
4424 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
4425 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
4426 webViewDatabase.clearFormData();
4428 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4430 // A string array must be used because the database contains a space and `Runtime.exec` will not otherwise escape the string correctly.
4431 Process deleteWebDataProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
4432 Process deleteWebDataJournalProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
4434 // Wait until the processes have finished.
4435 deleteWebDataProcess.waitFor();
4436 deleteWebDataJournalProcess.waitFor();
4437 } catch (Exception exception) {
4438 // Do nothing if an error is thrown.
4443 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
4444 // Clear the cache from each WebView.
4445 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4446 // Get the WebView tab fragment.
4447 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4449 // Get the fragment view.
4450 View fragmentView = webViewTabFragment.getView();
4452 // Only clear the cache if the WebView exists.
4453 if (fragmentView != null) {
4454 // Get the nested scroll WebView from the tab fragment.
4455 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4457 // Clear the cache for this WebView.
4458 nestedScrollWebView.clearCache(true);
4462 // Manually delete the cache directories.
4464 // Delete the main cache directory.
4465 Process deleteCacheProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/cache");
4467 // Delete the secondary `Service Worker` cache directory.
4468 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4469 Process deleteServiceWorkerProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
4471 // Wait until the processes have finished.
4472 deleteCacheProcess.waitFor();
4473 deleteServiceWorkerProcess.waitFor();
4474 } catch (Exception exception) {
4475 // Do nothing if an error is thrown.
4479 // Wipe out each WebView.
4480 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4481 // Get the WebView tab fragment.
4482 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4484 // Get the fragment view.
4485 View fragmentView = webViewTabFragment.getView();
4487 // Only wipe out the WebView if it exists.
4488 if (fragmentView != null) {
4489 // Get the nested scroll WebView from the tab fragment.
4490 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4492 // Clear SSL certificate preferences for this WebView.
4493 nestedScrollWebView.clearSslPreferences();
4495 // Clear the back/forward history for this WebView.
4496 nestedScrollWebView.clearHistory();
4498 // Destroy the internal state of `mainWebView`.
4499 nestedScrollWebView.destroy();
4503 // Clear the custom headers.
4504 customHeaders.clear();
4506 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
4507 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
4508 if (clearEverything) {
4510 // Delete the folder.
4511 Process deleteAppWebviewProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
4513 // Wait until the process has finished.
4514 deleteAppWebviewProcess.waitFor();
4515 } catch (Exception exception) {
4516 // Do nothing if an error is thrown.
4520 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
4521 if (Build.VERSION.SDK_INT >= 21) {
4522 finishAndRemoveTask();
4527 // Remove the terminated program from RAM. The status code is `0`.
4531 private void setCurrentWebView(int pageNumber) {
4532 // Get a handle for the shared preferences.
4533 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4535 // Get the theme preference.
4536 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
4538 // Get handles for the URL views.
4539 RelativeLayout urlRelativeLayout = findViewById(R.id.url_relativelayout);
4540 EditText urlEditText = findViewById(R.id.url_edittext);
4541 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
4543 // Stop the swipe to refresh indicator if it is running
4544 swipeRefreshLayout.setRefreshing(false);
4546 // Get the WebView tab fragment.
4547 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(pageNumber);
4549 // Get the fragment view.
4550 View fragmentView = webViewTabFragment.getView();
4552 // Set the current WebView if the fragment view is not null.
4553 if (fragmentView != null) { // The fragment has been populated.
4554 // Store the current WebView.
4555 currentWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4557 // Update the status of swipe to refresh.
4558 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
4559 // Enable the swipe refresh layout if the WebView is scrolled all the way to the top. It is updated every time the scroll changes.
4560 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
4561 } else { // Swipe to refresh is disabled.
4562 // Disable the swipe refresh layout.
4563 swipeRefreshLayout.setEnabled(false);
4566 // Get a handle for the cookie manager.
4567 CookieManager cookieManager = CookieManager.getInstance();
4569 // Set the first-party cookie status.
4570 cookieManager.setAcceptCookie(currentWebView.getAcceptFirstPartyCookies());
4572 // Update the privacy icons. `true` redraws the icons in the app bar.
4573 updatePrivacyIcons(true);
4575 // Get a handle for the input method manager.
4576 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
4578 // Remove the lint warning below that the input method manager might be null.
4579 assert inputMethodManager != null;
4581 // Get the current URL.
4582 String url = currentWebView.getUrl();
4584 // Update the URL edit text if not loading a new intent. Otherwise, this will be handled by `onPageStarted()` (if called) and `onPageFinished()`.
4585 if (!loadingNewIntent) { // A new intent is not being loaded.
4586 if ((url == null) || url.equals("about:blank")) { // The WebView is blank.
4587 // Display the hint in the URL edit text.
4588 urlEditText.setText("");
4590 // Request focus for the URL text box.
4591 urlEditText.requestFocus();
4593 // Display the keyboard.
4594 inputMethodManager.showSoftInput(urlEditText, 0);
4595 } else { // The WebView has a loaded URL.
4596 // Clear the focus from the URL text box.
4597 urlEditText.clearFocus();
4599 // Hide the soft keyboard.
4600 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
4602 // Display the current URL in the URL text box.
4603 urlEditText.setText(url);
4605 // Highlight the URL text.
4608 } else { // A new intent is being loaded.
4609 // Reset the loading new intent tracker.
4610 loadingNewIntent = false;
4613 // Set the background to indicate the domain settings status.
4614 if (currentWebView.getDomainSettingsApplied()) {
4615 // Set a green background on the URL relative layout to indicate that custom domain settings are being used. The deprecated `.getDrawable()` must be used until the minimum API >= 21.
4617 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
4619 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
4622 urlRelativeLayout.setBackground(getResources().getDrawable(R.color.transparent));
4624 } else { // The fragment has not been populated. Try again in 100 milliseconds.
4625 // Create a handler to set the current WebView.
4626 Handler setCurrentWebViewHandler = new Handler();
4628 // Create a runnable to set the current WebView.
4629 Runnable setCurrentWebWebRunnable = () -> {
4630 // Set the current WebView.
4631 setCurrentWebView(pageNumber);
4634 // Try setting the current WebView again after 100 milliseconds.
4635 setCurrentWebViewHandler.postDelayed(setCurrentWebWebRunnable, 100);
4640 public void initializeWebView(NestedScrollWebView nestedScrollWebView, int pageNumber, ProgressBar progressBar, String url) {
4641 // Get handles for the activity views.
4642 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
4643 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
4644 RelativeLayout mainContentRelativeLayout = findViewById(R.id.main_content_relativelayout);
4645 ActionBar actionBar = getSupportActionBar();
4646 LinearLayout tabsLinearLayout = findViewById(R.id.tabs_linearlayout);
4647 EditText urlEditText = findViewById(R.id.url_edittext);
4648 TabLayout tabLayout = findViewById(R.id.tablayout);
4649 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
4651 // Remove the incorrect lint warning below that the action bar might be null.
4652 assert actionBar != null;
4654 // Get a handle for the activity
4655 Activity activity = this;
4657 // Get a handle for the input method manager.
4658 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
4660 // Instantiate the blocklist helper.
4661 BlocklistHelper blocklistHelper = new BlocklistHelper();
4663 // Remove the lint warning below that the input method manager might be null.
4664 assert inputMethodManager != null;
4666 // Get a handle for the shared preferences.
4667 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4669 // Initialize the favorite icon.
4670 nestedScrollWebView.initializeFavoriteIcon();
4672 // Set the app bar scrolling.
4673 nestedScrollWebView.setNestedScrollingEnabled(sharedPreferences.getBoolean("scroll_app_bar", true));
4675 // Allow pinch to zoom.
4676 nestedScrollWebView.getSettings().setBuiltInZoomControls(true);
4678 // Hide zoom controls.
4679 nestedScrollWebView.getSettings().setDisplayZoomControls(false);
4681 // Don't allow mixed content (HTTP and HTTPS) on the same website.
4682 if (Build.VERSION.SDK_INT >= 21) {
4683 nestedScrollWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW);
4686 // Set the WebView to load in overview mode (zoomed out to the maximum width).
4687 nestedScrollWebView.getSettings().setLoadWithOverviewMode(true);
4689 // Explicitly disable geolocation.
4690 nestedScrollWebView.getSettings().setGeolocationEnabled(false);
4692 // Create a double-tap gesture detector to toggle full-screen mode.
4693 GestureDetector doubleTapGestureDetector = new GestureDetector(getApplicationContext(), new GestureDetector.SimpleOnGestureListener() {
4694 // Override `onDoubleTap()`. All other events are handled using the default settings.
4696 public boolean onDoubleTap(MotionEvent event) {
4697 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
4698 // Toggle the full screen browsing mode tracker.
4699 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
4701 // Toggle the full screen browsing mode.
4702 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
4703 // Store the swipe refresh layout top padding.
4704 swipeRefreshLayoutPaddingTop = swipeRefreshLayout.getPaddingTop();
4706 // Hide the app bar if specified.
4708 // Close the find on page bar if it is visible.
4709 closeFindOnPage(null);
4711 // Hide the tab linear layout.
4712 tabsLinearLayout.setVisibility(View.GONE);
4714 // Hide the action bar.
4717 // Check to see if app bar scrolling is disabled.
4718 if (!scrollAppBar) {
4719 // Remove the padding from the top of the swipe refresh layout.
4720 swipeRefreshLayout.setPadding(0, 0, 0, 0);
4724 // Hide the banner ad in the free flavor.
4725 if (BuildConfig.FLAVOR.contentEquals("free")) {
4726 AdHelper.hideAd(findViewById(R.id.adview));
4729 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
4730 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4732 /* Hide the system bars.
4733 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4734 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4735 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4736 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4738 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
4739 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
4740 } else { // Switch to normal viewing mode.
4741 // Show the tab linear layout.
4742 tabsLinearLayout.setVisibility(View.VISIBLE);
4744 // Show the action bar.
4747 // Check to see if app bar scrolling is disabled.
4748 if (!scrollAppBar) {
4749 // Add the padding from the top of the swipe refresh layout.
4750 swipeRefreshLayout.setPadding(0, swipeRefreshLayoutPaddingTop, 0, 0);
4753 // Show the banner ad in the free flavor.
4754 if (BuildConfig.FLAVOR.contentEquals("free")) {
4756 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
4759 // Remove the `SYSTEM_UI` flags from the root frame layout.
4760 rootFrameLayout.setSystemUiVisibility(0);
4762 // Add the translucent status flag.
4763 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4766 // Consume the double-tap.
4768 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
4774 // Pass all touch events on the WebView through the double-tap gesture detector.
4775 nestedScrollWebView.setOnTouchListener((View view, MotionEvent event) -> {
4776 // Call `performClick()` on the view, which is required for accessibility.
4777 view.performClick();
4779 // Send the event to the gesture detector.
4780 return doubleTapGestureDetector.onTouchEvent(event);
4783 // Register the WebView for a context menu. This is used to see link targets and download images.
4784 registerForContextMenu(nestedScrollWebView);
4786 // Allow the downloading of files.
4787 nestedScrollWebView.setDownloadListener((String downloadUrl, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
4788 // Check if the download should be processed by an external app.
4789 if (sharedPreferences.getBoolean("download_with_external_app", false)) { // Download with an external app.
4790 // Create a download intent. Not specifying the action type will display the maximum number of options.
4791 Intent downloadIntent = new Intent();
4793 // Set the URI and the MIME type. Specifying `text/html` displays a good number of options.
4794 downloadIntent.setDataAndType(Uri.parse(downloadUrl), "text/html");
4796 // Flag the intent to open in a new task.
4797 downloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4799 // Show the chooser.
4800 startActivity(Intent.createChooser(downloadIntent, getString(R.string.open_with)));
4801 } else { // Download with Android's download manager.
4802 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
4803 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission has not been granted.
4804 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
4806 // Store the variables for future use by `onRequestPermissionsResult()`.
4807 this.downloadUrl = downloadUrl;
4808 downloadContentDisposition = contentDisposition;
4809 downloadContentLength = contentLength;
4811 // Show a dialog if the user has previously denied the permission.
4812 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
4813 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
4814 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
4816 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
4817 downloadLocationPermissionDialogFragment.show(getSupportFragmentManager(), getString(R.string.download_location));
4818 } else { // Show the permission request directly.
4819 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
4820 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
4822 } else { // The storage permission has already been granted.
4823 // Get a handle for the download file alert dialog.
4824 DialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(downloadUrl, contentDisposition, contentLength);
4826 // Show the download file alert dialog.
4827 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
4832 // Update the find on page count.
4833 nestedScrollWebView.setFindListener(new WebView.FindListener() {
4834 // Get a handle for `findOnPageCountTextView`.
4835 final TextView findOnPageCountTextView = findViewById(R.id.find_on_page_count_textview);
4838 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
4839 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
4840 // Set `findOnPageCountTextView` to `0/0`.
4841 findOnPageCountTextView.setText(R.string.zero_of_zero);
4842 } else if (isDoneCounting) { // There are matches.
4843 // `activeMatchOrdinal` is zero-based.
4844 int activeMatch = activeMatchOrdinal + 1;
4846 // Build the match string.
4847 String matchString = activeMatch + "/" + numberOfMatches;
4849 // Set `findOnPageCountTextView`.
4850 findOnPageCountTextView.setText(matchString);
4855 // Update the status of swipe to refresh based on the scroll position of the nested scroll WebView.
4856 // Once the minimum API >= 23 this can be replaced with `nestedScrollWebView.setOnScrollChangeListener()`.
4857 nestedScrollWebView.getViewTreeObserver().addOnScrollChangedListener(() -> {
4858 if (nestedScrollWebView.getSwipeToRefresh()) {
4859 // Only enable swipe to refresh if the WebView is scrolled to the top.
4860 swipeRefreshLayout.setEnabled(nestedScrollWebView.getScrollY() == 0);
4864 // Set the web chrome client.
4865 nestedScrollWebView.setWebChromeClient(new WebChromeClient() {
4866 // Update the progress bar when a page is loading.
4868 public void onProgressChanged(WebView view, int progress) {
4869 // Inject the night mode CSS if night mode is enabled.
4870 if (nestedScrollWebView.getNightMode()) { // Night mode is enabled.
4871 // `background-color: #212121` sets the background to be dark gray. `color: #BDBDBD` sets the text color to be light gray. `box-shadow: none` removes a lower underline on links
4872 // used by WordPress. `text-decoration: none` removes all text underlines. `text-shadow: none` removes text shadows, which usually have a hard coded color.
4873 // `border: none` removes all borders, which can also be used to underline text. `a {color: #1565C0}` sets links to be a dark blue.
4874 // `::selection {background: #0D47A1}' sets the text selection highlight color to be a dark blue. `!important` takes precedent over any existing sub-settings.
4875 nestedScrollWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; " +
4876 "style.innerHTML = '* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important;" +
4877 "text-shadow: none !important; border: none !important;} a {color: #1565C0 !important;} ::selection {background: #0D47A1 !important;}'; parent.appendChild(style)})()", value -> {
4878 // Initialize a handler to display `mainWebView`.
4879 Handler displayWebViewHandler = new Handler();
4881 // Setup a runnable to display `mainWebView` after a delay to allow the CSS to be applied.
4882 Runnable displayWebViewRunnable = () -> {
4883 // Only display `mainWebView` if the progress bar is gone. This prevents the display of the `WebView` while it is still loading.
4884 if (progressBar.getVisibility() == View.GONE) {
4885 nestedScrollWebView.setVisibility(View.VISIBLE);
4889 // Display the WebView after 500 milliseconds.
4890 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
4892 } else { // Night mode is disabled.
4893 // Display the nested scroll WebView if night mode is disabled.
4894 // Because of a race condition between `applyDomainSettings` and `onPageStarted`,
4895 // when night mode is set by domain settings the WebView may be hidden even if night mode is not currently enabled.
4896 nestedScrollWebView.setVisibility(View.VISIBLE);
4899 // Update the progress bar.
4900 progressBar.setProgress(progress);
4902 // Set the visibility of the progress bar.
4903 if (progress < 100) {
4904 // Show the progress bar.
4905 progressBar.setVisibility(View.VISIBLE);
4907 // Hide the progress bar.
4908 progressBar.setVisibility(View.GONE);
4910 //Stop the swipe to refresh indicator if it is running
4911 swipeRefreshLayout.setRefreshing(false);
4915 // Set the favorite icon when it changes.
4917 public void onReceivedIcon(WebView view, Bitmap icon) {
4918 // Only update the favorite icon if the website has finished loading.
4919 if (progressBar.getVisibility() == View.GONE) {
4920 // Store the new favorite icon.
4921 nestedScrollWebView.setFavoriteOrDefaultIcon(icon);
4923 // Get the current page position.
4924 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
4926 // Get the current tab.
4927 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
4929 // Check to see if the tab has been populated.
4931 // Get the custom view from the tab.
4932 View tabView = tab.getCustomView();
4934 // Check to see if the custom tab view has been populated.
4935 if (tabView != null) {
4936 // Get the favorite icon image view from the tab.
4937 ImageView tabFavoriteIconImageView = tabView.findViewById(R.id.favorite_icon_imageview);
4939 // Display the favorite icon in the tab.
4940 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
4946 // Save a copy of the title when it changes.
4948 public void onReceivedTitle(WebView view, String title) {
4949 // Get the current page position.
4950 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
4952 // Get the current tab.
4953 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
4955 // Only populate the title text view if the tab has been fully created.
4957 // Get the custom view from the tab.
4958 View tabView = tab.getCustomView();
4960 // Remove the incorrect warning below that the current tab view might be null.
4961 assert tabView != null;
4963 // Get the title text view from the tab.
4964 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
4966 // Set the title according to the URL.
4967 if (title.equals("about:blank")) {
4968 // Set the title to indicate a new tab.
4969 tabTitleTextView.setText(R.string.new_tab);
4971 // Set the title as the tab text.
4972 tabTitleTextView.setText(title);
4977 // Enter full screen video.
4979 public void onShowCustomView(View video, CustomViewCallback callback) {
4980 // Get a handle for the full screen video frame layout.
4981 FrameLayout fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
4983 // Set the full screen video flag.
4984 displayingFullScreenVideo = true;
4986 // Pause the ad if this is the free flavor.
4987 if (BuildConfig.FLAVOR.contentEquals("free")) {
4988 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
4989 AdHelper.pauseAd(findViewById(R.id.adview));
4992 // Hide the keyboard.
4993 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
4995 // Hide the main content relative layout.
4996 mainContentRelativeLayout.setVisibility(View.GONE);
4998 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
4999 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
5001 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
5002 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
5004 /* Hide the system bars.
5005 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5006 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5007 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5008 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5010 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5011 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5013 // Disable the sliding drawers.
5014 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
5016 // Add the video view to the full screen video frame layout.
5017 fullScreenVideoFrameLayout.addView(video);
5019 // Show the full screen video frame layout.
5020 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
5023 // Exit full screen video.
5025 public void onHideCustomView() {
5026 // Get a handle for the full screen video frame layout.
5027 FrameLayout fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
5029 // Unset the full screen video flag.
5030 displayingFullScreenVideo = false;
5032 // Remove all the views from the full screen video frame layout.
5033 fullScreenVideoFrameLayout.removeAllViews();
5035 // Hide the full screen video frame layout.
5036 fullScreenVideoFrameLayout.setVisibility(View.GONE);
5038 // Enable the sliding drawers.
5039 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
5041 // Show the main content relative layout.
5042 mainContentRelativeLayout.setVisibility(View.VISIBLE);
5044 // Apply the appropriate full screen mode flags.
5045 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
5046 // Hide the app bar if specified.
5048 // Hide the tab linear layout.
5049 tabsLinearLayout.setVisibility(View.GONE);
5051 // Hide the action bar.
5055 // Hide the banner ad in the free flavor.
5056 if (BuildConfig.FLAVOR.contentEquals("free")) {
5057 AdHelper.hideAd(findViewById(R.id.adview));
5060 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
5061 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
5063 /* Hide the system bars.
5064 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5065 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5066 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5067 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5069 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5070 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5071 } else { // Switch to normal viewing mode.
5072 // Remove the `SYSTEM_UI` flags from the root frame layout.
5073 rootFrameLayout.setSystemUiVisibility(0);
5075 // Add the translucent status flag.
5076 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
5079 // Reload the ad for the free flavor if not in full screen mode.
5080 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
5082 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
5088 public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
5089 // Show the file chooser if the device is running API >= 21.
5090 if (Build.VERSION.SDK_INT >= 21) {
5091 // Store the file path callback.
5092 fileChooserCallback = filePathCallback;
5094 // Create an intent to open a chooser based ont the file chooser parameters.
5095 Intent fileChooserIntent = fileChooserParams.createIntent();
5097 // Open the file chooser.
5098 startActivityForResult(fileChooserIntent, FILE_UPLOAD_REQUEST_CODE);
5104 nestedScrollWebView.setWebViewClient(new WebViewClient() {
5105 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
5106 // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
5108 public boolean shouldOverrideUrlLoading(WebView view, String url) {
5109 // Sanitize the url.
5110 url = sanitizeUrl(url);
5112 if (url.startsWith("http")) { // Load the URL in Privacy Browser.
5113 // Apply the domain settings for the new URL. This doesn't do anything if the domain has not changed.
5114 boolean userAgentChanged = applyDomainSettings(nestedScrollWebView, url, true, false);
5116 // Check if the user agent has changed.
5117 if (userAgentChanged) {
5118 // Manually load the URL. The changing of the user agent will cause WebView to reload the previous URL.
5119 nestedScrollWebView.loadUrl(url, customHeaders);
5121 // Returning true indicates that Privacy Browser is manually handling the loading of the URL.
5124 // Returning false causes the current WebView to handle the URL and prevents it from adding redirects to the history list.
5127 } else if (url.startsWith("mailto:")) { // Load the email address in an external email program.
5128 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
5129 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
5131 // Parse the url and set it as the data for the intent.
5132 emailIntent.setData(Uri.parse(url));
5134 // Open the email program in a new task instead of as part of Privacy Browser.
5135 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5138 startActivity(emailIntent);
5140 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5142 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
5143 // Open the dialer and load the phone number, but wait for the user to place the call.
5144 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
5146 // Add the phone number to the intent.
5147 dialIntent.setData(Uri.parse(url));
5149 // Open the dialer in a new task instead of as part of Privacy Browser.
5150 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5153 startActivity(dialIntent);
5155 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5157 } else { // Load a system chooser to select an app that can handle the URL.
5158 // Open an app that can handle the URL.
5159 Intent genericIntent = new Intent(Intent.ACTION_VIEW);
5161 // Add the URL to the intent.
5162 genericIntent.setData(Uri.parse(url));
5164 // List all apps that can handle the URL instead of just opening the first one.
5165 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
5167 // Open the app in a new task instead of as part of Privacy Browser.
5168 genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5170 // Start the app or display a snackbar if no app is available to handle the URL.
5172 startActivity(genericIntent);
5173 } catch (ActivityNotFoundException exception) {
5174 Snackbar.make(nestedScrollWebView, getString(R.string.unrecognized_url) + " " + url, Snackbar.LENGTH_SHORT).show();
5177 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5182 // Check requests against the block lists. The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
5184 public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
5185 // 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.
5186 while (ultraPrivacy == null) {
5187 // The wait must be synchronized, which only lets one thread run on it at a time, or `java.lang.IllegalMonitorStateException` is thrown.
5188 synchronized (this) {
5190 // Check to see if the blocklists have been populated after 100 ms.
5192 } catch (InterruptedException exception) {
5198 // Sanitize the URL.
5199 url = sanitizeUrl(url);
5201 // Get a handle for the navigation view.
5202 NavigationView navigationView = findViewById(R.id.navigationview);
5204 // Get a handle for the navigation menu.
5205 Menu navigationMenu = navigationView.getMenu();
5207 // Get a handle for the navigation requests menu item. The menu is 0 based.
5208 MenuItem navigationRequestsMenuItem = navigationMenu.getItem(5);
5210 // Create an empty web resource response to be used if the resource request is blocked.
5211 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
5213 // Reset the whitelist results tracker.
5214 String[] whitelistResultStringArray = null;
5216 // Initialize the third party request tracker.
5217 boolean isThirdPartyRequest = false;
5219 // Get the current URL. `.getUrl()` throws an error because operations on the WebView cannot be made from this thread.
5220 String currentBaseDomain = nestedScrollWebView.getCurrentDomainName();
5222 // Store a copy of the current domain for use in later requests.
5223 String currentDomain = currentBaseDomain;
5225 // Nobody is happy when comparing null strings.
5226 if ((currentBaseDomain != null) && (url != null)) {
5227 // Convert the request URL to a URI.
5228 Uri requestUri = Uri.parse(url);
5230 // Get the request host name.
5231 String requestBaseDomain = requestUri.getHost();
5233 // Only check for third-party requests if the current base domain is not empty and the request domain is not null.
5234 if (!currentBaseDomain.isEmpty() && (requestBaseDomain != null)) {
5235 // Determine the current base domain.
5236 while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
5237 // Remove the first subdomain.
5238 currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
5241 // Determine the request base domain.
5242 while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
5243 // Remove the first subdomain.
5244 requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
5247 // Update the third party request tracker.
5248 isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
5252 // Get the current WebView page position.
5253 int webViewPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5255 // Determine if the WebView is currently displayed.
5256 boolean webViewDisplayed = (webViewPagePosition == tabLayout.getSelectedTabPosition());
5258 // Block third-party requests if enabled.
5259 if (isThirdPartyRequest && nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS)) {
5260 // Add the result to the resource requests.
5261 nestedScrollWebView.addResourceRequest(new String[]{BlocklistHelper.REQUEST_THIRD_PARTY, url});
5263 // Increment the blocked requests counters.
5264 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5265 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS);
5267 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5268 if (webViewDisplayed) {
5269 // Updating the UI must be run from the UI thread.
5270 activity.runOnUiThread(() -> {
5271 // Update the menu item titles.
5272 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5274 // Update the options menu if it has been populated.
5275 if (optionsMenu != null) {
5276 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5277 optionsMenu.findItem(R.id.block_all_third_party_requests).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " +
5278 getString(R.string.block_all_third_party_requests));
5283 // Return an empty web resource response.
5284 return emptyWebResourceResponse;
5287 // Check UltraPrivacy if it is enabled.
5288 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY)) {
5289 // Check the URL against UltraPrivacy.
5290 String[] ultraPrivacyResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraPrivacy);
5292 // Process the UltraPrivacy results.
5293 if (ultraPrivacyResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched UltraPrivacy's blacklist.
5294 // Add the result to the resource requests.
5295 nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5296 ultraPrivacyResults[5]});
5298 // Increment the blocked requests counters.
5299 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5300 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRA_PRIVACY);
5302 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5303 if (webViewDisplayed) {
5304 // Updating the UI must be run from the UI thread.
5305 activity.runOnUiThread(() -> {
5306 // Update the menu item titles.
5307 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5309 // Update the options menu if it has been populated.
5310 if (optionsMenu != null) {
5311 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5312 optionsMenu.findItem(R.id.ultraprivacy).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRA_PRIVACY) + " - " + getString(R.string.ultraprivacy));
5317 // The resource request was blocked. Return an empty web resource response.
5318 return emptyWebResourceResponse;
5319 } else if (ultraPrivacyResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched UltraPrivacy's whitelist.
5320 // Add a whitelist entry to the resource requests array.
5321 nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5322 ultraPrivacyResults[5]});
5324 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
5329 // Check EasyList if it is enabled.
5330 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST)) {
5331 // Check the URL against EasyList.
5332 String[] easyListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyList);
5334 // Process the EasyList results.
5335 if (easyListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched EasyList's blacklist.
5336 // Add the result to the resource requests.
5337 nestedScrollWebView.addResourceRequest(new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]});
5339 // Increment the blocked requests counters.
5340 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5341 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASY_LIST);
5343 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5344 if (webViewDisplayed) {
5345 // Updating the UI must be run from the UI thread.
5346 activity.runOnUiThread(() -> {
5347 // Update the menu item titles.
5348 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5350 // Update the options menu if it has been populated.
5351 if (optionsMenu != null) {
5352 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5353 optionsMenu.findItem(R.id.easylist).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASY_LIST) + " - " + getString(R.string.easylist));
5358 // The resource request was blocked. Return an empty web resource response.
5359 return emptyWebResourceResponse;
5360 } else if (easyListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched EasyList's whitelist.
5361 // Update the whitelist result string array tracker.
5362 whitelistResultStringArray = new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]};
5366 // Check EasyPrivacy if it is enabled.
5367 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY)) {
5368 // Check the URL against EasyPrivacy.
5369 String[] easyPrivacyResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyPrivacy);
5371 // Process the EasyPrivacy results.
5372 if (easyPrivacyResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched EasyPrivacy's blacklist.
5373 // Add the result to the resource requests.
5374 nestedScrollWebView.addResourceRequest(new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4],
5375 easyPrivacyResults[5]});
5377 // Increment the blocked requests counters.
5378 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5379 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASY_PRIVACY);
5381 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5382 if (webViewDisplayed) {
5383 // Updating the UI must be run from the UI thread.
5384 activity.runOnUiThread(() -> {
5385 // Update the menu item titles.
5386 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5388 // Update the options menu if it has been populated.
5389 if (optionsMenu != null) {
5390 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5391 optionsMenu.findItem(R.id.easyprivacy).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASY_PRIVACY) + " - " + getString(R.string.easyprivacy));
5396 // The resource request was blocked. Return an empty web resource response.
5397 return emptyWebResourceResponse;
5398 } else if (easyPrivacyResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched EasyPrivacy's whitelist.
5399 // Update the whitelist result string array tracker.
5400 whitelistResultStringArray = new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5]};
5404 // Check Fanboy’s Annoyance List if it is enabled.
5405 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST)) {
5406 // Check the URL against Fanboy's Annoyance List.
5407 String[] fanboysAnnoyanceListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList);
5409 // Process the Fanboy's Annoyance List results.
5410 if (fanboysAnnoyanceListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched Fanboy's Annoyance List's blacklist.
5411 // Add the result to the resource requests.
5412 nestedScrollWebView.addResourceRequest(new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5413 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]});
5415 // Increment the blocked requests counters.
5416 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5417 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST);
5419 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5420 if (webViewDisplayed) {
5421 // Updating the UI must be run from the UI thread.
5422 activity.runOnUiThread(() -> {
5423 // Update the menu item titles.
5424 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5426 // Update the options menu if it has been populated.
5427 if (optionsMenu != null) {
5428 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5429 optionsMenu.findItem(R.id.fanboys_annoyance_list).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " +
5430 getString(R.string.fanboys_annoyance_list));
5435 // The resource request was blocked. Return an empty web resource response.
5436 return emptyWebResourceResponse;
5437 } else if (fanboysAnnoyanceListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)){ // The resource request matched Fanboy's Annoyance List's whitelist.
5438 // Update the whitelist result string array tracker.
5439 whitelistResultStringArray = new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5440 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]};
5442 } else if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST)) { // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
5443 // Check the URL against Fanboy's Annoyance List.
5444 String[] fanboysSocialListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysSocialList);
5446 // Process the Fanboy's Social Blocking List results.
5447 if (fanboysSocialListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched Fanboy's Social Blocking List's blacklist.
5448 // Add the result to the resource requests.
5449 nestedScrollWebView.addResourceRequest(new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5450 fanboysSocialListResults[4], fanboysSocialListResults[5]});
5452 // Increment the blocked requests counters.
5453 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5454 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST);
5456 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5457 if (webViewDisplayed) {
5458 // Updating the UI must be run from the UI thread.
5459 activity.runOnUiThread(() -> {
5460 // Update the menu item titles.
5461 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5463 // Update the options menu if it has been populated.
5464 if (optionsMenu != null) {
5465 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5466 optionsMenu.findItem(R.id.fanboys_social_blocking_list).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " +
5467 getString(R.string.fanboys_social_blocking_list));
5472 // The resource request was blocked. Return an empty web resource response.
5473 return emptyWebResourceResponse;
5474 } else if (fanboysSocialListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched Fanboy's Social Blocking List's whitelist.
5475 // Update the whitelist result string array tracker.
5476 whitelistResultStringArray = new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5477 fanboysSocialListResults[4], fanboysSocialListResults[5]};
5481 // Add the request to the log because it hasn't been processed by any of the previous checks.
5482 if (whitelistResultStringArray != null) { // The request was processed by a whitelist.
5483 nestedScrollWebView.addResourceRequest(whitelistResultStringArray);
5484 } else { // The request didn't match any blocklist entry. Log it as a default request.
5485 nestedScrollWebView.addResourceRequest(new String[]{BlocklistHelper.REQUEST_DEFAULT, url});
5488 // The resource request has not been blocked. `return null` loads the requested resource.
5492 // Handle HTTP authentication requests.
5494 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
5495 // Store the handler.
5496 nestedScrollWebView.setHttpAuthHandler(handler);
5498 // Instantiate an HTTP authentication dialog.
5499 DialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm, nestedScrollWebView.getWebViewFragmentId());
5501 // Show the HTTP authentication dialog.
5502 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
5506 public void onPageStarted(WebView view, String url, Bitmap favicon) {
5507 // Get the preferences.
5508 boolean scrollAppBar = sharedPreferences.getBoolean("scroll_app_bar", true);
5509 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
5511 // Get a handler for the app bar layout.
5512 AppBarLayout appBarLayout = findViewById(R.id.appbar_layout);
5514 // Set the top padding of the swipe refresh layout according to the app bar scrolling preference.
5516 // No padding is needed because it will automatically be placed below the app bar layout due to the scrolling layout behavior.
5517 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5519 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5520 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10, defaultProgressViewEndOffset);
5522 // Get the app bar layout height. This can't be done in `applyAppSettings()` because the app bar is not yet populated.
5523 int appBarHeight = appBarLayout.getHeight();
5525 // The swipe refresh layout must be manually moved below the app bar layout.
5526 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0);
5528 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5529 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight);
5532 // Reset the list of resource requests.
5533 nestedScrollWebView.clearResourceRequests();
5535 // Reset the requests counters.
5536 nestedScrollWebView.resetRequestsCounters();
5538 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
5539 if (nestedScrollWebView.getNightMode()) {
5540 nestedScrollWebView.setVisibility(View.INVISIBLE);
5542 nestedScrollWebView.setVisibility(View.VISIBLE);
5545 // Hide the keyboard.
5546 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
5548 // Check to see if Privacy Browser is waiting on Orbot.
5549 if (!waitingForOrbot) { // Process the URL.
5550 // Get the current page position.
5551 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5553 // Update the URL text bar if the page is currently selected.
5554 if (tabLayout.getSelectedTabPosition() == currentPagePosition) {
5555 // Clear the focus from the URL edit text.
5556 urlEditText.clearFocus();
5558 // Display the formatted URL text.
5559 urlEditText.setText(url);
5561 // Apply text highlighting to `urlTextBox`.
5565 // Reset the list of host IP addresses.
5566 nestedScrollWebView.clearCurrentIpAddresses();
5568 // Get a URI for the current URL.
5569 Uri currentUri = Uri.parse(url);
5571 // Get the IP addresses for the host.
5572 new GetHostIpAddresses(activity, getSupportFragmentManager(), nestedScrollWebView).execute(currentUri.getHost());
5574 // Apply any custom domain settings if the URL was loaded by navigating history.
5575 if (nestedScrollWebView.getNavigatingHistory()) {
5576 // Reset navigating history.
5577 nestedScrollWebView.setNavigatingHistory(false);
5579 // Apply the domain settings.
5580 boolean userAgentChanged = applyDomainSettings(nestedScrollWebView, url, true, false);
5582 // Manually load the URL if the user agent has changed, which will have caused the previous URL to be reloaded.
5583 if (userAgentChanged) {
5588 // Replace Refresh with Stop if the options menu has been created. (The first WebView typically begins loading before the menu items are instantiated.)
5589 if (optionsMenu != null) {
5590 // Get a handle for the refresh menu item.
5591 MenuItem refreshMenuItem = optionsMenu.findItem(R.id.refresh);
5594 refreshMenuItem.setTitle(R.string.stop);
5596 // Get the app bar and theme preferences.
5597 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
5599 // If the icon is displayed in the AppBar, set it according to the theme.
5600 if (displayAdditionalAppBarIcons) {
5602 refreshMenuItem.setIcon(R.drawable.close_dark);
5604 refreshMenuItem.setIcon(R.drawable.close_light);
5612 public void onPageFinished(WebView view, String url) {
5613 // Flush any cookies to persistent storage. The cookie manager has become very lazy about flushing cookies in recent versions.
5614 if (nestedScrollWebView.getAcceptFirstPartyCookies() && Build.VERSION.SDK_INT >= 21) {
5615 CookieManager.getInstance().flush();
5618 // Update the Refresh menu item if the options menu has been created.
5619 if (optionsMenu != null) {
5620 // Get a handle for the refresh menu item.
5621 MenuItem refreshMenuItem = optionsMenu.findItem(R.id.refresh);
5623 // Reset the Refresh title.
5624 refreshMenuItem.setTitle(R.string.refresh);
5626 // Get the app bar and theme preferences.
5627 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
5628 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
5630 // If the icon is displayed in the AppBar, reset it according to the theme.
5631 if (displayAdditionalAppBarIcons) {
5633 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
5635 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
5640 // Clear the cache and history if Incognito Mode is enabled.
5641 if (incognitoModeEnabled) {
5642 // Clear the cache. `true` includes disk files.
5643 nestedScrollWebView.clearCache(true);
5645 // Clear the back/forward history.
5646 nestedScrollWebView.clearHistory();
5648 // Manually delete cache folders.
5650 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
5651 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
5652 String privateDataDirectoryString = getApplicationInfo().dataDir;
5654 // Delete the main cache directory.
5655 Runtime.getRuntime().exec("rm -rf " + privateDataDirectoryString + "/cache");
5657 // Delete the secondary `Service Worker` cache directory.
5658 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
5659 Runtime.getRuntime().exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
5660 } catch (IOException e) {
5661 // Do nothing if an error is thrown.
5665 // Update the URL text box and apply domain settings if not waiting on Orbot.
5666 if (!waitingForOrbot) {
5667 // Get the current page position.
5668 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5670 // Check the current website information against any pinned domain information if the current IP addresses have been loaded.
5671 if ((nestedScrollWebView.hasPinnedSslCertificate() || nestedScrollWebView.hasPinnedIpAddresses()) && nestedScrollWebView.hasCurrentIpAddresses() &&
5672 !nestedScrollWebView.ignorePinnedDomainInformation()) {
5673 CheckPinnedMismatchHelper.checkPinnedMismatch(getSupportFragmentManager(), nestedScrollWebView);
5676 // 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.
5677 String currentUrl = nestedScrollWebView.getUrl();
5679 // Get the current tab.
5680 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
5682 // Update the URL text bar if the page is currently selected and the user is not currently typing in the URL edit text.
5683 // Crash records show that, in some crazy way, it is possible for the current URL to be blank at this point.
5684 // Probably some sort of race condition when Privacy Browser is being resumed.
5685 if ((tabLayout.getSelectedTabPosition() == currentPagePosition) && !urlEditText.hasFocus() && (currentUrl != null)) {
5686 // Check to see if the URL is `about:blank`.
5687 if (currentUrl.equals("about:blank")) { // The WebView is blank.
5688 // Display the hint in the URL edit text.
5689 urlEditText.setText("");
5691 // Request focus for the URL text box.
5692 urlEditText.requestFocus();
5694 // Display the keyboard.
5695 inputMethodManager.showSoftInput(urlEditText, 0);
5697 // Apply the domain settings. This clears any settings from the previous domain.
5698 applyDomainSettings(nestedScrollWebView, "", true, false);
5700 // Only populate the title text view if the tab has been fully created.
5702 // Get the custom view from the tab.
5703 View tabView = tab.getCustomView();
5705 // Remove the incorrect warning below that the current tab view might be null.
5706 assert tabView != null;
5708 // Get the title text view from the tab.
5709 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
5711 // Set the title as the tab text.
5712 tabTitleTextView.setText(R.string.new_tab);
5714 } else { // The WebView has loaded a webpage.
5715 // Display the final URL. Getting the URL from the WebView instead of using the one provided by `onPageFinished()` makes websites like YouTube function correctly.
5716 urlEditText.setText(currentUrl);
5718 // Apply text highlighting to the URL.
5721 // Only populate the title text view if the tab has been fully created.
5723 // Get the custom view from the tab.
5724 View tabView = tab.getCustomView();
5726 // Remove the incorrect warning below that the current tab view might be null.
5727 assert tabView != null;
5729 // Get the title text view from the tab.
5730 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
5732 // Set the title as the tab text. Sometimes `onReceivedTitle()` is not called, especially when navigating history.
5733 tabTitleTextView.setText(nestedScrollWebView.getTitle());
5740 // Handle SSL Certificate errors.
5742 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
5743 // Get the current website SSL certificate.
5744 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
5746 // Extract the individual pieces of information from the current website SSL certificate.
5747 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
5748 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
5749 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
5750 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
5751 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
5752 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
5753 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
5754 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
5756 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
5757 if (nestedScrollWebView.hasPinnedSslCertificate()) {
5758 // Get the pinned SSL certificate.
5759 ArrayList<Object> pinnedSslCertificateArrayList = nestedScrollWebView.getPinnedSslCertificate();
5761 // Extract the arrays from the array list.
5762 String[] pinnedSslCertificateStringArray = (String[]) pinnedSslCertificateArrayList.get(0);
5763 Date[] pinnedSslCertificateDateArray = (Date[]) pinnedSslCertificateArrayList.get(1);
5765 // Check if the current SSL certificate matches the pinned certificate.
5766 if (currentWebsiteIssuedToCName.equals(pinnedSslCertificateStringArray[0]) && currentWebsiteIssuedToOName.equals(pinnedSslCertificateStringArray[1]) &&
5767 currentWebsiteIssuedToUName.equals(pinnedSslCertificateStringArray[2]) && currentWebsiteIssuedByCName.equals(pinnedSslCertificateStringArray[3]) &&
5768 currentWebsiteIssuedByOName.equals(pinnedSslCertificateStringArray[4]) && currentWebsiteIssuedByUName.equals(pinnedSslCertificateStringArray[5]) &&
5769 currentWebsiteSslStartDate.equals(pinnedSslCertificateDateArray[0]) && currentWebsiteSslEndDate.equals(pinnedSslCertificateDateArray[1])) {
5771 // An SSL certificate is pinned and matches the current domain certificate. Proceed to the website without displaying an error.
5774 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
5775 // Store the SSL error handler.
5776 nestedScrollWebView.setSslErrorHandler(handler);
5778 // Instantiate an SSL certificate error alert dialog.
5779 DialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error, nestedScrollWebView.getWebViewFragmentId());
5781 // Show the SSL certificate error dialog.
5782 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
5787 // Check to see if this is the first page.
5788 if (pageNumber == 0) {
5789 // Set this nested scroll WebView as the current WebView.
5790 currentWebView = nestedScrollWebView;
5792 // Apply the app settings from the shared preferences.
5795 // Load the website if not waiting for Orbot to connect.
5796 if (!waitingForOrbot) {
5797 // Get the intent that started the app.
5798 Intent launchingIntent = getIntent();
5800 // Get the information from the intent.
5801 String launchingIntentAction = launchingIntent.getAction();
5802 Uri launchingIntentUriData = launchingIntent.getData();
5804 // If the intent action is a web search, perform the search.
5805 if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) {
5806 // Create an encoded URL string.
5807 String encodedUrlString;
5809 // Sanitize the search input and convert it to a search.
5811 encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
5812 } catch (UnsupportedEncodingException exception) {
5813 encodedUrlString = "";
5816 // Load the completed search URL.
5817 loadUrl(searchURL + encodedUrlString);
5818 } else if (launchingIntentUriData != null){ // Check to see if the intent contains a new URL.
5819 // Load the URL from the intent.
5820 loadUrl(launchingIntentUriData.toString());
5821 } else { // The is no URL in the intent.
5822 // Select the homepage based on the proxy through Orbot status.
5823 if (proxyThroughOrbot) {
5824 // Load the Tor homepage.
5825 loadUrl(sharedPreferences.getString("tor_homepage", getString(R.string.tor_homepage_default_value)));
5827 // Load the normal homepage.
5828 loadUrl(sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
5832 } else { // This is not the first tab.
5833 // Apply the domain settings.
5834 applyDomainSettings(nestedScrollWebView, url, false, false);
5837 nestedScrollWebView.loadUrl(url, customHeaders);
5839 // Set the focus and display the keyboard if the URL is blank.
5840 if (url.equals("")) {
5841 // Request focus for the URL text box.
5842 urlEditText.requestFocus();
5844 // Create a display keyboard handler.
5845 Handler displayKeyboardHandler = new Handler();
5847 // Create a display keyboard runnable.
5848 Runnable displayKeyboardRunnable = () -> {
5849 // Display the keyboard.
5850 inputMethodManager.showSoftInput(urlEditText, 0);
5853 // Display the keyboard after 100 milliseconds, which leaves enough time for the tab to transition.
5854 displayKeyboardHandler.postDelayed(displayKeyboardRunnable, 100);