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.DownloadManager;
28 import android.app.SearchManager;
29 import android.content.ActivityNotFoundException;
30 import android.content.BroadcastReceiver;
31 import android.content.ClipData;
32 import android.content.ClipboardManager;
33 import android.content.Context;
34 import android.content.Intent;
35 import android.content.IntentFilter;
36 import android.content.SharedPreferences;
37 import android.content.pm.PackageManager;
38 import android.content.res.Configuration;
39 import android.database.Cursor;
40 import android.graphics.Bitmap;
41 import android.graphics.BitmapFactory;
42 import android.graphics.Typeface;
43 import android.graphics.drawable.BitmapDrawable;
44 import android.graphics.drawable.Drawable;
45 import android.net.Uri;
46 import android.net.http.SslCertificate;
47 import android.net.http.SslError;
48 import android.os.Build;
49 import android.os.Bundle;
50 import android.os.Environment;
51 import android.os.Handler;
52 import android.preference.PreferenceManager;
53 import android.print.PrintDocumentAdapter;
54 import android.print.PrintManager;
55 import android.text.Editable;
56 import android.text.Spanned;
57 import android.text.TextWatcher;
58 import android.text.style.ForegroundColorSpan;
59 import android.util.Patterns;
60 import android.view.ContextMenu;
61 import android.view.GestureDetector;
62 import android.view.KeyEvent;
63 import android.view.Menu;
64 import android.view.MenuItem;
65 import android.view.MotionEvent;
66 import android.view.View;
67 import android.view.ViewGroup;
68 import android.view.WindowManager;
69 import android.view.inputmethod.InputMethodManager;
70 import android.webkit.CookieManager;
71 import android.webkit.HttpAuthHandler;
72 import android.webkit.SslErrorHandler;
73 import android.webkit.ValueCallback;
74 import android.webkit.WebChromeClient;
75 import android.webkit.WebResourceResponse;
76 import android.webkit.WebSettings;
77 import android.webkit.WebStorage;
78 import android.webkit.WebView;
79 import android.webkit.WebViewClient;
80 import android.webkit.WebViewDatabase;
81 import android.widget.ArrayAdapter;
82 import android.widget.CursorAdapter;
83 import android.widget.EditText;
84 import android.widget.FrameLayout;
85 import android.widget.ImageView;
86 import android.widget.LinearLayout;
87 import android.widget.ListView;
88 import android.widget.ProgressBar;
89 import android.widget.RadioButton;
90 import android.widget.RelativeLayout;
91 import android.widget.TextView;
93 import androidx.annotation.NonNull;
94 import androidx.appcompat.app.ActionBar;
95 import androidx.appcompat.app.ActionBarDrawerToggle;
96 import androidx.appcompat.app.AppCompatActivity;
97 import androidx.appcompat.widget.Toolbar;
98 import androidx.coordinatorlayout.widget.CoordinatorLayout;
99 import androidx.core.app.ActivityCompat;
100 import androidx.core.content.ContextCompat;
101 import androidx.core.view.GravityCompat;
102 import androidx.drawerlayout.widget.DrawerLayout;
103 import androidx.fragment.app.DialogFragment;
104 import androidx.fragment.app.FragmentManager;
105 import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
106 import androidx.viewpager.widget.ViewPager;
108 import com.google.android.material.appbar.AppBarLayout;
109 import com.google.android.material.floatingactionbutton.FloatingActionButton;
110 import com.google.android.material.navigation.NavigationView;
111 import com.google.android.material.snackbar.Snackbar;
112 import com.google.android.material.tabs.TabLayout;
114 import com.stoutner.privacybrowser.BuildConfig;
115 import com.stoutner.privacybrowser.R;
116 import com.stoutner.privacybrowser.adapters.WebViewPagerAdapter;
117 import com.stoutner.privacybrowser.asynctasks.GetHostIpAddresses;
118 import com.stoutner.privacybrowser.asynctasks.PopulateBlocklists;
119 import com.stoutner.privacybrowser.dialogs.AdConsentDialog;
120 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
121 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
122 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
123 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
124 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
125 import com.stoutner.privacybrowser.dialogs.DownloadLocationPermissionDialog;
126 import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
127 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
128 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
129 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
130 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
131 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
132 import com.stoutner.privacybrowser.fragments.WebViewTabFragment;
133 import com.stoutner.privacybrowser.helpers.AdHelper;
134 import com.stoutner.privacybrowser.helpers.BlocklistHelper;
135 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
136 import com.stoutner.privacybrowser.helpers.CheckPinnedMismatchHelper;
137 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
138 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
139 import com.stoutner.privacybrowser.views.NestedScrollWebView;
141 import java.io.ByteArrayInputStream;
142 import java.io.ByteArrayOutputStream;
144 import java.io.IOException;
145 import java.io.UnsupportedEncodingException;
146 import java.net.MalformedURLException;
148 import java.net.URLDecoder;
149 import java.net.URLEncoder;
150 import java.util.ArrayList;
151 import java.util.Date;
152 import java.util.HashMap;
153 import java.util.HashSet;
154 import java.util.List;
155 import java.util.Map;
156 import java.util.Set;
158 // AppCompatActivity from android.support.v7.app.AppCompatActivity must be used to have access to the SupportActionBar until the minimum API is >= 21.
159 public class MainWebViewActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener,
160 DownloadFileDialog.DownloadFileListener, DownloadImageDialog.DownloadImageListener, DownloadLocationPermissionDialog.DownloadLocationPermissionDialogListener, EditBookmarkDialog.EditBookmarkListener,
161 EditBookmarkFolderDialog.EditBookmarkFolderListener, NavigationView.OnNavigationItemSelectedListener, PopulateBlocklists.PopulateBlocklistsListener, WebViewTabFragment.NewTabListener {
163 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`, `onResume()`, and `applyProxyThroughOrbot()`.
164 public static String orbotStatus;
166 // The WebView pager adapter is accessed from `HttpAuthenticationDialog`, `PinnedMismatchDialog`, and `SslCertificateErrorDialog`. It is also used in `onCreate()`, `onResume()`, and `addTab()`.
167 public static WebViewPagerAdapter webViewPagerAdapter;
169 // The load URL on restart variables are public static so they can be accessed from `BookmarksActivity`. They are used in `onRestart()`.
170 public static boolean loadUrlOnRestart;
171 public static String urlToLoadOnRestart;
173 // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onRestart()`.
174 public static boolean restartFromBookmarksActivity;
176 // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`,
177 // `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
178 public static String currentBookmarksFolder;
180 // The user agent constants are public static so they can be accessed from `SettingsFragment`, `DomainsActivity`, and `DomainSettingsFragment`.
181 public final static int UNRECOGNIZED_USER_AGENT = -1;
182 public final static int SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1;
183 public final static int SETTINGS_CUSTOM_USER_AGENT = 12;
184 public final static int DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0;
185 public final static int DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2;
186 public final static int DOMAINS_CUSTOM_USER_AGENT = 13;
190 // The current WebView is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
191 // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, `applyProxyThroughOrbot()`, and `applyDomainSettings()`.
192 private NestedScrollWebView currentWebView;
194 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
195 private final Map<String, String> customHeaders = new HashMap<>();
197 // The search URL is set in `applyProxyThroughOrbot()` and used in `onCreate()`, `onNewIntent()`, `loadURLFromTextBox()`, and `initializeWebView()`.
198 private String searchURL;
200 // The options menu is set in `onCreateOptionsMenu()` and used in `onOptionsItemSelected()`, `updatePrivacyIcons()`, and `initializeWebView()`.
201 private Menu optionsMenu;
203 // The blocklists are populated in `finishedPopulatingBlocklists()` and accessed from `initializeWebView()`.
204 private ArrayList<List<String[]>> easyList;
205 private ArrayList<List<String[]>> easyPrivacy;
206 private ArrayList<List<String[]>> fanboysAnnoyanceList;
207 private ArrayList<List<String[]>> fanboysSocialList;
208 private ArrayList<List<String[]>> ultraPrivacy;
210 // `webViewDefaultUserAgent` is used in `onCreate()` and `onPrepareOptionsMenu()`.
211 private String webViewDefaultUserAgent;
213 // `proxyThroughOrbot` is used in `onRestart()`, `onOptionsItemSelected()`, `applyAppSettings()`, and `applyProxyThroughOrbot()`.
214 private boolean proxyThroughOrbot;
216 // The incognito mode is set in `applyAppSettings()` and used in `initializeWebView()`.
217 private boolean incognitoModeEnabled;
219 // The full screen browsing mode tracker is set it `applyAppSettings()` and used in `initializeWebView()`.
220 private boolean fullScreenBrowsingModeEnabled;
222 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
223 private boolean inFullScreenBrowsingMode;
225 // The app bar trackers are set in `applyAppSettings()` and used in `initializeWebView()`.
226 private boolean hideAppBar;
227 private boolean scrollAppBar;
229 // The loading new intent tracker is set in `onNewIntent()` and used in `setCurrentWebView()`.
230 private boolean loadingNewIntent;
232 // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
233 private boolean reapplyDomainSettingsOnRestart;
235 // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
236 private boolean reapplyAppSettingsOnRestart;
238 // `displayingFullScreenVideo` is used in `onCreate()` and `onResume()`.
239 private boolean displayingFullScreenVideo;
241 // `orbotStatusBroadcastReceiver` is used in `onCreate()` and `onDestroy()`.
242 private BroadcastReceiver orbotStatusBroadcastReceiver;
244 // `waitingForOrbot` is used in `onCreate()`, `onResume()`, and `applyProxyThroughOrbot()`.
245 private boolean waitingForOrbot;
247 // The action bar drawer toggle is initialized in `onCreate()` and used in `onResume()`.
248 private ActionBarDrawerToggle actionBarDrawerToggle;
250 // The color spans are used in `onCreate()` and `highlightUrlText()`.
251 private ForegroundColorSpan redColorSpan;
252 private ForegroundColorSpan initialGrayColorSpan;
253 private ForegroundColorSpan finalGrayColorSpan;
255 // The drawer header padding variables are used in `onCreate()` and `onConfigurationChanged()`.
256 private int drawerHeaderPaddingLeftAndRight;
257 private int drawerHeaderPaddingTop;
258 private int drawerHeaderPaddingBottom;
260 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onDestroy`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`,
261 // and `loadBookmarksFolder()`.
262 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
264 // `bookmarksCursor` is used in `onDestroy()`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
265 private Cursor bookmarksCursor;
267 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
268 private CursorAdapter bookmarksCursorAdapter;
270 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
271 private String oldFolderNameString;
273 // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
274 private ValueCallback<Uri[]> fileChooserCallback;
276 // The default progress view offsets are set in `onCreate()` and used in `initializeWebView()`.
277 private int defaultProgressViewStartOffset;
278 private int defaultProgressViewEndOffset;
280 // The swipe refresh layout top padding is used when exiting full screen browsing mode. It is used in an inner class in `initializeWebView()`.
281 private int swipeRefreshLayoutPaddingTop;
283 // The URL sanitizers are set in `applyAppSettings()` and used in `sanitizeUrl()`.
284 private boolean sanitizeGoogleAnalytics;
285 private boolean sanitizeFacebookClickIds;
286 private boolean sanitizeTwitterAmpRedirects;
288 // The download strings are used in `onCreate()`, `onRequestPermissionResult()` and `initializeWebView()`.
289 private String downloadUrl;
290 private String downloadContentDisposition;
291 private long downloadContentLength;
293 // `downloadImageUrl` is used in `onCreateContextMenu()` and `onRequestPermissionResult()`.
294 private String downloadImageUrl;
296 // The request codes are used in `onCreate()`, `onCreateContextMenu()`, `onCloseDownloadLocationPermissionDialog()`, `onRequestPermissionResult()`, and `initializeWebView()`.
297 private final int DOWNLOAD_FILE_REQUEST_CODE = 1;
298 private final int DOWNLOAD_IMAGE_REQUEST_CODE = 2;
301 // Remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
302 @SuppressLint("ClickableViewAccessibility")
303 protected void onCreate(Bundle savedInstanceState) {
304 // Get a handle for the shared preferences.
305 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
307 // Get the theme and screenshot preferences.
308 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
309 boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
311 // Disable screenshots if not allowed.
312 if (!allowScreenshots) {
313 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
316 // Set the activity theme.
318 setTheme(R.style.PrivacyBrowserDark);
320 setTheme(R.style.PrivacyBrowserLight);
323 // Run the default commands.
324 super.onCreate(savedInstanceState);
326 // Set the content view.
327 setContentView(R.layout.main_framelayout);
329 // Get a handle for the input method.
330 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
332 // Remove the lint warning below that the input method manager might be null.
333 assert inputMethodManager != null;
335 // Get a handle for the toolbar.
336 Toolbar toolbar = findViewById(R.id.toolbar);
338 // Set the action bar. `SupportActionBar` must be used until the minimum API is >= 21.
339 setSupportActionBar(toolbar);
341 // Get a handle for the action bar.
342 ActionBar actionBar = getSupportActionBar();
344 // This is needed to get rid of the Android Studio warning that the action bar might be null.
345 assert actionBar != null;
347 // Add the custom layout, which shows the URL text bar.
348 actionBar.setCustomView(R.layout.url_app_bar);
349 actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
351 // Initialize the foreground color spans for highlighting the URLs. We have to use the deprecated `getColor()` until API >= 23.
352 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
353 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
354 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
356 // Get handles for the URL views.
357 EditText urlEditText = findViewById(R.id.url_edittext);
359 // Remove the formatting from `urlTextBar` when the user is editing the text.
360 urlEditText.setOnFocusChangeListener((View v, boolean hasFocus) -> {
361 if (hasFocus) { // The user is editing the URL text box.
362 // Remove the highlighting.
363 urlEditText.getText().removeSpan(redColorSpan);
364 urlEditText.getText().removeSpan(initialGrayColorSpan);
365 urlEditText.getText().removeSpan(finalGrayColorSpan);
366 } else { // The user has stopped editing the URL text box.
367 // Move to the beginning of the string.
368 urlEditText.setSelection(0);
370 // Reapply the highlighting.
375 // Set the go button on the keyboard to load the URL in `urlTextBox`.
376 urlEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
377 // If the event is a key-down event on the `enter` button, load the URL.
378 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
379 // Load the URL into the mainWebView and consume the event.
380 loadUrlFromTextBox();
382 // If the enter key was pressed, consume the event.
385 // If any other key was pressed, do not consume the event.
390 // Initialize the Orbot status and the waiting for Orbot trackers.
391 orbotStatus = "unknown";
392 waitingForOrbot = false;
394 // Create an Orbot status `BroadcastReceiver`.
395 orbotStatusBroadcastReceiver = new BroadcastReceiver() {
397 public void onReceive(Context context, Intent intent) {
398 // Store the content of the status message in `orbotStatus`.
399 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
401 // If Privacy Browser is waiting on Orbot, load the website now that Orbot is connected.
402 if (orbotStatus.equals("ON") && waitingForOrbot) {
403 // Reset the waiting for Orbot status.
404 waitingForOrbot = false;
406 // Get the intent that started the app.
407 Intent launchingIntent = getIntent();
409 // Get the information from the intent.
410 String launchingIntentAction = launchingIntent.getAction();
411 Uri launchingIntentUriData = launchingIntent.getData();
413 // If the intent action is a web search, perform the search.
414 if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) {
415 // Create an encoded URL string.
416 String encodedUrlString;
418 // Sanitize the search input and convert it to a search.
420 encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
421 } catch (UnsupportedEncodingException exception) {
422 encodedUrlString = "";
425 // Load the completed search URL.
426 loadUrl(searchURL + encodedUrlString);
427 } else if (launchingIntentUriData != null){ // Check to see if the intent contains a new URL.
428 // Load the URL from the intent.
429 loadUrl(launchingIntentUriData.toString());
430 } else { // The is no URL in the intent.
431 // Select the homepage based on the proxy through Orbot status.
432 if (proxyThroughOrbot) {
433 // Load the Tor homepage.
434 loadUrl(sharedPreferences.getString("tor_homepage", getString(R.string.tor_homepage_default_value)));
436 // Load the normal homepage.
437 loadUrl(sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
444 // Register `orbotStatusBroadcastReceiver` on `this` context.
445 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
447 // Get handles for views that need to be modified.
448 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
449 NavigationView navigationView = findViewById(R.id.navigationview);
450 TabLayout tabLayout = findViewById(R.id.tablayout);
451 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
452 ViewPager webViewPager = findViewById(R.id.webviewpager);
453 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
454 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
455 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
456 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
457 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
459 // Initially disable the sliding drawers. They will be enabled once the blocklists are loaded.
460 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
462 // Listen for touches on the navigation menu.
463 navigationView.setNavigationItemSelectedListener(this);
465 // Get handles for the navigation menu and the back and forward menu items. The menu is zero-based.
466 Menu navigationMenu = navigationView.getMenu();
467 MenuItem navigationBackMenuItem = navigationMenu.getItem(2);
468 MenuItem navigationForwardMenuItem = navigationMenu.getItem(3);
469 MenuItem navigationHistoryMenuItem = navigationMenu.getItem(4);
470 MenuItem navigationRequestsMenuItem = navigationMenu.getItem(5);
472 // Initialize the web view pager adapter.
473 webViewPagerAdapter = new WebViewPagerAdapter(getSupportFragmentManager());
475 // Set the pager adapter on the web view pager.
476 webViewPager.setAdapter(webViewPagerAdapter);
478 // Store up to 100 tabs in memory.
479 webViewPager.setOffscreenPageLimit(100);
481 // Update the web view pager every time a tab is modified.
482 webViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
484 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
489 public void onPageSelected(int position) {
490 // Close the find on page bar if it is open.
491 closeFindOnPage(null);
493 // Set the current WebView.
494 setCurrentWebView(position);
496 // 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.
497 if (tabLayout.getSelectedTabPosition() != position) {
498 // Create a handler to select the tab.
499 Handler selectTabHandler = new Handler();
501 // Create a runnable to select the tab.
502 Runnable selectTabRunnable = () -> {
503 // Get a handle for the tab.
504 TabLayout.Tab tab = tabLayout.getTabAt(position);
506 // Assert that the tab is not null.
513 // Select the tab layout after 150 milliseconds, which leaves enough time for a new tab to be inflated.
514 selectTabHandler.postDelayed(selectTabRunnable, 150);
519 public void onPageScrollStateChanged(int state) {
524 // Display the View SSL Certificate dialog when the currently selected tab is reselected.
525 tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
527 public void onTabSelected(TabLayout.Tab tab) {
528 // Select the same page in the view pager.
529 webViewPager.setCurrentItem(tab.getPosition());
533 public void onTabUnselected(TabLayout.Tab tab) {
538 public void onTabReselected(TabLayout.Tab tab) {
539 // Instantiate the View SSL Certificate dialog.
540 DialogFragment viewSslCertificateDialogFragment = ViewSslCertificateDialog.displayDialog(currentWebView.getWebViewFragmentId());
542 // Display the View SSL Certificate dialog.
543 viewSslCertificateDialogFragment.show(getSupportFragmentManager(), getString(R.string.view_ssl_certificate));
547 // 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.
548 // The deprecated `getResources().getDrawable()` must be used until the minimum API >= 21 and and `getResources().getColor()` must be used until the minimum API >= 23.
550 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
551 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
552 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
553 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
555 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
556 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
557 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
558 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
561 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
562 launchBookmarksActivityFab.setOnClickListener(v -> {
563 // Get a copy of the favorite icon bitmap.
564 Bitmap favoriteIconBitmap = currentWebView.getFavoriteOrDefaultIcon();
566 // Create a favorite icon byte array output stream.
567 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
569 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
570 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
572 // Convert the favorite icon byte array stream to a byte array.
573 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
575 // Create an intent to launch the bookmarks activity.
576 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
578 // Add the extra information to the intent.
579 bookmarksIntent.putExtra("current_url", currentWebView.getUrl());
580 bookmarksIntent.putExtra("current_title", currentWebView.getTitle());
581 bookmarksIntent.putExtra("current_folder", currentBookmarksFolder);
582 bookmarksIntent.putExtra("favorite_icon_byte_array", favoriteIconByteArray);
585 startActivity(bookmarksIntent);
588 // Set the create new bookmark folder FAB to display an alert dialog.
589 createBookmarkFolderFab.setOnClickListener(v -> {
590 // Create a create bookmark folder dialog.
591 DialogFragment createBookmarkFolderDialog = CreateBookmarkFolderDialog.createBookmarkFolder(currentWebView.getFavoriteOrDefaultIcon());
593 // Show the create bookmark folder dialog.
594 createBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.create_folder));
597 // Set the create new bookmark FAB to display an alert dialog.
598 createBookmarkFab.setOnClickListener(view -> {
599 // Instantiate the create bookmark dialog.
600 DialogFragment createBookmarkDialog = CreateBookmarkDialog.createBookmark(currentWebView.getUrl(), currentWebView.getTitle(), currentWebView.getFavoriteOrDefaultIcon());
602 // Display the create bookmark dialog.
603 createBookmarkDialog.show(getSupportFragmentManager(), getString(R.string.create_bookmark));
606 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
607 findOnPageEditText.addTextChangedListener(new TextWatcher() {
609 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
614 public void onTextChanged(CharSequence s, int start, int before, int count) {
619 public void afterTextChanged(Editable s) {
620 // 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.
621 if (currentWebView != null) {
622 currentWebView.findAllAsync(findOnPageEditText.getText().toString());
627 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
628 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
629 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
630 // Hide the soft keyboard.
631 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
633 // Consume the event.
635 } else { // A different key was pressed.
636 // Do not consume the event.
641 // Implement swipe to refresh.
642 swipeRefreshLayout.setOnRefreshListener(() -> currentWebView.reload());
644 // Store the default progress view offsets for use later in `initializeWebView()`.
645 defaultProgressViewStartOffset = swipeRefreshLayout.getProgressViewStartOffset();
646 defaultProgressViewEndOffset = swipeRefreshLayout.getProgressViewEndOffset();
648 // Set the swipe to refresh color according to the theme.
650 swipeRefreshLayout.setColorSchemeResources(R.color.blue_800);
651 swipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.gray_850);
653 swipeRefreshLayout.setColorSchemeResources(R.color.blue_500);
656 // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
657 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
658 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
660 // Initialize the bookmarks database helper. The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
661 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
663 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
664 currentBookmarksFolder = "";
666 // Load the home folder, which is `""` in the database.
667 loadBookmarksFolder();
669 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
670 // Convert the id from long to int to match the format of the bookmarks database.
671 int databaseID = (int) id;
673 // Get the bookmark cursor for this ID and move it to the first row.
674 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseID);
675 bookmarkCursor.moveToFirst();
677 // Act upon the bookmark according to the type.
678 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
679 // Store the new folder name in `currentBookmarksFolder`.
680 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
682 // Load the new folder.
683 loadBookmarksFolder();
684 } else { // The selected bookmark is not a folder.
685 // Load the bookmark URL.
686 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
688 // Close the bookmarks drawer.
689 drawerLayout.closeDrawer(GravityCompat.END);
692 // Close the `Cursor`.
693 bookmarkCursor.close();
696 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
697 // Convert the database ID from `long` to `int`.
698 int databaseId = (int) id;
700 // Find out if the selected bookmark is a folder.
701 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
704 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
705 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
707 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
708 DialogFragment editBookmarkFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId, currentWebView.getFavoriteOrDefaultIcon());
709 editBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.edit_folder));
711 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
712 DialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId, currentWebView.getFavoriteOrDefaultIcon());
713 editBookmarkDialog.show(getSupportFragmentManager(), getString(R.string.edit_bookmark));
716 // Consume the event.
720 // Get the status bar pixel size.
721 int statusBarResourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
722 int statusBarPixelSize = getResources().getDimensionPixelSize(statusBarResourceId);
724 // Get the resource density.
725 float screenDensity = getResources().getDisplayMetrics().density;
727 // Calculate the drawer header padding. This is used to move the text in the drawer headers below any cutouts.
728 drawerHeaderPaddingLeftAndRight = (int) (15 * screenDensity);
729 drawerHeaderPaddingTop = statusBarPixelSize + (int) (4 * screenDensity);
730 drawerHeaderPaddingBottom = (int) (8 * screenDensity);
732 // The drawer listener is used to update the navigation menu.`
733 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
735 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
739 public void onDrawerOpened(@NonNull View drawerView) {
743 public void onDrawerClosed(@NonNull View drawerView) {
747 public void onDrawerStateChanged(int newState) {
748 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // A drawer is opening or closing.
749 // Get handles for the drawer headers.
750 TextView navigationHeaderTextView = findViewById(R.id.navigationText);
751 TextView bookmarksHeaderTextView = findViewById(R.id.bookmarks_title_textview);
753 // 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.
754 if (navigationHeaderTextView != null) {
755 navigationHeaderTextView.setPadding(drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingTop, drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingBottom);
758 // 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.
759 if (bookmarksHeaderTextView != null) {
760 bookmarksHeaderTextView.setPadding(drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingTop, drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingBottom);
763 // Update the navigation menu items if the WebView is not null.
764 if (currentWebView != null) {
765 navigationBackMenuItem.setEnabled(currentWebView.canGoBack());
766 navigationForwardMenuItem.setEnabled(currentWebView.canGoForward());
767 navigationHistoryMenuItem.setEnabled((currentWebView.canGoBack() || currentWebView.canGoForward()));
768 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
770 // Hide the keyboard (if displayed).
771 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
774 // 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.
775 urlEditText.clearFocus();
776 currentWebView.clearFocus();
781 // Create the hamburger icon at the start of the AppBar.
782 actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
784 // 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).
785 customHeaders.put("X-Requested-With", "");
787 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
788 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
790 // Inflate a bare WebView to get the default user agent. It is not used to render content on the screen.
791 @SuppressLint("InflateParams") View webViewLayout = getLayoutInflater().inflate(R.layout.bare_webview, null, false);
793 // Get a handle for the WebView.
794 WebView bareWebView = webViewLayout.findViewById(R.id.bare_webview);
796 // Store the default user agent.
797 webViewDefaultUserAgent = bareWebView.getSettings().getUserAgentString();
799 // Destroy the bare WebView.
800 bareWebView.destroy();
802 // Populate the blocklists.
803 new PopulateBlocklists(this, this).execute();
807 protected void onNewIntent(Intent intent) {
808 // Get the information from the intent.
809 String intentAction = intent.getAction();
810 Uri intentUriData = intent.getData();
812 // Determine if this is a web search.
813 boolean isWebSearch = ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH));
815 // 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.
816 if (intentUriData != null || isWebSearch) {
817 // Get the shared preferences.
818 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
820 // Create a URL string.
823 // If the intent action is a web search, perform the search.
825 // Create an encoded URL string.
826 String encodedUrlString;
828 // Sanitize the search input and convert it to a search.
830 encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
831 } catch (UnsupportedEncodingException exception) {
832 encodedUrlString = "";
835 // Add the base search URL.
836 url = searchURL + encodedUrlString;
837 } else { // The intent should contain a URL.
838 // Set the intent data as the URL.
839 url = intentUriData.toString();
842 // Add a new tab if specified in the preferences.
843 if (sharedPreferences.getBoolean("open_intents_in_new_tab", true)) { // Load the URL in a new tab.
844 // Set the loading new intent flag.
845 loadingNewIntent = true;
849 } else { // Load the URL in the current tab.
854 // Get a handle for the drawer layout.
855 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
857 // Close the navigation drawer if it is open.
858 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
859 drawerLayout.closeDrawer(GravityCompat.START);
862 // Close the bookmarks drawer if it is open.
863 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
864 drawerLayout.closeDrawer(GravityCompat.END);
870 public void onRestart() {
871 // Run the default commands.
874 // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
875 if (proxyThroughOrbot) {
876 // Request Orbot to start. If Orbot is already running no hard will be caused by this request.
877 Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
879 // Send the intent to the Orbot package.
880 orbotIntent.setPackage("org.torproject.android");
883 sendBroadcast(orbotIntent);
886 // Apply the app settings if returning from the Settings activity.
887 if (reapplyAppSettingsOnRestart) {
888 // Reset the reapply app settings on restart tracker.
889 reapplyAppSettingsOnRestart = false;
891 // Apply the app settings.
895 // Apply the domain settings if returning from the settings or domains activity.
896 if (reapplyDomainSettingsOnRestart) {
897 // Reset the reapply domain settings on restart tracker.
898 reapplyDomainSettingsOnRestart = false;
900 // Reapply the domain settings for each tab.
901 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
902 // Get the WebView tab fragment.
903 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
905 // Get the fragment view.
906 View fragmentView = webViewTabFragment.getView();
908 // Only reload the WebViews if they exist.
909 if (fragmentView != null) {
910 // Get the nested scroll WebView from the tab fragment.
911 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
913 // Reset the current domain name so the domain settings will be reapplied.
914 nestedScrollWebView.resetCurrentDomainName();
916 // Reapply the domain settings if the URL is not null, which can happen if an empty tab is active when returning from settings.
917 if (nestedScrollWebView.getUrl() != null) {
918 applyDomainSettings(nestedScrollWebView, nestedScrollWebView.getUrl(), false, true);
924 // Load the URL on restart (used when loading a bookmark).
925 if (loadUrlOnRestart) {
926 // Load the specified URL.
927 loadUrl(urlToLoadOnRestart);
929 // Reset the load on restart tracker.
930 loadUrlOnRestart = false;
933 // Update the bookmarks drawer if returning from the Bookmarks activity.
934 if (restartFromBookmarksActivity) {
935 // Get a handle for the drawer layout.
936 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
938 // Close the bookmarks drawer.
939 drawerLayout.closeDrawer(GravityCompat.END);
941 // Reload the bookmarks drawer.
942 loadBookmarksFolder();
944 // Reset `restartFromBookmarksActivity`.
945 restartFromBookmarksActivity = false;
948 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
949 updatePrivacyIcons(true);
952 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
954 public void onResume() {
955 // Run the default commands.
958 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
959 // Get the WebView tab fragment.
960 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
962 // Get the fragment view.
963 View fragmentView = webViewTabFragment.getView();
965 // Only resume the WebViews if they exist (they won't when the app is first created).
966 if (fragmentView != null) {
967 // Get the nested scroll WebView from the tab fragment.
968 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
970 // Resume the nested scroll WebView JavaScript timers.
971 nestedScrollWebView.resumeTimers();
973 // Resume the nested scroll WebView.
974 nestedScrollWebView.onResume();
978 // Display a message to the user if waiting for Orbot.
979 if (waitingForOrbot && !orbotStatus.equals("ON")) {
980 // Disable the wide view port so that the waiting for Orbot text is displayed correctly.
981 currentWebView.getSettings().setUseWideViewPort(false);
983 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
984 currentWebView.loadData("<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>", "text/html", null);
987 if (displayingFullScreenVideo || inFullScreenBrowsingMode) {
988 // Get a handle for the root frame layouts.
989 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
991 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
992 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
994 /* Hide the system bars.
995 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
996 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
997 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
998 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1000 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
1001 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1002 } else if (BuildConfig.FLAVOR.contentEquals("free")) { // Resume the adView for the free flavor.
1004 AdHelper.resumeAd(findViewById(R.id.adview));
1009 public void onPause() {
1010 // Run the default commands.
1013 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
1014 // Get the WebView tab fragment.
1015 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
1017 // Get the fragment view.
1018 View fragmentView = webViewTabFragment.getView();
1020 // Only pause the WebViews if they exist (they won't when the app is first created).
1021 if (fragmentView != null) {
1022 // Get the nested scroll WebView from the tab fragment.
1023 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
1025 // Pause the nested scroll WebView.
1026 nestedScrollWebView.onPause();
1028 // Pause the nested scroll WebView JavaScript timers.
1029 nestedScrollWebView.pauseTimers();
1033 // Pause the ad or it will continue to consume resources in the background on the free flavor.
1034 if (BuildConfig.FLAVOR.contentEquals("free")) {
1036 AdHelper.pauseAd(findViewById(R.id.adview));
1041 public void onDestroy() {
1042 // Unregister the Orbot status broadcast receiver.
1043 this.unregisterReceiver(orbotStatusBroadcastReceiver);
1045 // Close the bookmarks cursor and database.
1046 bookmarksCursor.close();
1047 bookmarksDatabaseHelper.close();
1049 // Run the default commands.
1054 public boolean onCreateOptionsMenu(Menu menu) {
1055 // Inflate the menu. This adds items to the action bar if it is present.
1056 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1058 // Store a handle for the options menu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons()`.
1061 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1062 updatePrivacyIcons(false);
1064 // Get handles for the menu items.
1065 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1066 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1067 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1068 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
1069 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
1070 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1071 MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
1073 // Only display third-party cookies if API >= 21
1074 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1076 // Only display the form data menu items if the API < 26.
1077 toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1078 clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1080 // Disable the clear form data menu item if the API >= 26 so that the status of the main Clear Data is calculated correctly.
1081 clearFormDataMenuItem.setEnabled(Build.VERSION.SDK_INT < 26);
1083 // Only show Ad Consent if this is the free flavor.
1084 adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
1086 // Get the shared preferences.
1087 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1089 // Get the dark theme and app bar preferences..
1090 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
1091 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
1093 // 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.
1094 if (displayAdditionalAppBarIcons) {
1095 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1096 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1097 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
1098 } else { //Do not display the additional icons.
1099 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1100 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1101 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1104 // Replace Refresh with Stop if a URL is already loading.
1105 if (currentWebView != null && currentWebView.getProgress() != 100) {
1107 refreshMenuItem.setTitle(R.string.stop);
1109 // If the icon is displayed in the AppBar, set it according to the theme.
1110 if (displayAdditionalAppBarIcons) {
1112 refreshMenuItem.setIcon(R.drawable.close_dark);
1114 refreshMenuItem.setIcon(R.drawable.close_light);
1123 public boolean onPrepareOptionsMenu(Menu menu) {
1124 // Get handles for the menu items.
1125 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
1126 MenuItem firstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1127 MenuItem thirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1128 MenuItem domStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1129 MenuItem saveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
1130 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
1131 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1132 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1133 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
1134 MenuItem blocklistsMenuItem = menu.findItem(R.id.blocklists);
1135 MenuItem easyListMenuItem = menu.findItem(R.id.easylist);
1136 MenuItem easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
1137 MenuItem fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
1138 MenuItem fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
1139 MenuItem ultraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
1140 MenuItem blockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
1141 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1142 MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
1143 MenuItem wideViewportMenuItem = menu.findItem(R.id.wide_viewport);
1144 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1145 MenuItem nightModeMenuItem = menu.findItem(R.id.night_mode);
1146 MenuItem proxyThroughOrbotMenuItem = menu.findItem(R.id.proxy_through_orbot);
1148 // Get a handle for the cookie manager.
1149 CookieManager cookieManager = CookieManager.getInstance();
1151 // Initialize the current user agent string and the font size.
1152 String currentUserAgent = getString(R.string.user_agent_privacy_browser);
1155 // 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.
1156 if (currentWebView != null) {
1157 // Set the add or edit domain text.
1158 if (currentWebView.getDomainSettingsApplied()) {
1159 addOrEditDomain.setTitle(R.string.edit_domain_settings);
1161 addOrEditDomain.setTitle(R.string.add_domain_settings);
1164 // Get the current user agent from the WebView.
1165 currentUserAgent = currentWebView.getSettings().getUserAgentString();
1167 // Get the current font size from the
1168 fontSize = currentWebView.getSettings().getTextZoom();
1170 // Set the status of the menu item checkboxes.
1171 domStorageMenuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1172 saveFormDataMenuItem.setChecked(currentWebView.getSettings().getSaveFormData()); // Form data can be removed once the minimum API >= 26.
1173 easyListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST));
1174 easyPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY));
1175 fanboysAnnoyanceListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1176 fanboysSocialBlockingListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1177 ultraPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY));
1178 blockAllThirdPartyRequestsMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1179 swipeToRefreshMenuItem.setChecked(currentWebView.getSwipeToRefresh());
1180 wideViewportMenuItem.setChecked(currentWebView.getSettings().getUseWideViewPort());
1181 displayImagesMenuItem.setChecked(currentWebView.getSettings().getLoadsImagesAutomatically());
1182 nightModeMenuItem.setChecked(currentWebView.getNightMode());
1184 // Initialize the display names for the blocklists with the number of blocked requests.
1185 blocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
1186 easyListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASY_LIST) + " - " + getString(R.string.easylist));
1187 easyPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASY_PRIVACY) + " - " + getString(R.string.easyprivacy));
1188 fanboysAnnoyanceListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " + getString(R.string.fanboys_annoyance_list));
1189 fanboysSocialBlockingListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " + getString(R.string.fanboys_social_blocking_list));
1190 ultraPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRA_PRIVACY) + " - " + getString(R.string.ultraprivacy));
1191 blockAllThirdPartyRequestsMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " + getString(R.string.block_all_third_party_requests));
1193 // Only modify third-party cookies if the API >= 21.
1194 if (Build.VERSION.SDK_INT >= 21) {
1195 // Set the status of the third-party cookies checkbox.
1196 thirdPartyCookiesMenuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
1198 // Enable third-party cookies if first-party cookies are enabled.
1199 thirdPartyCookiesMenuItem.setEnabled(cookieManager.acceptCookie());
1202 // Enable DOM Storage if JavaScript is enabled.
1203 domStorageMenuItem.setEnabled(currentWebView.getSettings().getJavaScriptEnabled());
1206 // Set the status of the menu item checkboxes.
1207 firstPartyCookiesMenuItem.setChecked(cookieManager.acceptCookie());
1208 proxyThroughOrbotMenuItem.setChecked(proxyThroughOrbot);
1210 // Enable Clear Cookies if there are any.
1211 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1213 // 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`.
1214 String privateDataDirectoryString = getApplicationInfo().dataDir;
1216 // Get a count of the number of files in the Local Storage directory.
1217 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1218 int localStorageDirectoryNumberOfFiles = 0;
1219 if (localStorageDirectory.exists()) {
1220 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1223 // Get a count of the number of files in the IndexedDB directory.
1224 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1225 int indexedDBDirectoryNumberOfFiles = 0;
1226 if (indexedDBDirectory.exists()) {
1227 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1230 // Enable Clear DOM Storage if there is any.
1231 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1233 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
1234 if (Build.VERSION.SDK_INT < 26) {
1235 // Get the WebView database.
1236 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1238 // Enable the clear form data menu item if there is anything to clear.
1239 clearFormDataMenuItem.setEnabled(webViewDatabase.hasFormData());
1242 // Enable Clear Data if any of the submenu items are enabled.
1243 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
1245 // Disable Fanboy's Social Blocking List menu item if Fanboy's Annoyance List is checked.
1246 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListMenuItem.isChecked());
1248 // Select the current user agent menu item. A switch statement cannot be used because the user agents are not compile time constants.
1249 if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) { // Privacy Browser.
1250 menu.findItem(R.id.user_agent_privacy_browser).setChecked(true);
1251 } else if (currentUserAgent.equals(webViewDefaultUserAgent)) { // WebView Default.
1252 menu.findItem(R.id.user_agent_webview_default).setChecked(true);
1253 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) { // Firefox on Android.
1254 menu.findItem(R.id.user_agent_firefox_on_android).setChecked(true);
1255 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) { // Chrome on Android.
1256 menu.findItem(R.id.user_agent_chrome_on_android).setChecked(true);
1257 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) { // Safari on iOS.
1258 menu.findItem(R.id.user_agent_safari_on_ios).setChecked(true);
1259 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) { // Firefox on Linux.
1260 menu.findItem(R.id.user_agent_firefox_on_linux).setChecked(true);
1261 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) { // Chromium on Linux.
1262 menu.findItem(R.id.user_agent_chromium_on_linux).setChecked(true);
1263 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) { // Firefox on Windows.
1264 menu.findItem(R.id.user_agent_firefox_on_windows).setChecked(true);
1265 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) { // Chrome on Windows.
1266 menu.findItem(R.id.user_agent_chrome_on_windows).setChecked(true);
1267 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) { // Edge on Windows.
1268 menu.findItem(R.id.user_agent_edge_on_windows).setChecked(true);
1269 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) { // Internet Explorer on Windows.
1270 menu.findItem(R.id.user_agent_internet_explorer_on_windows).setChecked(true);
1271 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) { // Safari on macOS.
1272 menu.findItem(R.id.user_agent_safari_on_macos).setChecked(true);
1273 } else { // Custom user agent.
1274 menu.findItem(R.id.user_agent_custom).setChecked(true);
1277 // Instantiate the font size title and the selected font size menu item.
1278 String fontSizeTitle;
1279 MenuItem selectedFontSizeMenuItem;
1281 // Prepare the font size title and current size menu item.
1284 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
1285 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1289 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
1290 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1294 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
1295 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1299 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1300 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1304 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
1305 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1309 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
1310 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1314 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
1315 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1319 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
1320 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1324 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1325 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1329 // Set the font size title and select the current size menu item.
1330 fontSizeMenuItem.setTitle(fontSizeTitle);
1331 selectedFontSizeMenuItem.setChecked(true);
1333 // Run all the other default commands.
1334 super.onPrepareOptionsMenu(menu);
1336 // Display the menu.
1341 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1342 @SuppressLint("SetJavaScriptEnabled")
1343 public boolean onOptionsItemSelected(MenuItem menuItem) {
1344 // Reenter full screen browsing mode if it was interrupted by the options menu. <https://redmine.stoutner.com/issues/389>
1345 if (inFullScreenBrowsingMode) {
1346 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
1347 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1349 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
1351 /* Hide the system bars.
1352 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1353 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
1354 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1355 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1357 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
1358 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1361 // Get the selected menu item ID.
1362 int menuItemId = menuItem.getItemId();
1364 // Get a handle for the shared preferences.
1365 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1367 // Get a handle for the cookie manager.
1368 CookieManager cookieManager = CookieManager.getInstance();
1370 // Run the commands that correlate to the selected menu item.
1371 switch (menuItemId) {
1372 case R.id.toggle_javascript:
1373 // Toggle the JavaScript status.
1374 currentWebView.getSettings().setJavaScriptEnabled(!currentWebView.getSettings().getJavaScriptEnabled());
1376 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1377 updatePrivacyIcons(true);
1379 // Display a `Snackbar`.
1380 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScrip is enabled.
1381 Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1382 } else if (cookieManager.acceptCookie()) { // JavaScript is disabled, but first-party cookies are enabled.
1383 Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1384 } else { // Privacy mode.
1385 Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1388 // Reload the current WebView.
1389 currentWebView.reload();
1392 case R.id.add_or_edit_domain:
1393 if (currentWebView.getDomainSettingsApplied()) { // Edit the current domain settings.
1394 // Reapply the domain settings on returning to `MainWebViewActivity`.
1395 reapplyDomainSettingsOnRestart = true;
1397 // Create an intent to launch the domains activity.
1398 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1400 // Add the extra information to the intent.
1401 domainsIntent.putExtra("load_domain", currentWebView.getDomainSettingsDatabaseId());
1402 domainsIntent.putExtra("close_on_back", true);
1403 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1405 // Get the current certificate.
1406 SslCertificate sslCertificate = currentWebView.getCertificate();
1408 // Check to see if the SSL certificate is populated.
1409 if (sslCertificate != null) {
1410 // Extract the certificate to strings.
1411 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1412 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1413 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1414 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1415 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1416 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1417 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1418 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1420 // Add the certificate to the intent.
1421 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1422 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1423 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1424 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1425 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1426 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1427 domainsIntent.putExtra("ssl_start_date", startDateLong);
1428 domainsIntent.putExtra("ssl_end_date", endDateLong);
1431 // Check to see if the current IP addresses have been received.
1432 if (currentWebView.hasCurrentIpAddresses()) {
1433 // Add the current IP addresses to the intent.
1434 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1438 startActivity(domainsIntent);
1439 } else { // Add a new domain.
1440 // Apply the new domain settings on returning to `MainWebViewActivity`.
1441 reapplyDomainSettingsOnRestart = true;
1443 // Get the current domain
1444 Uri currentUri = Uri.parse(currentWebView.getUrl());
1445 String currentDomain = currentUri.getHost();
1447 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1448 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1450 // Create the domain and store the database ID.
1451 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1453 // Create an intent to launch the domains activity.
1454 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1456 // Add the extra information to the intent.
1457 domainsIntent.putExtra("load_domain", newDomainDatabaseId);
1458 domainsIntent.putExtra("close_on_back", true);
1459 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1461 // Get the current certificate.
1462 SslCertificate sslCertificate = currentWebView.getCertificate();
1464 // Check to see if the SSL certificate is populated.
1465 if (sslCertificate != null) {
1466 // Extract the certificate to strings.
1467 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1468 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1469 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1470 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1471 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1472 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1473 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1474 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1476 // Add the certificate to the intent.
1477 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1478 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1479 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1480 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1481 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1482 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1483 domainsIntent.putExtra("ssl_start_date", startDateLong);
1484 domainsIntent.putExtra("ssl_end_date", endDateLong);
1487 // Check to see if the current IP addresses have been received.
1488 if (currentWebView.hasCurrentIpAddresses()) {
1489 // Add the current IP addresses to the intent.
1490 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1494 startActivity(domainsIntent);
1498 case R.id.toggle_first_party_cookies:
1499 // Switch the first-party cookie status.
1500 cookieManager.setAcceptCookie(!cookieManager.acceptCookie());
1502 // Store the first-party cookie status.
1503 currentWebView.setAcceptFirstPartyCookies(cookieManager.acceptCookie());
1505 // Update the menu checkbox.
1506 menuItem.setChecked(cookieManager.acceptCookie());
1508 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1509 updatePrivacyIcons(true);
1511 // Display a snackbar.
1512 if (cookieManager.acceptCookie()) { // First-party cookies are enabled.
1513 Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1514 } else if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is still enabled.
1515 Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1516 } else { // Privacy mode.
1517 Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1520 // Reload the current WebView.
1521 currentWebView.reload();
1524 case R.id.toggle_third_party_cookies:
1525 if (Build.VERSION.SDK_INT >= 21) {
1526 // Switch the status of thirdPartyCookiesEnabled.
1527 cookieManager.setAcceptThirdPartyCookies(currentWebView, !cookieManager.acceptThirdPartyCookies(currentWebView));
1529 // Update the menu checkbox.
1530 menuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
1532 // Display a snackbar.
1533 if (cookieManager.acceptThirdPartyCookies(currentWebView)) {
1534 Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1536 Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1539 // Reload the current WebView.
1540 currentWebView.reload();
1541 } // Else do nothing because SDK < 21.
1544 case R.id.toggle_dom_storage:
1545 // Toggle the status of domStorageEnabled.
1546 currentWebView.getSettings().setDomStorageEnabled(!currentWebView.getSettings().getDomStorageEnabled());
1548 // Update the menu checkbox.
1549 menuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1551 // Update the privacy icon. `true` refreshes the app bar icons.
1552 updatePrivacyIcons(true);
1554 // Display a snackbar.
1555 if (currentWebView.getSettings().getDomStorageEnabled()) {
1556 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1558 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1561 // Reload the current WebView.
1562 currentWebView.reload();
1565 // Form data can be removed once the minimum API >= 26.
1566 case R.id.toggle_save_form_data:
1567 // Switch the status of saveFormDataEnabled.
1568 currentWebView.getSettings().setSaveFormData(!currentWebView.getSettings().getSaveFormData());
1570 // Update the menu checkbox.
1571 menuItem.setChecked(currentWebView.getSettings().getSaveFormData());
1573 // Display a snackbar.
1574 if (currentWebView.getSettings().getSaveFormData()) {
1575 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1577 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1580 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1581 updatePrivacyIcons(true);
1583 // Reload the current WebView.
1584 currentWebView.reload();
1587 case R.id.clear_cookies:
1588 Snackbar.make(findViewById(R.id.webviewpager), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1589 .setAction(R.string.undo, v -> {
1590 // Do nothing because everything will be handled by `onDismissed()` below.
1592 .addCallback(new Snackbar.Callback() {
1593 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1595 public void onDismissed(Snackbar snackbar, int event) {
1596 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1597 // Delete the cookies, which command varies by SDK.
1598 if (Build.VERSION.SDK_INT < 21) {
1599 cookieManager.removeAllCookie();
1601 cookieManager.removeAllCookies(null);
1609 case R.id.clear_dom_storage:
1610 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1611 .setAction(R.string.undo, v -> {
1612 // Do nothing because everything will be handled by `onDismissed()` below.
1614 .addCallback(new Snackbar.Callback() {
1615 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1617 public void onDismissed(Snackbar snackbar, int event) {
1618 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1619 // Delete the DOM Storage.
1620 WebStorage webStorage = WebStorage.getInstance();
1621 webStorage.deleteAllData();
1623 // Initialize a handler to manually delete the DOM storage files and directories.
1624 Handler deleteDomStorageHandler = new Handler();
1626 // Setup a runnable to manually delete the DOM storage files and directories.
1627 Runnable deleteDomStorageRunnable = () -> {
1629 // Get a handle for the runtime.
1630 Runtime runtime = Runtime.getRuntime();
1632 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
1633 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
1634 String privateDataDirectoryString = getApplicationInfo().dataDir;
1636 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1637 Process deleteLocalStorageProcess = runtime.exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1639 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1640 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1641 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1642 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1643 Process deleteDatabasesProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1645 // Wait for the processes to finish.
1646 deleteLocalStorageProcess.waitFor();
1647 deleteIndexProcess.waitFor();
1648 deleteQuotaManagerProcess.waitFor();
1649 deleteQuotaManagerJournalProcess.waitFor();
1650 deleteDatabasesProcess.waitFor();
1651 } catch (Exception exception) {
1652 // Do nothing if an error is thrown.
1656 // Manually delete the DOM storage files after 200 milliseconds.
1657 deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200);
1664 // Form data can be remove once the minimum API >= 26.
1665 case R.id.clear_form_data:
1666 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1667 .setAction(R.string.undo, v -> {
1668 // Do nothing because everything will be handled by `onDismissed()` below.
1670 .addCallback(new Snackbar.Callback() {
1671 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1673 public void onDismissed(Snackbar snackbar, int event) {
1674 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1675 // Delete the form data.
1676 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1677 mainWebViewDatabase.clearFormData();
1685 // Toggle the EasyList status.
1686 currentWebView.enableBlocklist(NestedScrollWebView.EASY_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST));
1688 // Update the menu checkbox.
1689 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST));
1691 // Reload the current WebView.
1692 currentWebView.reload();
1695 case R.id.easyprivacy:
1696 // Toggle the EasyPrivacy status.
1697 currentWebView.enableBlocklist(NestedScrollWebView.EASY_PRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY));
1699 // Update the menu checkbox.
1700 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY));
1702 // Reload the current WebView.
1703 currentWebView.reload();
1706 case R.id.fanboys_annoyance_list:
1707 // Toggle Fanboy's Annoyance List status.
1708 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1710 // Update the menu checkbox.
1711 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1713 // Update the staus of Fanboy's Social Blocking List.
1714 MenuItem fanboysSocialBlockingListMenuItem = optionsMenu.findItem(R.id.fanboys_social_blocking_list);
1715 fanboysSocialBlockingListMenuItem.setEnabled(!currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1717 // Reload the current WebView.
1718 currentWebView.reload();
1721 case R.id.fanboys_social_blocking_list:
1722 // Toggle Fanboy's Social Blocking List status.
1723 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1725 // Update the menu checkbox.
1726 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1728 // Reload the current WebView.
1729 currentWebView.reload();
1732 case R.id.ultraprivacy:
1733 // Toggle the UltraPrivacy status.
1734 currentWebView.enableBlocklist(NestedScrollWebView.ULTRA_PRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY));
1736 // Update the menu checkbox.
1737 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY));
1739 // Reload the current WebView.
1740 currentWebView.reload();
1743 case R.id.block_all_third_party_requests:
1744 //Toggle the third-party requests blocker status.
1745 currentWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, !currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1747 // Update the menu checkbox.
1748 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1750 // Reload the current WebView.
1751 currentWebView.reload();
1754 case R.id.user_agent_privacy_browser:
1755 // Update the user agent.
1756 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
1758 // Reload the current WebView.
1759 currentWebView.reload();
1762 case R.id.user_agent_webview_default:
1763 // Update the user agent.
1764 currentWebView.getSettings().setUserAgentString("");
1766 // Reload the current WebView.
1767 currentWebView.reload();
1770 case R.id.user_agent_firefox_on_android:
1771 // Update the user agent.
1772 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
1774 // Reload the current WebView.
1775 currentWebView.reload();
1778 case R.id.user_agent_chrome_on_android:
1779 // Update the user agent.
1780 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
1782 // Reload the current WebView.
1783 currentWebView.reload();
1786 case R.id.user_agent_safari_on_ios:
1787 // Update the user agent.
1788 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
1790 // Reload the current WebView.
1791 currentWebView.reload();
1794 case R.id.user_agent_firefox_on_linux:
1795 // Update the user agent.
1796 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
1798 // Reload the current WebView.
1799 currentWebView.reload();
1802 case R.id.user_agent_chromium_on_linux:
1803 // Update the user agent.
1804 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
1806 // Reload the current WebView.
1807 currentWebView.reload();
1810 case R.id.user_agent_firefox_on_windows:
1811 // Update the user agent.
1812 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
1814 // Reload the current WebView.
1815 currentWebView.reload();
1818 case R.id.user_agent_chrome_on_windows:
1819 // Update the user agent.
1820 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
1822 // Reload the current WebView.
1823 currentWebView.reload();
1826 case R.id.user_agent_edge_on_windows:
1827 // Update the user agent.
1828 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
1830 // Reload the current WebView.
1831 currentWebView.reload();
1834 case R.id.user_agent_internet_explorer_on_windows:
1835 // Update the user agent.
1836 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
1838 // Reload the current WebView.
1839 currentWebView.reload();
1842 case R.id.user_agent_safari_on_macos:
1843 // Update the user agent.
1844 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
1846 // Reload the current WebView.
1847 currentWebView.reload();
1850 case R.id.user_agent_custom:
1851 // Update the user agent.
1852 currentWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
1854 // Reload the current WebView.
1855 currentWebView.reload();
1858 case R.id.font_size_twenty_five_percent:
1859 currentWebView.getSettings().setTextZoom(25);
1862 case R.id.font_size_fifty_percent:
1863 currentWebView.getSettings().setTextZoom(50);
1866 case R.id.font_size_seventy_five_percent:
1867 currentWebView.getSettings().setTextZoom(75);
1870 case R.id.font_size_one_hundred_percent:
1871 currentWebView.getSettings().setTextZoom(100);
1874 case R.id.font_size_one_hundred_twenty_five_percent:
1875 currentWebView.getSettings().setTextZoom(125);
1878 case R.id.font_size_one_hundred_fifty_percent:
1879 currentWebView.getSettings().setTextZoom(150);
1882 case R.id.font_size_one_hundred_seventy_five_percent:
1883 currentWebView.getSettings().setTextZoom(175);
1886 case R.id.font_size_two_hundred_percent:
1887 currentWebView.getSettings().setTextZoom(200);
1890 case R.id.swipe_to_refresh:
1891 // Toggle the stored status of swipe to refresh.
1892 currentWebView.setSwipeToRefresh(!currentWebView.getSwipeToRefresh());
1894 // Get a handle for the swipe refresh layout.
1895 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
1897 // Update the swipe refresh layout.
1898 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
1899 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
1900 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
1901 } else { // Swipe to refresh is disabled.
1902 // Disable the swipe refresh layout.
1903 swipeRefreshLayout.setEnabled(false);
1907 case R.id.wide_viewport:
1908 // Toggle the viewport.
1909 currentWebView.getSettings().setUseWideViewPort(!currentWebView.getSettings().getUseWideViewPort());
1912 case R.id.display_images:
1913 if (currentWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1914 // Disable loading of images.
1915 currentWebView.getSettings().setLoadsImagesAutomatically(false);
1917 // Reload the website to remove existing images.
1918 currentWebView.reload();
1919 } else { // Images are not currently loaded automatically.
1920 // Enable loading of images. Missing images will be loaded without the need for a reload.
1921 currentWebView.getSettings().setLoadsImagesAutomatically(true);
1925 case R.id.night_mode:
1926 // Toggle night mode.
1927 currentWebView.setNightMode(!currentWebView.getNightMode());
1929 // Enable or disable JavaScript according to night mode, the global preference, and any domain settings.
1930 if (currentWebView.getNightMode()) { // Night mode is enabled, which requires JavaScript.
1931 // Enable JavaScript.
1932 currentWebView.getSettings().setJavaScriptEnabled(true);
1933 } else if (currentWebView.getDomainSettingsApplied()) { // Night mode is disabled and domain settings are applied. Set JavaScript according to the domain settings.
1934 // Apply the JavaScript preference that was stored the last time domain settings were loaded.
1935 currentWebView.getSettings().setJavaScriptEnabled(currentWebView.getDomainSettingsJavaScriptEnabled());
1936 } else { // Night mode is disabled and domain settings are not applied. Set JavaScript according to the global preference.
1937 // Apply the JavaScript preference.
1938 currentWebView.getSettings().setJavaScriptEnabled(sharedPreferences.getBoolean("javascript", false));
1941 // Update the privacy icons.
1942 updatePrivacyIcons(false);
1944 // Reload the website.
1945 currentWebView.reload();
1948 case R.id.find_on_page:
1949 // Get a handle for the views.
1950 Toolbar toolbar = findViewById(R.id.toolbar);
1951 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
1952 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
1954 // Set the minimum height of the find on page linear layout to match the toolbar.
1955 findOnPageLinearLayout.setMinimumHeight(toolbar.getHeight());
1957 // Hide the toolbar.
1958 toolbar.setVisibility(View.GONE);
1960 // Show the find on page linear layout.
1961 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1963 // Display the keyboard. The app must wait 200 ms before running the command to work around a bug in Android.
1964 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1965 findOnPageEditText.postDelayed(() -> {
1966 // Set the focus on `findOnPageEditText`.
1967 findOnPageEditText.requestFocus();
1969 // Get a handle for the input method manager.
1970 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1972 // Remove the lint warning below that the input method manager might be null.
1973 assert inputMethodManager != null;
1975 // Display the keyboard. `0` sets no input flags.
1976 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1981 // Get a print manager instance.
1982 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1984 // Remove the lint error below that print manager might be null.
1985 assert printManager != null;
1987 // Create a print document adapter from the current WebView.
1988 PrintDocumentAdapter printDocumentAdapter = currentWebView.createPrintDocumentAdapter();
1990 // Print the document.
1991 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1994 case R.id.add_to_homescreen:
1995 // Instantiate the create home screen shortcut dialog.
1996 DialogFragment createHomeScreenShortcutDialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView.getTitle(), currentWebView.getUrl(),
1997 currentWebView.getFavoriteOrDefaultIcon());
1999 // Show the create home screen shortcut dialog.
2000 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2003 case R.id.view_source:
2004 // Create an intent to launch the view source activity.
2005 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
2007 // Add the variables to the intent.
2008 viewSourceIntent.putExtra("user_agent", currentWebView.getSettings().getUserAgentString());
2009 viewSourceIntent.putExtra("current_url", currentWebView.getUrl());
2012 startActivity(viewSourceIntent);
2015 case R.id.share_url:
2016 // Setup the share string.
2017 String shareString = currentWebView.getTitle() + " – " + currentWebView.getUrl();
2019 // Create the share intent.
2020 Intent shareIntent = new Intent(Intent.ACTION_SEND);
2021 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
2022 shareIntent.setType("text/plain");
2025 startActivity(Intent.createChooser(shareIntent, getString(R.string.share_url)));
2028 case R.id.open_with_app:
2029 openWithApp(currentWebView.getUrl());
2032 case R.id.open_with_browser:
2033 openWithBrowser(currentWebView.getUrl());
2036 case R.id.proxy_through_orbot:
2037 // Toggle the proxy through Orbot variable.
2038 proxyThroughOrbot = !proxyThroughOrbot;
2040 // Apply the proxy through Orbot settings.
2041 applyProxyThroughOrbot(true);
2045 if (menuItem.getTitle().equals(getString(R.string.refresh))) { // The refresh button was pushed.
2046 // Reload the current WebView.
2047 currentWebView.reload();
2048 } else { // The stop button was pushed.
2049 // Stop the loading of the WebView.
2050 currentWebView.stopLoading();
2054 case R.id.ad_consent:
2055 // Display the ad consent dialog.
2056 DialogFragment adConsentDialogFragment = new AdConsentDialog();
2057 adConsentDialogFragment.show(getSupportFragmentManager(), getString(R.string.ad_consent));
2061 // Don't consume the event.
2062 return super.onOptionsItemSelected(menuItem);
2066 // removeAllCookies is deprecated, but it is required for API < 21.
2068 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2069 // Get the menu item ID.
2070 int menuItemId = menuItem.getItemId();
2072 // Get a handle for the shared preferences.
2073 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2075 // Run the commands that correspond to the selected menu item.
2076 switch (menuItemId) {
2077 case R.id.clear_and_exit:
2078 // Clear and exit Privacy Browser.
2083 // Select the homepage based on the proxy through Orbot status.
2084 if (proxyThroughOrbot) {
2085 // Load the Tor homepage.
2086 loadUrl(sharedPreferences.getString("tor_homepage", getString(R.string.tor_homepage_default_value)));
2088 // Load the normal homepage.
2089 loadUrl(sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
2094 if (currentWebView.canGoBack()) {
2095 // Reset the current domain name so that navigation works if third-party requests are blocked.
2096 currentWebView.resetCurrentDomainName();
2098 // Set navigating history so that the domain settings are applied when the new URL is loaded.
2099 currentWebView.setNavigatingHistory(true);
2101 // Load the previous website in the history.
2102 currentWebView.goBack();
2107 if (currentWebView.canGoForward()) {
2108 // Reset the current domain name so that navigation works if third-party requests are blocked.
2109 currentWebView.resetCurrentDomainName();
2111 // Set navigating history so that the domain settings are applied when the new URL is loaded.
2112 currentWebView.setNavigatingHistory(true);
2114 // Load the next website in the history.
2115 currentWebView.goForward();
2120 // Instantiate the URL history dialog.
2121 DialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(currentWebView.getWebViewFragmentId());
2123 // Show the URL history dialog.
2124 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2128 // Populate the resource requests.
2129 RequestsActivity.resourceRequests = currentWebView.getResourceRequests();
2131 // Create an intent to launch the Requests activity.
2132 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2134 // Add the block third-party requests status to the intent.
2135 requestsIntent.putExtra("block_all_third_party_requests", currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
2138 startActivity(requestsIntent);
2141 case R.id.downloads:
2142 // Launch the system Download Manager.
2143 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2145 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2146 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2148 startActivity(downloadManagerIntent);
2152 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2153 reapplyDomainSettingsOnRestart = true;
2155 // Launch the domains activity.
2156 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2158 // Add the extra information to the intent.
2159 domainsIntent.putExtra("current_url", currentWebView.getUrl());
2161 // Get the current certificate.
2162 SslCertificate sslCertificate = currentWebView.getCertificate();
2164 // Check to see if the SSL certificate is populated.
2165 if (sslCertificate != null) {
2166 // Extract the certificate to strings.
2167 String issuedToCName = sslCertificate.getIssuedTo().getCName();
2168 String issuedToOName = sslCertificate.getIssuedTo().getOName();
2169 String issuedToUName = sslCertificate.getIssuedTo().getUName();
2170 String issuedByCName = sslCertificate.getIssuedBy().getCName();
2171 String issuedByOName = sslCertificate.getIssuedBy().getOName();
2172 String issuedByUName = sslCertificate.getIssuedBy().getUName();
2173 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
2174 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
2176 // Add the certificate to the intent.
2177 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
2178 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
2179 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
2180 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
2181 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
2182 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
2183 domainsIntent.putExtra("ssl_start_date", startDateLong);
2184 domainsIntent.putExtra("ssl_end_date", endDateLong);
2187 // Check to see if the current IP addresses have been received.
2188 if (currentWebView.hasCurrentIpAddresses()) {
2189 // Add the current IP addresses to the intent.
2190 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
2194 startActivity(domainsIntent);
2198 // Set the flag to reapply app settings on restart when returning from Settings.
2199 reapplyAppSettingsOnRestart = true;
2201 // Set the flag to reapply the domain settings on restart when returning from Settings.
2202 reapplyDomainSettingsOnRestart = true;
2204 // Launch the settings activity.
2205 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2206 startActivity(settingsIntent);
2209 case R.id.import_export:
2210 // Launch the import/export activity.
2211 Intent importExportIntent = new Intent (this, ImportExportActivity.class);
2212 startActivity(importExportIntent);
2216 // Launch the logcat activity.
2217 Intent logcatIntent = new Intent(this, LogcatActivity.class);
2218 startActivity(logcatIntent);
2222 // Launch `GuideActivity`.
2223 Intent guideIntent = new Intent(this, GuideActivity.class);
2224 startActivity(guideIntent);
2228 // Create an intent to launch the about activity.
2229 Intent aboutIntent = new Intent(this, AboutActivity.class);
2231 // Create a string array for the blocklist versions.
2232 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],
2233 ultraPrivacy.get(0).get(0)[0]};
2235 // Add the blocklist versions to the intent.
2236 aboutIntent.putExtra("blocklist_versions", blocklistVersions);
2239 startActivity(aboutIntent);
2243 // Get a handle for the drawer layout.
2244 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
2246 // Close the navigation drawer.
2247 drawerLayout.closeDrawer(GravityCompat.START);
2252 public void onPostCreate(Bundle savedInstanceState) {
2253 // Run the default commands.
2254 super.onPostCreate(savedInstanceState);
2256 // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished. This creates the navigation drawer icon.
2257 actionBarDrawerToggle.syncState();
2261 public void onConfigurationChanged(Configuration newConfig) {
2262 // Run the default commands.
2263 super.onConfigurationChanged(newConfig);
2265 // Get the status bar pixel size.
2266 int statusBarResourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
2267 int statusBarPixelSize = getResources().getDimensionPixelSize(statusBarResourceId);
2269 // Get the resource density.
2270 float screenDensity = getResources().getDisplayMetrics().density;
2272 // Recalculate the drawer header padding.
2273 drawerHeaderPaddingLeftAndRight = (int) (15 * screenDensity);
2274 drawerHeaderPaddingTop = statusBarPixelSize + (int) (4 * screenDensity);
2275 drawerHeaderPaddingBottom = (int) (8 * screenDensity);
2277 // Reload the ad for the free flavor if not in full screen mode.
2278 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2279 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2280 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
2283 // `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:
2284 // https://code.google.com/p/android/issues/detail?id=20493#c8
2285 // ActivityCompat.invalidateOptionsMenu(this);
2289 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2290 // Store the hit test result.
2291 final WebView.HitTestResult hitTestResult = currentWebView.getHitTestResult();
2293 // Create the URL strings.
2294 final String imageUrl;
2295 final String linkUrl;
2297 // Get handles for the system managers.
2298 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2299 FragmentManager fragmentManager = getSupportFragmentManager();
2300 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2302 // Remove the lint errors below that the clipboard manager might be null.
2303 assert clipboardManager != null;
2305 // Process the link according to the type.
2306 switch (hitTestResult.getType()) {
2307 // `SRC_ANCHOR_TYPE` is a link.
2308 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2309 // Get the target URL.
2310 linkUrl = hitTestResult.getExtra();
2312 // Set the target URL as the title of the `ContextMenu`.
2313 menu.setHeaderTitle(linkUrl);
2315 // Add an Open in New Tab entry.
2316 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2317 // Load the link URL in a new tab.
2322 // Add an Open with App entry.
2323 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2324 openWithApp(linkUrl);
2328 // Add an Open with Browser entry.
2329 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2330 openWithBrowser(linkUrl);
2334 // Add a Copy URL entry.
2335 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2336 // Save the link URL in a `ClipData`.
2337 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2339 // Set the `ClipData` as the clipboard's primary clip.
2340 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2344 // Add a Download URL entry.
2345 menu.add(R.string.download_url).setOnMenuItemClickListener((MenuItem item) -> {
2346 // Check if the download should be processed by an external app.
2347 if (sharedPreferences.getBoolean("download_with_external_app", false)) { // Download with an external app.
2348 openUrlWithExternalApp(linkUrl);
2349 } else { // Download with Android's download manager.
2350 // Check to see if the storage permission has already been granted.
2351 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission needs to be requested.
2352 // Store the variables for future use by `onRequestPermissionsResult()`.
2353 downloadUrl = linkUrl;
2354 downloadContentDisposition = "none";
2355 downloadContentLength = -1;
2357 // Show a dialog if the user has previously denied the permission.
2358 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2359 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
2360 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
2362 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
2363 downloadLocationPermissionDialogFragment.show(fragmentManager, getString(R.string.download_location));
2364 } else { // Show the permission request directly.
2365 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
2366 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2368 } else { // The storage permission has already been granted.
2369 // Get a handle for the download file alert dialog.
2370 DialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(linkUrl, "none", -1);
2372 // Show the download file alert dialog.
2373 downloadFileDialogFragment.show(fragmentManager, getString(R.string.download));
2379 // Add a Cancel entry, which by default closes the context menu.
2380 menu.add(R.string.cancel);
2383 case WebView.HitTestResult.EMAIL_TYPE:
2384 // Get the target URL.
2385 linkUrl = hitTestResult.getExtra();
2387 // Set the target URL as the title of the `ContextMenu`.
2388 menu.setHeaderTitle(linkUrl);
2390 // Add a Write Email entry.
2391 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2392 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2393 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2395 // Parse the url and set it as the data for the `Intent`.
2396 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2398 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2399 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2402 startActivity(emailIntent);
2406 // Add a Copy Email Address entry.
2407 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2408 // Save the email address in a `ClipData`.
2409 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2411 // Set the `ClipData` as the clipboard's primary clip.
2412 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2416 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2417 menu.add(R.string.cancel);
2420 // `IMAGE_TYPE` is an image. `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link. Privacy Browser processes them the same.
2421 case WebView.HitTestResult.IMAGE_TYPE:
2422 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2423 // Get the image URL.
2424 imageUrl = hitTestResult.getExtra();
2426 // Set the image URL as the title of the context menu.
2427 menu.setHeaderTitle(imageUrl);
2429 // Add an Open in New Tab entry.
2430 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2431 // Load the image URL in a new tab.
2432 addNewTab(imageUrl);
2436 // Add a View Image entry.
2437 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2442 // Add a `Download Image` entry.
2443 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2444 // Check if the download should be processed by an external app.
2445 if (sharedPreferences.getBoolean("download_with_external_app", false)) { // Download with an external app.
2446 openUrlWithExternalApp(imageUrl);
2447 } else { // Download with Android's download manager.
2448 // Check to see if the storage permission has already been granted.
2449 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission needs to be requested.
2450 // Store the image URL for use by `onRequestPermissionResult()`.
2451 downloadImageUrl = imageUrl;
2453 // Show a dialog if the user has previously denied the permission.
2454 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2455 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2456 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2458 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
2459 downloadLocationPermissionDialogFragment.show(fragmentManager, getString(R.string.download_location));
2460 } else { // Show the permission request directly.
2461 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
2462 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2464 } else { // The storage permission has already been granted.
2465 // Get a handle for the download image alert dialog.
2466 DialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2468 // Show the download image alert dialog.
2469 downloadImageDialogFragment.show(fragmentManager, getString(R.string.download));
2475 // Add a `Copy URL` entry.
2476 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2477 // Save the image URL in a `ClipData`.
2478 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2480 // Set the `ClipData` as the clipboard's primary clip.
2481 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2485 // Add an Open with App entry.
2486 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2487 openWithApp(imageUrl);
2491 // Add an Open with Browser entry.
2492 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2493 openWithBrowser(imageUrl);
2497 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2498 menu.add(R.string.cancel);
2504 public void onCreateBookmark(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2505 // Get a handle for the bookmarks list view.
2506 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2508 // Get the views from the dialog fragment.
2509 EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
2510 EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
2512 // Extract the strings from the edit texts.
2513 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2514 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2516 // Create a favorite icon byte array output stream.
2517 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2519 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2520 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2522 // Convert the favorite icon byte array stream to a byte array.
2523 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2525 // Display the new bookmark below the current items in the (0 indexed) list.
2526 int newBookmarkDisplayOrder = bookmarksListView.getCount();
2528 // Create the bookmark.
2529 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2531 // Update the bookmarks cursor with the current contents of this folder.
2532 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2534 // Update the list view.
2535 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2537 // Scroll to the new bookmark.
2538 bookmarksListView.setSelection(newBookmarkDisplayOrder);
2542 public void onCreateBookmarkFolder(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2543 // Get a handle for the bookmarks list view.
2544 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2546 // Get handles for the views in the dialog fragment.
2547 EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
2548 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
2549 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
2551 // Get new folder name string.
2552 String folderNameString = createFolderNameEditText.getText().toString();
2554 // Create a folder icon bitmap.
2555 Bitmap folderIconBitmap;
2557 // Set the folder icon bitmap according to the dialog.
2558 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
2559 // Get the default folder icon drawable.
2560 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2562 // Convert the folder icon drawable to a bitmap drawable.
2563 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2565 // Convert the folder icon bitmap drawable to a bitmap.
2566 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2567 } else { // Use the WebView favorite icon.
2568 // Copy the favorite icon bitmap to the folder icon bitmap.
2569 folderIconBitmap = favoriteIconBitmap;
2572 // Create a folder icon byte array output stream.
2573 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2575 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2576 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2578 // Convert the folder icon byte array stream to a byte array.
2579 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2581 // Move all the bookmarks down one in the display order.
2582 for (int i = 0; i < bookmarksListView.getCount(); i++) {
2583 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2584 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2587 // Create the folder, which will be placed at the top of the `ListView`.
2588 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2590 // Update the bookmarks cursor with the current contents of this folder.
2591 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2593 // Update the `ListView`.
2594 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2596 // Scroll to the new folder.
2597 bookmarksListView.setSelection(0);
2601 public void onSaveBookmark(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, Bitmap favoriteIconBitmap) {
2602 // Get handles for the views from `dialogFragment`.
2603 EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
2604 EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
2605 RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
2607 // Store the bookmark strings.
2608 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
2609 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
2611 // Update the bookmark.
2612 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
2613 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
2614 } else { // Update the bookmark using the `WebView` favorite icon.
2615 // Create a favorite icon byte array output stream.
2616 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2618 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2619 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
2621 // Convert the favorite icon byte array stream to a byte array.
2622 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
2624 // Update the bookmark and the favorite icon.
2625 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
2628 // Update the bookmarks cursor with the current contents of this folder.
2629 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2631 // Update the list view.
2632 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2636 public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId, Bitmap favoriteIconBitmap) {
2637 // Get handles for the views from `dialogFragment`.
2638 EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
2639 RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
2640 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
2641 ImageView defaultFolderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
2643 // Get the new folder name.
2644 String newFolderNameString = editFolderNameEditText.getText().toString();
2646 // Check if the favorite icon has changed.
2647 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
2648 // Update the name in the database.
2649 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2650 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
2651 // Create the new folder icon Bitmap.
2652 Bitmap folderIconBitmap;
2654 // Populate the new folder icon bitmap.
2655 if (defaultFolderIconRadioButton.isChecked()) {
2656 // Get the default folder icon drawable.
2657 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2659 // Convert the folder icon drawable to a bitmap drawable.
2660 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2662 // Convert the folder icon bitmap drawable to a bitmap.
2663 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2664 } else { // Use the `WebView` favorite icon.
2665 // Copy the favorite icon bitmap to the folder icon bitmap.
2666 folderIconBitmap = favoriteIconBitmap;
2669 // Create a folder icon byte array output stream.
2670 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2672 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2673 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2675 // Convert the folder icon byte array stream to a byte array.
2676 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2678 // Update the folder icon in the database.
2679 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, newFolderIconByteArray);
2680 } else { // The folder icon and the name have changed.
2681 // Get the new folder icon `Bitmap`.
2682 Bitmap folderIconBitmap;
2683 if (defaultFolderIconRadioButton.isChecked()) {
2684 // Get the default folder icon drawable.
2685 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2687 // Convert the folder icon drawable to a bitmap drawable.
2688 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2690 // Convert the folder icon bitmap drawable to a bitmap.
2691 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2692 } else { // Use the `WebView` favorite icon.
2693 // Copy the favorite icon bitmap to the folder icon bitmap.
2694 folderIconBitmap = favoriteIconBitmap;
2697 // Create a folder icon byte array output stream.
2698 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2700 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2701 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2703 // Convert the folder icon byte array stream to a byte array.
2704 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2706 // Update the folder name and icon in the database.
2707 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, newFolderIconByteArray);
2710 // Update the bookmarks cursor with the current contents of this folder.
2711 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2713 // Update the `ListView`.
2714 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2718 public void onCloseDownloadLocationPermissionDialog(int downloadType) {
2719 switch (downloadType) {
2720 case DownloadLocationPermissionDialog.DOWNLOAD_FILE:
2721 // Request the WRITE_EXTERNAL_STORAGE permission with a file request code.
2722 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2725 case DownloadLocationPermissionDialog.DOWNLOAD_IMAGE:
2726 // Request the WRITE_EXTERNAL_STORAGE permission with an image request code.
2727 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2733 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
2734 // Get a handle for the fragment manager.
2735 FragmentManager fragmentManager = getSupportFragmentManager();
2737 switch (requestCode) {
2738 case DOWNLOAD_FILE_REQUEST_CODE:
2739 // Show the download file alert dialog. When the dialog closes, the correct command will be used based on the permission status.
2740 DialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(downloadUrl, downloadContentDisposition, downloadContentLength);
2742 // On API 23, displaying the fragment must be delayed or the app will crash.
2743 if (Build.VERSION.SDK_INT == 23) {
2744 new Handler().postDelayed(() -> downloadFileDialogFragment.show(fragmentManager, getString(R.string.download)), 500);
2746 downloadFileDialogFragment.show(fragmentManager, getString(R.string.download));
2749 // Reset the download variables.
2751 downloadContentDisposition = "";
2752 downloadContentLength = 0;
2755 case DOWNLOAD_IMAGE_REQUEST_CODE:
2756 // Show the download image alert dialog. When the dialog closes, the correct command will be used based on the permission status.
2757 DialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(downloadImageUrl);
2759 // On API 23, displaying the fragment must be delayed or the app will crash.
2760 if (Build.VERSION.SDK_INT == 23) {
2761 new Handler().postDelayed(() -> downloadImageDialogFragment.show(fragmentManager, getString(R.string.download)), 500);
2763 downloadImageDialogFragment.show(fragmentManager, getString(R.string.download));
2766 // Reset the image URL variable.
2767 downloadImageUrl = "";
2773 public void onDownloadImage(DialogFragment dialogFragment, String imageUrl) {
2774 // Download the image if it has an HTTP or HTTPS URI.
2775 if (imageUrl.startsWith("http")) {
2776 // Get a handle for the system `DOWNLOAD_SERVICE`.
2777 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2779 // Parse `imageUrl`.
2780 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
2782 // Get a handle for the cookie manager.
2783 CookieManager cookieManager = CookieManager.getInstance();
2785 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
2786 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2787 if (cookieManager.acceptCookie()) {
2788 // Get the cookies for `imageUrl`.
2789 String cookies = cookieManager.getCookie(imageUrl);
2791 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2792 downloadRequest.addRequestHeader("Cookie", cookies);
2795 // Get the file name from the dialog fragment.
2796 EditText downloadImageNameEditText = dialogFragment.getDialog().findViewById(R.id.download_image_name);
2797 String imageName = downloadImageNameEditText.getText().toString();
2799 // Specify the download location.
2800 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
2801 // Download to the public download directory.
2802 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, imageName);
2803 } else { // External write permission denied.
2804 // Download to the app's external download directory.
2805 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, imageName);
2808 // Allow `MediaScanner` to index the download if it is a media file.
2809 downloadRequest.allowScanningByMediaScanner();
2811 // Add the URL as the description for the download.
2812 downloadRequest.setDescription(imageUrl);
2814 // Show the download notification after the download is completed.
2815 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2817 // Remove the lint warning below that `downloadManager` might be `null`.
2818 assert downloadManager != null;
2820 // Initiate the download.
2821 downloadManager.enqueue(downloadRequest);
2822 } else { // The image is not an HTTP or HTTPS URI.
2823 Snackbar.make(currentWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
2828 public void onDownloadFile(DialogFragment dialogFragment, String downloadUrl) {
2829 // Download the file if it has an HTTP or HTTPS URI.
2830 if (downloadUrl.startsWith("http")) {
2831 // Get a handle for the system `DOWNLOAD_SERVICE`.
2832 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2834 // Parse `downloadUrl`.
2835 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
2837 // Get a handle for the cookie manager.
2838 CookieManager cookieManager = CookieManager.getInstance();
2840 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
2841 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2842 if (cookieManager.acceptCookie()) {
2843 // Get the cookies for `downloadUrl`.
2844 String cookies = cookieManager.getCookie(downloadUrl);
2846 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2847 downloadRequest.addRequestHeader("Cookie", cookies);
2850 // Get the file name from the dialog fragment.
2851 EditText downloadFileNameEditText = dialogFragment.getDialog().findViewById(R.id.download_file_name);
2852 String fileName = downloadFileNameEditText.getText().toString();
2854 // Specify the download location.
2855 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
2856 // Download to the public download directory.
2857 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
2858 } else { // External write permission denied.
2859 // Download to the app's external download directory.
2860 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, fileName);
2863 // Allow `MediaScanner` to index the download if it is a media file.
2864 downloadRequest.allowScanningByMediaScanner();
2866 // Add the URL as the description for the download.
2867 downloadRequest.setDescription(downloadUrl);
2869 // Show the download notification after the download is completed.
2870 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2872 // Remove the lint warning below that `downloadManager` might be `null`.
2873 assert downloadManager != null;
2875 // Initiate the download.
2876 downloadManager.enqueue(downloadRequest);
2877 } else { // The download is not an HTTP or HTTPS URI.
2878 Snackbar.make(currentWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
2882 // Override `onBackPressed` to handle the navigation drawer and and the WebView.
2884 public void onBackPressed() {
2885 // Get a handle for the drawer layout and the tab layout.
2886 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
2887 TabLayout tabLayout = findViewById(R.id.tablayout);
2889 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
2890 // Close the navigation drawer.
2891 drawerLayout.closeDrawer(GravityCompat.START);
2892 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
2893 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
2894 // close the bookmarks drawer.
2895 drawerLayout.closeDrawer(GravityCompat.END);
2896 } else { // A subfolder is displayed.
2897 // Place the former parent folder in `currentFolder`.
2898 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolderName(currentBookmarksFolder);
2900 // Load the new folder.
2901 loadBookmarksFolder();
2903 } else if (currentWebView.canGoBack()) { // There is at least one item in the current WebView history.
2904 // Reset the current domain name so that navigation works if third-party requests are blocked.
2905 currentWebView.resetCurrentDomainName();
2907 // Set navigating history so that the domain settings are applied when the new URL is loaded.
2908 currentWebView.setNavigatingHistory(true);
2911 currentWebView.goBack();
2912 } else if (tabLayout.getTabCount() > 1) { // There are at least two tabs.
2913 // Close the current tab.
2915 } else { // There isn't anything to do in Privacy Browser.
2916 // Run the default commands.
2917 super.onBackPressed();
2919 // Manually kill Privacy Browser. Otherwise, it is glitchy when restarted.
2924 // Process the results of an upload file chooser. Currently there is only one `startActivityForResult` in this activity, so the request code, used to differentiate them, is ignored.
2926 public void onActivityResult(int requestCode, int resultCode, Intent data) {
2927 // File uploads only work on API >= 21.
2928 if (Build.VERSION.SDK_INT >= 21) {
2929 // Pass the file to the WebView.
2930 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
2934 private void loadUrlFromTextBox() {
2935 // Get a handle for the URL edit text.
2936 EditText urlEditText = findViewById(R.id.url_edittext);
2938 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
2939 String unformattedUrlString = urlEditText.getText().toString().trim();
2941 // Initialize the formatted URL string.
2944 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
2945 if (unformattedUrlString.startsWith("content://")) { // This is a Content URL.
2946 // Load the entire content URL.
2947 url = unformattedUrlString;
2948 } else if (Patterns.WEB_URL.matcher(unformattedUrlString).matches() || unformattedUrlString.startsWith("http://") || unformattedUrlString.startsWith("https://") ||
2949 unformattedUrlString.startsWith("file://")) { // This is a standard URL.
2950 // Add `https://` at the beginning if there is no protocol. Otherwise the app will segfault.
2951 if (!unformattedUrlString.startsWith("http") && !unformattedUrlString.startsWith("file://") && !unformattedUrlString.startsWith("content://")) {
2952 unformattedUrlString = "https://" + unformattedUrlString;
2955 // Initialize `unformattedUrl`.
2956 URL unformattedUrl = null;
2958 // 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.
2960 unformattedUrl = new URL(unformattedUrlString);
2961 } catch (MalformedURLException e) {
2962 e.printStackTrace();
2965 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2966 String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2967 String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2968 String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2969 String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2970 String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2973 Uri.Builder uri = new Uri.Builder();
2974 uri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2976 // Decode the URI as a UTF-8 string in.
2978 url = URLDecoder.decode(uri.build().toString(), "UTF-8");
2979 } catch (UnsupportedEncodingException exception) {
2980 // Do nothing. The formatted URL string will remain blank.
2982 } else if (!unformattedUrlString.isEmpty()){ // This is not a URL, but rather a search string.
2983 // Create an encoded URL String.
2984 String encodedUrlString;
2986 // Sanitize the search input.
2988 encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2989 } catch (UnsupportedEncodingException exception) {
2990 encodedUrlString = "";
2993 // Add the base search URL.
2994 url = searchURL + encodedUrlString;
2997 // 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.
2998 urlEditText.clearFocus();
3004 private void loadUrl(String url) {
3005 // Sanitize the URL.
3006 url = sanitizeUrl(url);
3008 // Apply the domain settings.
3009 applyDomainSettings(currentWebView, url, true, false);
3012 currentWebView.loadUrl(url, customHeaders);
3015 public void findPreviousOnPage(View view) {
3016 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
3017 currentWebView.findNext(false);
3020 public void findNextOnPage(View view) {
3021 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
3022 currentWebView.findNext(true);
3025 public void closeFindOnPage(View view) {
3026 // Get a handle for the views.
3027 Toolbar toolbar = findViewById(R.id.toolbar);
3028 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
3029 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
3031 // Delete the contents of `find_on_page_edittext`.
3032 findOnPageEditText.setText(null);
3034 // Clear the highlighted phrases if the WebView is not null.
3035 if (currentWebView != null) {
3036 currentWebView.clearMatches();
3039 // Hide the find on page linear layout.
3040 findOnPageLinearLayout.setVisibility(View.GONE);
3042 // Show the toolbar.
3043 toolbar.setVisibility(View.VISIBLE);
3045 // Get a handle for the input method manager.
3046 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
3048 // Remove the lint warning below that the input method manager might be null.
3049 assert inputMethodManager != null;
3051 // Hide the keyboard.
3052 inputMethodManager.hideSoftInputFromWindow(toolbar.getWindowToken(), 0);
3055 private void applyAppSettings() {
3056 // Get a handle for the shared preferences.
3057 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3059 // Store the values from the shared preferences in variables.
3060 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3061 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
3062 sanitizeGoogleAnalytics = sharedPreferences.getBoolean("google_analytics", true);
3063 sanitizeFacebookClickIds = sharedPreferences.getBoolean("facebook_click_ids", true);
3064 sanitizeTwitterAmpRedirects = sharedPreferences.getBoolean("twitter_amp_redirects", true);
3065 proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
3066 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3067 hideAppBar = sharedPreferences.getBoolean("hide_app_bar", true);
3068 scrollAppBar = sharedPreferences.getBoolean("scroll_app_bar", true);
3070 // Get handles for the views that need to be modified.
3071 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
3072 AppBarLayout appBarLayout = findViewById(R.id.appbar_layout);
3073 ActionBar actionBar = getSupportActionBar();
3074 Toolbar toolbar = findViewById(R.id.toolbar);
3075 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
3076 LinearLayout tabsLinearLayout = findViewById(R.id.tabs_linearlayout);
3077 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
3079 // Remove the incorrect lint warning below that the action bar might be null.
3080 assert actionBar != null;
3082 // Apply the proxy through Orbot settings.
3083 applyProxyThroughOrbot(false);
3085 // Set Do Not Track status.
3086 if (doNotTrackEnabled) {
3087 customHeaders.put("DNT", "1");
3089 customHeaders.remove("DNT");
3092 // Get the current layout parameters. Using coordinator layout parameters allows the `setBehavior()` command and using app bar layout parameters allows the `setScrollFlags()` command.
3093 CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
3094 AppBarLayout.LayoutParams toolbarLayoutParams = (AppBarLayout.LayoutParams) toolbar.getLayoutParams();
3095 AppBarLayout.LayoutParams findOnPageLayoutParams = (AppBarLayout.LayoutParams) findOnPageLinearLayout.getLayoutParams();
3096 AppBarLayout.LayoutParams tabsLayoutParams = (AppBarLayout.LayoutParams) tabsLinearLayout.getLayoutParams();
3098 // Add the scrolling behavior to the layout parameters.
3100 // Enable scrolling of the app bar.
3101 swipeRefreshLayoutParams.setBehavior(new AppBarLayout.ScrollingViewBehavior());
3102 toolbarLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3103 findOnPageLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3104 tabsLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3106 // Disable scrolling of the app bar.
3107 swipeRefreshLayoutParams.setBehavior(null);
3108 toolbarLayoutParams.setScrollFlags(0);
3109 findOnPageLayoutParams.setScrollFlags(0);
3110 tabsLayoutParams.setScrollFlags(0);
3112 // Expand the app bar if it is currently collapsed.
3113 appBarLayout.setExpanded(true);
3116 // Apply the modified layout parameters.
3117 swipeRefreshLayout.setLayoutParams(swipeRefreshLayoutParams);
3118 toolbar.setLayoutParams(toolbarLayoutParams);
3119 findOnPageLinearLayout.setLayoutParams(findOnPageLayoutParams);
3120 tabsLinearLayout.setLayoutParams(tabsLayoutParams);
3122 // Set the app bar scrolling for each WebView.
3123 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3124 // Get the WebView tab fragment.
3125 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3127 // Get the fragment view.
3128 View fragmentView = webViewTabFragment.getView();
3130 // Only modify the WebViews if they exist.
3131 if (fragmentView != null) {
3132 // Get the nested scroll WebView from the tab fragment.
3133 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3135 // Set the app bar scrolling.
3136 nestedScrollWebView.setNestedScrollingEnabled(scrollAppBar);
3140 // Update the full screen browsing mode settings.
3141 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
3142 // Update the visibility of the app bar, which might have changed in the settings.
3144 // Hide the tab linear layout.
3145 tabsLinearLayout.setVisibility(View.GONE);
3147 // Hide the action bar.
3150 // Show the tab linear layout.
3151 tabsLinearLayout.setVisibility(View.VISIBLE);
3153 // Show the action bar.
3157 // Hide the banner ad in the free flavor.
3158 if (BuildConfig.FLAVOR.contentEquals("free")) {
3159 AdHelper.hideAd(findViewById(R.id.adview));
3162 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
3163 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3165 /* Hide the system bars.
3166 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3167 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
3168 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3169 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3171 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
3172 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3173 } else { // Privacy Browser is not in full screen browsing mode.
3174 // 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.
3175 inFullScreenBrowsingMode = false;
3177 // Show the tab linear layout.
3178 tabsLinearLayout.setVisibility(View.VISIBLE);
3180 // Show the action bar.
3183 // Show the banner ad in the free flavor.
3184 if (BuildConfig.FLAVOR.contentEquals("free")) {
3185 // Initialize the ads. If this isn't the first run, `loadAd()` will be automatically called instead.
3186 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getSupportFragmentManager(), getString(R.string.google_app_id), getString(R.string.ad_unit_id));
3189 // Remove the `SYSTEM_UI` flags from the root frame layout.
3190 rootFrameLayout.setSystemUiVisibility(0);
3192 // Add the translucent status flag.
3193 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3198 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
3199 @SuppressLint("SetJavaScriptEnabled")
3200 private boolean applyDomainSettings(NestedScrollWebView nestedScrollWebView, String url, boolean resetTab, boolean reloadWebsite) {
3201 // Store a copy of the current user agent to track changes for the return boolean.
3202 String initialUserAgent = nestedScrollWebView.getSettings().getUserAgentString();
3204 // Parse the URL into a URI.
3205 Uri uri = Uri.parse(url);
3207 // Extract the domain from `uri`.
3208 String newHostName = uri.getHost();
3210 // Strings don't like to be null.
3211 if (newHostName == null) {
3215 // 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.
3216 if (!nestedScrollWebView.getCurrentDomainName().equals(newHostName) || newHostName.equals("")) {
3217 // Set the new host name as the current domain name.
3218 nestedScrollWebView.setCurrentDomainName(newHostName);
3220 // Reset the ignoring of pinned domain information.
3221 nestedScrollWebView.setIgnorePinnedDomainInformation(false);
3223 // Clear any pinned SSL certificate or IP addresses.
3224 nestedScrollWebView.clearPinnedSslCertificate();
3225 nestedScrollWebView.clearPinnedIpAddresses();
3227 // Reset the favorite icon if specified.
3229 // Initialize the favorite icon.
3230 nestedScrollWebView.initializeFavoriteIcon();
3232 // Get the current page position.
3233 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
3235 // Get a handle for the tab layout.
3236 TabLayout tabLayout = findViewById(R.id.tablayout);
3238 // Get the corresponding tab.
3239 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
3241 // Update the tab if it isn't null, which sometimes happens when restarting from the background.
3243 // Get the tab custom view.
3244 View tabCustomView = tab.getCustomView();
3246 // Remove the warning below that the tab custom view might be null.
3247 assert tabCustomView != null;
3249 // Get the tab views.
3250 ImageView tabFavoriteIconImageView = tabCustomView.findViewById(R.id.favorite_icon_imageview);
3251 TextView tabTitleTextView = tabCustomView.findViewById(R.id.title_textview);
3253 // Set the default favorite icon as the favorite icon for this tab.
3254 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(nestedScrollWebView.getFavoriteOrDefaultIcon(), 64, 64, true));
3256 // Set the loading title text.
3257 tabTitleTextView.setText(R.string.loading);
3261 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3262 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3264 // Get a full cursor from `domainsDatabaseHelper`.
3265 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3267 // Initialize `domainSettingsSet`.
3268 Set<String> domainSettingsSet = new HashSet<>();
3270 // Get the domain name column index.
3271 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3273 // Populate `domainSettingsSet`.
3274 for (int i = 0; i < domainNameCursor.getCount(); i++) {
3275 // Move `domainsCursor` to the current row.
3276 domainNameCursor.moveToPosition(i);
3278 // Store the domain name in `domainSettingsSet`.
3279 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3282 // Close `domainNameCursor.
3283 domainNameCursor.close();
3285 // Initialize the domain name in database variable.
3286 String domainNameInDatabase = null;
3288 // Check the hostname against the domain settings set.
3289 if (domainSettingsSet.contains(newHostName)) { // The hostname is contained in the domain settings set.
3290 // Record the domain name in the database.
3291 domainNameInDatabase = newHostName;
3293 // Set the domain settings applied tracker to true.
3294 nestedScrollWebView.setDomainSettingsApplied(true);
3295 } else { // The hostname is not contained in the domain settings set.
3296 // Set the domain settings applied tracker to false.
3297 nestedScrollWebView.setDomainSettingsApplied(false);
3300 // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3301 while (!nestedScrollWebView.getDomainSettingsApplied() && newHostName.contains(".")) { // Stop checking if domain settings are already applied or there are no more `.` in the host name.
3302 if (domainSettingsSet.contains("*." + newHostName)) { // Check the host name prepended by `*.`.
3303 // Set the domain settings applied tracker to true.
3304 nestedScrollWebView.setDomainSettingsApplied(true);
3306 // Store the applied domain names as it appears in the database.
3307 domainNameInDatabase = "*." + newHostName;
3310 // Strip out the lowest subdomain of of the host name.
3311 newHostName = newHostName.substring(newHostName.indexOf(".") + 1);
3315 // Get a handle for the shared preferences.
3316 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3318 // Store the general preference information.
3319 String defaultFontSizeString = sharedPreferences.getString("font_size", getString(R.string.font_size_default_value));
3320 String defaultUserAgentName = sharedPreferences.getString("user_agent", getString(R.string.user_agent_default_value));
3321 boolean defaultSwipeToRefresh = sharedPreferences.getBoolean("swipe_to_refresh", true);
3322 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
3323 boolean wideViewport = sharedPreferences.getBoolean("wide_viewport", true);
3324 boolean displayWebpageImages = sharedPreferences.getBoolean("display_webpage_images", true);
3326 // Get a handle for the cookie manager.
3327 CookieManager cookieManager = CookieManager.getInstance();
3329 // Get handles for the views.
3330 RelativeLayout urlRelativeLayout = findViewById(R.id.url_relativelayout);
3331 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
3333 // Initialize the user agent array adapter and string array.
3334 ArrayAdapter<CharSequence> userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item);
3335 String[] userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
3337 if (nestedScrollWebView.getDomainSettingsApplied()) { // The url has custom domain settings.
3338 // Get a cursor for the current host and move it to the first position.
3339 Cursor currentDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3340 currentDomainSettingsCursor.moveToFirst();
3342 // Get the settings from the cursor.
3343 nestedScrollWebView.setDomainSettingsDatabaseId(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3344 nestedScrollWebView.setDomainSettingsJavaScriptEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3345 nestedScrollWebView.setAcceptFirstPartyCookies(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3346 boolean domainThirdPartyCookiesEnabled = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3347 nestedScrollWebView.getSettings().setDomStorageEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3348 // Form data can be removed once the minimum API >= 26.
3349 boolean saveFormData = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3350 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASY_LIST,
3351 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3352 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASY_PRIVACY,
3353 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3354 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST,
3355 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3356 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST,
3357 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3358 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRA_PRIVACY,
3359 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_ULTRAPRIVACY)) == 1);
3360 nestedScrollWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS,
3361 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
3362 String userAgentName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3363 int fontSize = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3364 int swipeToRefreshInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
3365 int nightModeInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
3366 int wideViewportInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.WIDE_VIEWPORT));
3367 int displayWebpageImagesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3368 boolean pinnedSslCertificate = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3369 String pinnedSslIssuedToCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3370 String pinnedSslIssuedToOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3371 String pinnedSslIssuedToUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3372 String pinnedSslIssuedByCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3373 String pinnedSslIssuedByOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3374 String pinnedSslIssuedByUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3375 boolean pinnedIpAddresses = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_IP_ADDRESSES)) == 1);
3376 String pinnedHostIpAddresses = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.IP_ADDRESSES));
3378 // Create the pinned SSL date variables.
3379 Date pinnedSslStartDate;
3380 Date pinnedSslEndDate;
3382 // 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.
3383 if (currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
3384 pinnedSslStartDate = null;
3386 pinnedSslStartDate = new Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
3389 // 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.
3390 if (currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
3391 pinnedSslEndDate = null;
3393 pinnedSslEndDate = new Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
3396 // If there is a pinned SSL certificate, store it in the WebView.
3397 if (pinnedSslCertificate) {
3398 nestedScrollWebView.setPinnedSslCertificate(pinnedSslIssuedToCName, pinnedSslIssuedToOName, pinnedSslIssuedToUName, pinnedSslIssuedByCName, pinnedSslIssuedByOName, pinnedSslIssuedByUName,
3399 pinnedSslStartDate, pinnedSslEndDate);
3402 // If there is a pinned IP address, store it in the WebView.
3403 if (pinnedIpAddresses) {
3404 nestedScrollWebView.setPinnedIpAddresses(pinnedHostIpAddresses);
3407 // Set night mode according to the night mode int.
3408 switch (nightModeInt) {
3409 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
3410 // Set night mode according to the current default.
3411 nestedScrollWebView.setNightMode(sharedPreferences.getBoolean("night_mode", false));
3414 case DomainsDatabaseHelper.ENABLED:
3415 // Enable night mode.
3416 nestedScrollWebView.setNightMode(true);
3419 case DomainsDatabaseHelper.DISABLED:
3420 // Disable night mode.
3421 nestedScrollWebView.setNightMode(false);
3425 // Enable JavaScript if night mode is enabled.
3426 if (nestedScrollWebView.getNightMode()) {
3427 // Enable JavaScript.
3428 nestedScrollWebView.getSettings().setJavaScriptEnabled(true);
3430 // Set JavaScript according to the domain settings.
3431 nestedScrollWebView.getSettings().setJavaScriptEnabled(nestedScrollWebView.getDomainSettingsJavaScriptEnabled());
3434 // Close the current host domain settings cursor.
3435 currentDomainSettingsCursor.close();
3437 // Apply the domain settings.
3438 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptFirstPartyCookies());
3440 // Set third-party cookies status if API >= 21.
3441 if (Build.VERSION.SDK_INT >= 21) {
3442 cookieManager.setAcceptThirdPartyCookies(nestedScrollWebView, domainThirdPartyCookiesEnabled);
3445 // Apply the form data setting if the API < 26.
3446 if (Build.VERSION.SDK_INT < 26) {
3447 nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
3450 // Apply the font size.
3451 if (fontSize == 0) { // Apply the default font size.
3452 nestedScrollWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3453 } else { // Apply the specified font size.
3454 nestedScrollWebView.getSettings().setTextZoom(fontSize);
3457 // Set the user agent.
3458 if (userAgentName.equals(getString(R.string.system_default_user_agent))) { // Use the system default user agent.
3459 // Get the array position of the default user agent name.
3460 int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3462 // Set the user agent according to the system default.
3463 switch (defaultUserAgentArrayPosition) {
3464 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
3465 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3466 nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
3469 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3470 // Set the user agent to `""`, which uses the default value.
3471 nestedScrollWebView.getSettings().setUserAgentString("");
3474 case SETTINGS_CUSTOM_USER_AGENT:
3475 // Set the default custom user agent.
3476 nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
3480 // Get the user agent string from the user agent data array
3481 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
3483 } else { // Set the user agent according to the stored name.
3484 // Get the array position of the user agent name.
3485 int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
3487 switch (userAgentArrayPosition) {
3488 case UNRECOGNIZED_USER_AGENT: // The user agent name contains a custom user agent.
3489 nestedScrollWebView.getSettings().setUserAgentString(userAgentName);
3492 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3493 // Set the user agent to `""`, which uses the default value.
3494 nestedScrollWebView.getSettings().setUserAgentString("");
3498 // Get the user agent string from the user agent data array.
3499 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3503 // Set swipe to refresh.
3504 switch (swipeToRefreshInt) {
3505 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
3506 // Store the swipe to refresh status in the nested scroll WebView.
3507 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
3509 // 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.
3510 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
3513 case DomainsDatabaseHelper.ENABLED:
3514 // Store the swipe to refresh status in the nested scroll WebView.
3515 nestedScrollWebView.setSwipeToRefresh(true);
3517 // Enable swipe to refresh. This can be removed once the minimum API >= 23 because it is continuously set by an on scroll change listener.
3518 swipeRefreshLayout.setEnabled(true);
3521 case DomainsDatabaseHelper.DISABLED:
3522 // Store the swipe to refresh status in the nested scroll WebView.
3523 nestedScrollWebView.setSwipeToRefresh(false);
3525 // Disable swipe to refresh. This can be removed once the minimum API >= 23 because it is continuously set by an on scroll change listener.
3526 swipeRefreshLayout.setEnabled(false);
3529 // Set the viewport.
3530 switch (wideViewportInt) {
3531 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
3532 nestedScrollWebView.getSettings().setUseWideViewPort(wideViewport);
3535 case DomainsDatabaseHelper.ENABLED:
3536 nestedScrollWebView.getSettings().setUseWideViewPort(true);
3539 case DomainsDatabaseHelper.DISABLED:
3540 nestedScrollWebView.getSettings().setUseWideViewPort(false);
3544 // Set the loading of webpage images.
3545 switch (displayWebpageImagesInt) {
3546 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
3547 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
3550 case DomainsDatabaseHelper.ENABLED:
3551 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(true);
3554 case DomainsDatabaseHelper.DISABLED:
3555 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(false);
3559 // 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.
3561 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
3563 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
3565 } else { // The new URL does not have custom domain settings. Load the defaults.
3566 // Store the values from the shared preferences.
3567 boolean defaultJavaScriptEnabled = sharedPreferences.getBoolean("javascript", false);
3568 nestedScrollWebView.setAcceptFirstPartyCookies(sharedPreferences.getBoolean("first_party_cookies", false));
3569 boolean defaultThirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies", false);
3570 nestedScrollWebView.getSettings().setDomStorageEnabled(sharedPreferences.getBoolean("dom_storage", false));
3571 boolean saveFormData = sharedPreferences.getBoolean("save_form_data", false); // Form data can be removed once the minimum API >= 26.
3572 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASY_LIST, sharedPreferences.getBoolean("easylist", true));
3573 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASY_PRIVACY, sharedPreferences.getBoolean("easyprivacy", true));
3574 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, sharedPreferences.getBoolean("fanboys_annoyance_list", true));
3575 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, sharedPreferences.getBoolean("fanboys_social_blocking_list", true));
3576 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRA_PRIVACY, sharedPreferences.getBoolean("ultraprivacy", true));
3577 nestedScrollWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, sharedPreferences.getBoolean("block_all_third_party_requests", false));
3578 nestedScrollWebView.setNightMode(sharedPreferences.getBoolean("night_mode", false));
3580 // Enable JavaScript if night mode is enabled.
3581 if (nestedScrollWebView.getNightMode()) {
3582 // Enable JavaScript.
3583 nestedScrollWebView.getSettings().setJavaScriptEnabled(true);
3585 // Set JavaScript according to the domain settings.
3586 nestedScrollWebView.getSettings().setJavaScriptEnabled(defaultJavaScriptEnabled);
3589 // Apply the default settings.
3590 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptFirstPartyCookies());
3591 nestedScrollWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3593 // Apply the form data setting if the API < 26.
3594 if (Build.VERSION.SDK_INT < 26) {
3595 nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
3598 // Store the swipe to refresh status in the nested scroll WebView.
3599 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
3601 // Apply swipe to refresh according to the default.
3602 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
3604 // Reset the pinned variables.
3605 nestedScrollWebView.setDomainSettingsDatabaseId(-1);
3607 // Set third-party cookies status if API >= 21.
3608 if (Build.VERSION.SDK_INT >= 21) {
3609 cookieManager.setAcceptThirdPartyCookies(nestedScrollWebView, defaultThirdPartyCookiesEnabled);
3612 // Get the array position of the user agent name.
3613 int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3615 // Set the user agent.
3616 switch (userAgentArrayPosition) {
3617 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
3618 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3619 nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
3622 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3623 // Set the user agent to `""`, which uses the default value.
3624 nestedScrollWebView.getSettings().setUserAgentString("");
3627 case SETTINGS_CUSTOM_USER_AGENT:
3628 // Set the default custom user agent.
3629 nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
3633 // Get the user agent string from the user agent data array
3634 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3637 // Set the viewport.
3638 nestedScrollWebView.getSettings().setUseWideViewPort(wideViewport);
3640 // Set the loading of webpage images.
3641 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
3643 // Set a transparent background on URL edit text. The deprecated `getResources().getDrawable()` must be used until the minimum API >= 21.
3644 urlRelativeLayout.setBackground(getResources().getDrawable(R.color.transparent));
3647 // Close the domains database helper.
3648 domainsDatabaseHelper.close();
3650 // Update the privacy icons.
3651 updatePrivacyIcons(true);
3654 // Reload the website if returning from the Domains activity.
3655 if (reloadWebsite) {
3656 nestedScrollWebView.reload();
3659 // Return the user agent changed status.
3660 return !nestedScrollWebView.getSettings().getUserAgentString().equals(initialUserAgent);
3663 private void applyProxyThroughOrbot(boolean reloadWebsite) {
3664 // Get a handle for the shared preferences.
3665 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3667 // Get the search and theme preferences.
3668 String torSearchString = sharedPreferences.getString("tor_search", getString(R.string.tor_search_default_value));
3669 String torSearchCustomUrlString = sharedPreferences.getString("tor_search_custom_url", getString(R.string.tor_search_custom_url_default_value));
3670 String searchString = sharedPreferences.getString("search", getString(R.string.search_default_value));
3671 String searchCustomUrlString = sharedPreferences.getString("search_custom_url", getString(R.string.search_custom_url_default_value));
3672 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
3674 // Get a handle for the app bar layout.
3675 AppBarLayout appBarLayout = findViewById(R.id.appbar_layout);
3677 // Set the homepage, search, and proxy options.
3678 if (proxyThroughOrbot) { // Set the Tor options.
3679 // Set the search URL.
3680 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
3681 searchURL = torSearchCustomUrlString;
3682 } else { // Use the string from the pre-built list.
3683 searchURL = torSearchString;
3686 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
3687 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
3689 // Set the app bar background to indicate proxying through Orbot is enabled.
3691 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
3693 appBarLayout.setBackgroundResource(R.color.blue_50);
3696 // Check to see if Orbot is ready.
3697 if (!orbotStatus.equals("ON")) { // Orbot is not ready.
3698 // Set `waitingForOrbot`.
3699 waitingForOrbot = true;
3701 // Disable the wide view port so that the waiting for Orbot text is displayed correctly.
3702 currentWebView.getSettings().setUseWideViewPort(false);
3704 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
3705 currentWebView.loadData("<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>", "text/html", null);
3706 } else if (reloadWebsite) { // Orbot is ready and the website should be reloaded.
3707 // Reload the website.
3708 currentWebView.reload();
3710 } else { // Set the non-Tor options.
3711 // Set the search URL.
3712 if (searchString.equals("Custom URL")) { // Get the custom URL string.
3713 searchURL = searchCustomUrlString;
3714 } else { // Use the string from the pre-built list.
3715 searchURL = searchString;
3718 // Reset the proxy to default. The host is `""` and the port is `"0"`.
3719 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
3721 // Set the default app bar layout background.
3723 appBarLayout.setBackgroundResource(R.color.gray_900);
3725 appBarLayout.setBackgroundResource(R.color.gray_100);
3728 // Reset `waitingForOrbot.
3729 waitingForOrbot = false;
3731 // Reload the WebViews if requested.
3732 if (reloadWebsite) {
3733 // Reload the WebViews.
3734 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3735 // Get the WebView tab fragment.
3736 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3738 // Get the fragment view.
3739 View fragmentView = webViewTabFragment.getView();
3741 // Only reload the WebViews if they exist.
3742 if (fragmentView != null) {
3743 // Get the nested scroll WebView from the tab fragment.
3744 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3746 // Reload the WebView.
3747 nestedScrollWebView.reload();
3754 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
3755 // Only update the privacy icons if the options menu and the current WebView have already been populated.
3756 if ((optionsMenu != null) && (currentWebView != null)) {
3757 // Get a handle for the shared preferences.
3758 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3760 // Get the theme and screenshot preferences.
3761 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
3763 // Get handles for the menu items.
3764 MenuItem privacyMenuItem = optionsMenu.findItem(R.id.toggle_javascript);
3765 MenuItem firstPartyCookiesMenuItem = optionsMenu.findItem(R.id.toggle_first_party_cookies);
3766 MenuItem domStorageMenuItem = optionsMenu.findItem(R.id.toggle_dom_storage);
3767 MenuItem refreshMenuItem = optionsMenu.findItem(R.id.refresh);
3769 // Update the privacy icon.
3770 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is enabled.
3771 privacyMenuItem.setIcon(R.drawable.javascript_enabled);
3772 } else if (currentWebView.getAcceptFirstPartyCookies()) { // JavaScript is disabled but cookies are enabled.
3773 privacyMenuItem.setIcon(R.drawable.warning);
3774 } else { // All the dangerous features are disabled.
3775 privacyMenuItem.setIcon(R.drawable.privacy_mode);
3778 // Update the first-party cookies icon.
3779 if (currentWebView.getAcceptFirstPartyCookies()) { // First-party cookies are enabled.
3780 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
3781 } else { // First-party cookies are disabled.
3783 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_dark);
3785 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_light);
3789 // Update the DOM storage icon.
3790 if (currentWebView.getSettings().getJavaScriptEnabled() && currentWebView.getSettings().getDomStorageEnabled()) { // Both JavaScript and DOM storage are enabled.
3791 domStorageMenuItem.setIcon(R.drawable.dom_storage_enabled);
3792 } else if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is enabled but DOM storage is disabled.
3794 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
3796 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
3798 } else { // JavaScript is disabled, so DOM storage is ghosted.
3800 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
3802 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
3806 // Update the refresh icon.
3808 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
3810 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
3813 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
3814 if (runInvalidateOptionsMenu) {
3815 invalidateOptionsMenu();
3820 private void openUrlWithExternalApp(String url) {
3821 // Create a download intent. Not specifying the action type will display the maximum number of options.
3822 Intent downloadIntent = new Intent();
3824 // Set the URI and the MIME type. Specifying `text/html` displays a good number of options.
3825 downloadIntent.setDataAndType(Uri.parse(url), "text/html");
3827 // Flag the intent to open in a new task.
3828 downloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3830 // Show the chooser.
3831 startActivity(Intent.createChooser(downloadIntent, getString(R.string.open_with)));
3834 private void highlightUrlText() {
3835 // Get a handle for the URL edit text.
3836 EditText urlEditText = findViewById(R.id.url_edittext);
3838 // Only highlight the URL text if the box is not currently selected.
3839 if (!urlEditText.hasFocus()) {
3840 // Get the URL string.
3841 String urlString = urlEditText.getText().toString();
3843 // Highlight the URL according to the protocol.
3844 if (urlString.startsWith("file://")) { // This is a file URL.
3845 // De-emphasize only the protocol.
3846 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3847 } else if (urlString.startsWith("content://")) {
3848 // De-emphasize only the protocol.
3849 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 10, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3850 } else { // This is a web URL.
3851 // Get the index of the `/` immediately after the domain name.
3852 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
3854 // Create a base URL string.
3857 // Get the base URL.
3858 if (endOfDomainName > 0) { // There is at least one character after the base URL.
3859 // Get the base URL.
3860 baseUrl = urlString.substring(0, endOfDomainName);
3861 } else { // There are no characters after the base URL.
3862 // Set the base URL to be the entire URL string.
3863 baseUrl = urlString;
3866 // Get the index of the last `.` in the domain.
3867 int lastDotIndex = baseUrl.lastIndexOf(".");
3869 // Get the index of the penultimate `.` in the domain.
3870 int penultimateDotIndex = baseUrl.lastIndexOf(".", lastDotIndex - 1);
3872 // Markup the beginning of the URL.
3873 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
3874 urlEditText.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3876 // De-emphasize subdomains.
3877 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
3878 urlEditText.getText().setSpan(initialGrayColorSpan, 7, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3880 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
3881 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
3882 // De-emphasize the protocol and the additional subdomains.
3883 urlEditText.getText().setSpan(initialGrayColorSpan, 0, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3884 } else { // There is only one subdomain in the domain name.
3885 // De-emphasize only the protocol.
3886 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3890 // De-emphasize the text after the domain name.
3891 if (endOfDomainName > 0) {
3892 urlEditText.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3898 private void loadBookmarksFolder() {
3899 // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
3900 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
3902 // Populate the bookmarks cursor adapter. `this` specifies the `Context`. `false` disables `autoRequery`.
3903 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
3905 public View newView(Context context, Cursor cursor, ViewGroup parent) {
3906 // Inflate the individual item layout. `false` does not attach it to the root.
3907 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
3911 public void bindView(View view, Context context, Cursor cursor) {
3912 // Get handles for the views.
3913 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
3914 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
3916 // Get the favorite icon byte array from the cursor.
3917 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
3919 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
3920 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
3922 // Display the bitmap in `bookmarkFavoriteIcon`.
3923 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
3925 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
3926 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
3927 bookmarkNameTextView.setText(bookmarkNameString);
3929 // Make the font bold for folders.
3930 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
3931 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
3932 } else { // Reset the font to default for normal bookmarks.
3933 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
3938 // Get a handle for the bookmarks list view.
3939 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
3941 // Populate the list view with the adapter.
3942 bookmarksListView.setAdapter(bookmarksCursorAdapter);
3944 // Get a handle for the bookmarks title text view.
3945 TextView bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
3947 // Set the bookmarks drawer title.
3948 if (currentBookmarksFolder.isEmpty()) {
3949 bookmarksTitleTextView.setText(R.string.bookmarks);
3951 bookmarksTitleTextView.setText(currentBookmarksFolder);
3955 private void openWithApp(String url) {
3956 // Create the open with intent with `ACTION_VIEW`.
3957 Intent openWithAppIntent = new Intent(Intent.ACTION_VIEW);
3959 // Set the URI but not the MIME type. This should open all available apps.
3960 openWithAppIntent.setData(Uri.parse(url));
3962 // Flag the intent to open in a new task.
3963 openWithAppIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3965 // Show the chooser.
3966 startActivity(openWithAppIntent);
3969 private void openWithBrowser(String url) {
3970 // Create the open with intent with `ACTION_VIEW`.
3971 Intent openWithBrowserIntent = new Intent(Intent.ACTION_VIEW);
3973 // Set the URI and the MIME type. `"text/html"` should load browser options.
3974 openWithBrowserIntent.setDataAndType(Uri.parse(url), "text/html");
3976 // Flag the intent to open in a new task.
3977 openWithBrowserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3979 // Show the chooser.
3980 startActivity(openWithBrowserIntent);
3983 private String sanitizeUrl(String url) {
3984 // Sanitize Google Analytics.
3985 if (sanitizeGoogleAnalytics) {
3987 if (url.contains("?utm_")) {
3988 url = url.substring(0, url.indexOf("?utm_"));
3992 if (url.contains("&utm_")) {
3993 url = url.substring(0, url.indexOf("&utm_"));
3997 // Sanitize Facebook Click IDs.
3998 if (sanitizeFacebookClickIds) {
3999 // Remove `?fbclid=`.
4000 if (url.contains("?fbclid=")) {
4001 url = url.substring(0, url.indexOf("?fbclid="));
4004 // Remove `&fbclid=`.
4005 if (url.contains("&fbclid=")) {
4006 url = url.substring(0, url.indexOf("&fbclid="));
4010 // Sanitize Twitter AMP redirects.
4011 if (sanitizeTwitterAmpRedirects) {
4013 if (url.contains("?amp=1")) {
4014 url = url.substring(0, url.indexOf("?amp=1"));
4018 // Return the sanitized URL.
4022 public void finishedPopulatingBlocklists(ArrayList<ArrayList<List<String[]>>> combinedBlocklists) {
4023 // Store the blocklists.
4024 easyList = combinedBlocklists.get(0);
4025 easyPrivacy = combinedBlocklists.get(1);
4026 fanboysAnnoyanceList = combinedBlocklists.get(2);
4027 fanboysSocialList = combinedBlocklists.get(3);
4028 ultraPrivacy = combinedBlocklists.get(4);
4030 // Add the first tab.
4034 public void addTab(View view) {
4035 // Add a new tab with a blank URL.
4039 private void addNewTab(String url) {
4040 // Sanitize the URL.
4041 url = sanitizeUrl(url);
4043 // Get a handle for the tab layout and the view pager.
4044 TabLayout tabLayout = findViewById(R.id.tablayout);
4045 ViewPager webViewPager = findViewById(R.id.webviewpager);
4047 // Get the new page number. The page numbers are 0 indexed, so the new page number will match the current count.
4048 int newTabNumber = tabLayout.getTabCount();
4051 tabLayout.addTab(tabLayout.newTab());
4054 TabLayout.Tab newTab = tabLayout.getTabAt(newTabNumber);
4056 // Remove the lint warning below that the current tab might be null.
4057 assert newTab != null;
4059 // Set a custom view on the new tab.
4060 newTab.setCustomView(R.layout.tab_custom_view);
4062 // Add the new WebView page.
4063 webViewPagerAdapter.addPage(newTabNumber, webViewPager, url);
4066 public void closeTab(View view) {
4067 // Get a handle for the tab layout.
4068 TabLayout tabLayout = findViewById(R.id.tablayout);
4070 // Run the command according to the number of tabs.
4071 if (tabLayout.getTabCount() > 1) { // There is more than one tab open.
4072 // Close the current tab.
4074 } else { // There is only one tab open.
4079 private void closeCurrentTab() {
4080 // Get handles for the views.
4081 AppBarLayout appBarLayout = findViewById(R.id.appbar_layout);
4082 TabLayout tabLayout = findViewById(R.id.tablayout);
4083 ViewPager webViewPager = findViewById(R.id.webviewpager);
4085 // Get the current tab number.
4086 int currentTabNumber = tabLayout.getSelectedTabPosition();
4088 // Delete the current tab.
4089 tabLayout.removeTabAt(currentTabNumber);
4091 // 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.
4092 if (webViewPagerAdapter.deletePage(currentTabNumber, webViewPager)) {
4093 setCurrentWebView(currentTabNumber);
4096 // Expand the app bar if it is currently collapsed.
4097 appBarLayout.setExpanded(true);
4100 private void clearAndExit() {
4101 // Get a handle for the shared preferences.
4102 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4104 // Close the bookmarks cursor and database.
4105 bookmarksCursor.close();
4106 bookmarksDatabaseHelper.close();
4108 // Get the status of the clear everything preference.
4109 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
4111 // Get a handle for the runtime.
4112 Runtime runtime = Runtime.getRuntime();
4114 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
4115 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
4116 String privateDataDirectoryString = getApplicationInfo().dataDir;
4119 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
4120 // The command to remove cookies changed slightly in API 21.
4121 if (Build.VERSION.SDK_INT >= 21) {
4122 CookieManager.getInstance().removeAllCookies(null);
4124 CookieManager.getInstance().removeAllCookie();
4127 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4129 // Two commands must be used because `Runtime.exec()` does not like `*`.
4130 Process deleteCookiesProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
4131 Process deleteCookiesJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
4133 // Wait until the processes have finished.
4134 deleteCookiesProcess.waitFor();
4135 deleteCookiesJournalProcess.waitFor();
4136 } catch (Exception exception) {
4137 // Do nothing if an error is thrown.
4141 // Clear DOM storage.
4142 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
4143 // Ask `WebStorage` to clear the DOM storage.
4144 WebStorage webStorage = WebStorage.getInstance();
4145 webStorage.deleteAllData();
4147 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4149 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4150 Process deleteLocalStorageProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
4152 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
4153 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
4154 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
4155 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
4156 Process deleteDatabaseProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
4158 // Wait until the processes have finished.
4159 deleteLocalStorageProcess.waitFor();
4160 deleteIndexProcess.waitFor();
4161 deleteQuotaManagerProcess.waitFor();
4162 deleteQuotaManagerJournalProcess.waitFor();
4163 deleteDatabaseProcess.waitFor();
4164 } catch (Exception exception) {
4165 // Do nothing if an error is thrown.
4169 // Clear form data if the API < 26.
4170 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
4171 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
4172 webViewDatabase.clearFormData();
4174 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4176 // A string array must be used because the database contains a space and `Runtime.exec` will not otherwise escape the string correctly.
4177 Process deleteWebDataProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
4178 Process deleteWebDataJournalProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
4180 // Wait until the processes have finished.
4181 deleteWebDataProcess.waitFor();
4182 deleteWebDataJournalProcess.waitFor();
4183 } catch (Exception exception) {
4184 // Do nothing if an error is thrown.
4189 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
4190 // Clear the cache from each WebView.
4191 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4192 // Get the WebView tab fragment.
4193 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4195 // Get the fragment view.
4196 View fragmentView = webViewTabFragment.getView();
4198 // Only clear the cache if the WebView exists.
4199 if (fragmentView != null) {
4200 // Get the nested scroll WebView from the tab fragment.
4201 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4203 // Clear the cache for this WebView.
4204 nestedScrollWebView.clearCache(true);
4208 // Manually delete the cache directories.
4210 // Delete the main cache directory.
4211 Process deleteCacheProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/cache");
4213 // Delete the secondary `Service Worker` cache directory.
4214 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4215 Process deleteServiceWorkerProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
4217 // Wait until the processes have finished.
4218 deleteCacheProcess.waitFor();
4219 deleteServiceWorkerProcess.waitFor();
4220 } catch (Exception exception) {
4221 // Do nothing if an error is thrown.
4225 // Wipe out each WebView.
4226 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4227 // Get the WebView tab fragment.
4228 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4230 // Get the fragment view.
4231 View fragmentView = webViewTabFragment.getView();
4233 // Only wipe out the WebView if it exists.
4234 if (fragmentView != null) {
4235 // Get the nested scroll WebView from the tab fragment.
4236 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4238 // Clear SSL certificate preferences for this WebView.
4239 nestedScrollWebView.clearSslPreferences();
4241 // Clear the back/forward history for this WebView.
4242 nestedScrollWebView.clearHistory();
4244 // Destroy the internal state of `mainWebView`.
4245 nestedScrollWebView.destroy();
4249 // Clear the custom headers.
4250 customHeaders.clear();
4252 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
4253 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
4254 if (clearEverything) {
4256 // Delete the folder.
4257 Process deleteAppWebviewProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
4259 // Wait until the process has finished.
4260 deleteAppWebviewProcess.waitFor();
4261 } catch (Exception exception) {
4262 // Do nothing if an error is thrown.
4266 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
4267 if (Build.VERSION.SDK_INT >= 21) {
4268 finishAndRemoveTask();
4273 // Remove the terminated program from RAM. The status code is `0`.
4277 private void setCurrentWebView(int pageNumber) {
4278 // Get a handle for the shared preferences.
4279 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4281 // Get the theme preference.
4282 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
4284 // Get handles for the URL views.
4285 RelativeLayout urlRelativeLayout = findViewById(R.id.url_relativelayout);
4286 EditText urlEditText = findViewById(R.id.url_edittext);
4287 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
4289 // Stop the swipe to refresh indicator if it is running
4290 swipeRefreshLayout.setRefreshing(false);
4292 // Get the WebView tab fragment.
4293 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(pageNumber);
4295 // Get the fragment view.
4296 View fragmentView = webViewTabFragment.getView();
4298 // Set the current WebView if the fragment view is not null.
4299 if (fragmentView != null) { // The fragment has been populated.
4300 // Store the current WebView.
4301 currentWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4303 // Update the status of swipe to refresh.
4304 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
4305 // Enable the swipe refresh layout if the WebView is scrolled all the way to the top. It is updated every time the scroll changes.
4306 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
4307 } else { // Swipe to refresh is disabled.
4308 // Disable the swipe refresh layout.
4309 swipeRefreshLayout.setEnabled(false);
4312 // Get a handle for the cookie manager.
4313 CookieManager cookieManager = CookieManager.getInstance();
4315 // Set the first-party cookie status.
4316 cookieManager.setAcceptCookie(currentWebView.getAcceptFirstPartyCookies());
4318 // Update the privacy icons. `true` redraws the icons in the app bar.
4319 updatePrivacyIcons(true);
4321 // Get a handle for the input method manager.
4322 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
4324 // Remove the lint warning below that the input method manager might be null.
4325 assert inputMethodManager != null;
4327 // Get the current URL.
4328 String url = currentWebView.getUrl();
4330 // Update the URL edit text if not loading a new intent. Otherwise, this will be handled by `onPageStarted()` (if called) and `onPageFinished()`.
4331 if (!loadingNewIntent) { // A new intent is not being loaded.
4332 if ((url == null) || url.equals("about:blank")) { // The WebView is blank.
4333 // Display the hint in the URL edit text.
4334 urlEditText.setText("");
4336 // Request focus for the URL text box.
4337 urlEditText.requestFocus();
4339 // Display the keyboard.
4340 inputMethodManager.showSoftInput(urlEditText, 0);
4341 } else { // The WebView has a loaded URL.
4342 // Clear the focus from the URL text box.
4343 urlEditText.clearFocus();
4345 // Hide the soft keyboard.
4346 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
4348 // Display the current URL in the URL text box.
4349 urlEditText.setText(url);
4351 // Highlight the URL text.
4354 } else { // A new intent is being loaded.
4355 // Reset the loading new intent tracker.
4356 loadingNewIntent = false;
4359 // Set the background to indicate the domain settings status.
4360 if (currentWebView.getDomainSettingsApplied()) {
4361 // 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.
4363 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
4365 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
4368 urlRelativeLayout.setBackground(getResources().getDrawable(R.color.transparent));
4370 } else { // The fragment has not been populated. Try again in 100 milliseconds.
4371 // Create a handler to set the current WebView.
4372 Handler setCurrentWebViewHandler = new Handler();
4374 // Create a runnable to set the current WebView.
4375 Runnable setCurrentWebWebRunnable = () -> {
4376 // Set the current WebView.
4377 setCurrentWebView(pageNumber);
4380 // Try setting the current WebView again after 100 milliseconds.
4381 setCurrentWebViewHandler.postDelayed(setCurrentWebWebRunnable, 100);
4386 public void initializeWebView(NestedScrollWebView nestedScrollWebView, int pageNumber, ProgressBar progressBar, String url) {
4387 // Get handles for the activity views.
4388 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
4389 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
4390 RelativeLayout mainContentRelativeLayout = findViewById(R.id.main_content_relativelayout);
4391 ActionBar actionBar = getSupportActionBar();
4392 LinearLayout tabsLinearLayout = findViewById(R.id.tabs_linearlayout);
4393 EditText urlEditText = findViewById(R.id.url_edittext);
4394 TabLayout tabLayout = findViewById(R.id.tablayout);
4395 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
4397 // Remove the incorrect lint warning below that the action bar might be null.
4398 assert actionBar != null;
4400 // Get a handle for the activity
4401 Activity activity = this;
4403 // Get a handle for the input method manager.
4404 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
4406 // Instantiate the blocklist helper.
4407 BlocklistHelper blocklistHelper = new BlocklistHelper();
4409 // Remove the lint warning below that the input method manager might be null.
4410 assert inputMethodManager != null;
4412 // Get a handle for the shared preferences.
4413 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4415 // Initialize the favorite icon.
4416 nestedScrollWebView.initializeFavoriteIcon();
4418 // Set the app bar scrolling.
4419 nestedScrollWebView.setNestedScrollingEnabled(sharedPreferences.getBoolean("scroll_app_bar", true));
4421 // Allow pinch to zoom.
4422 nestedScrollWebView.getSettings().setBuiltInZoomControls(true);
4424 // Hide zoom controls.
4425 nestedScrollWebView.getSettings().setDisplayZoomControls(false);
4427 // Don't allow mixed content (HTTP and HTTPS) on the same website.
4428 if (Build.VERSION.SDK_INT >= 21) {
4429 nestedScrollWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW);
4432 // Set the WebView to load in overview mode (zoomed out to the maximum width).
4433 nestedScrollWebView.getSettings().setLoadWithOverviewMode(true);
4435 // Explicitly disable geolocation.
4436 nestedScrollWebView.getSettings().setGeolocationEnabled(false);
4438 // Create a double-tap gesture detector to toggle full-screen mode.
4439 GestureDetector doubleTapGestureDetector = new GestureDetector(getApplicationContext(), new GestureDetector.SimpleOnGestureListener() {
4440 // Override `onDoubleTap()`. All other events are handled using the default settings.
4442 public boolean onDoubleTap(MotionEvent event) {
4443 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
4444 // Toggle the full screen browsing mode tracker.
4445 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
4447 // Toggle the full screen browsing mode.
4448 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
4449 // Store the swipe refresh layout top padding.
4450 swipeRefreshLayoutPaddingTop = swipeRefreshLayout.getPaddingTop();
4452 // Hide the app bar if specified.
4454 // Close the find on page bar if it is visible.
4455 closeFindOnPage(null);
4457 // Hide the tab linear layout.
4458 tabsLinearLayout.setVisibility(View.GONE);
4460 // Hide the action bar.
4463 // Check to see if app bar scrolling is disabled.
4464 if (!scrollAppBar) {
4465 // Remove the padding from the top of the swipe refresh layout.
4466 swipeRefreshLayout.setPadding(0, 0, 0, 0);
4470 // Hide the banner ad in the free flavor.
4471 if (BuildConfig.FLAVOR.contentEquals("free")) {
4472 AdHelper.hideAd(findViewById(R.id.adview));
4475 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
4476 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4478 /* Hide the system bars.
4479 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4480 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4481 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4482 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4484 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
4485 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
4486 } else { // Switch to normal viewing mode.
4487 // Show the tab linear layout.
4488 tabsLinearLayout.setVisibility(View.VISIBLE);
4490 // Show the action bar.
4493 // Check to see if app bar scrolling is disabled.
4494 if (!scrollAppBar) {
4495 // Add the padding from the top of the swipe refresh layout.
4496 swipeRefreshLayout.setPadding(0, swipeRefreshLayoutPaddingTop, 0, 0);
4499 // Show the banner ad in the free flavor.
4500 if (BuildConfig.FLAVOR.contentEquals("free")) {
4502 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
4505 // Remove the `SYSTEM_UI` flags from the root frame layout.
4506 rootFrameLayout.setSystemUiVisibility(0);
4508 // Add the translucent status flag.
4509 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4512 // Consume the double-tap.
4514 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
4520 // Pass all touch events on the WebView through the double-tap gesture detector.
4521 nestedScrollWebView.setOnTouchListener((View view, MotionEvent event) -> {
4522 // Call `performClick()` on the view, which is required for accessibility.
4523 view.performClick();
4525 // Send the event to the gesture detector.
4526 return doubleTapGestureDetector.onTouchEvent(event);
4529 // Register the WebView for a context menu. This is used to see link targets and download images.
4530 registerForContextMenu(nestedScrollWebView);
4532 // Allow the downloading of files.
4533 nestedScrollWebView.setDownloadListener((String downloadUrl, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
4534 // Check if the download should be processed by an external app.
4535 if (sharedPreferences.getBoolean("download_with_external_app", false)) { // Download with an external app.
4536 // Create a download intent. Not specifying the action type will display the maximum number of options.
4537 Intent downloadIntent = new Intent();
4539 // Set the URI and the MIME type. Specifying `text/html` displays a good number of options.
4540 downloadIntent.setDataAndType(Uri.parse(downloadUrl), "text/html");
4542 // Flag the intent to open in a new task.
4543 downloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4545 // Show the chooser.
4546 startActivity(Intent.createChooser(downloadIntent, getString(R.string.open_with)));
4547 } else { // Download with Android's download manager.
4548 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
4549 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission has not been granted.
4550 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
4552 // Store the variables for future use by `onRequestPermissionsResult()`.
4553 this.downloadUrl = downloadUrl;
4554 downloadContentDisposition = contentDisposition;
4555 downloadContentLength = contentLength;
4557 // Show a dialog if the user has previously denied the permission.
4558 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
4559 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
4560 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
4562 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
4563 downloadLocationPermissionDialogFragment.show(getSupportFragmentManager(), getString(R.string.download_location));
4564 } else { // Show the permission request directly.
4565 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
4566 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
4568 } else { // The storage permission has already been granted.
4569 // Get a handle for the download file alert dialog.
4570 DialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(downloadUrl, contentDisposition, contentLength);
4572 // Show the download file alert dialog.
4573 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
4578 // Update the find on page count.
4579 nestedScrollWebView.setFindListener(new WebView.FindListener() {
4580 // Get a handle for `findOnPageCountTextView`.
4581 final TextView findOnPageCountTextView = findViewById(R.id.find_on_page_count_textview);
4584 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
4585 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
4586 // Set `findOnPageCountTextView` to `0/0`.
4587 findOnPageCountTextView.setText(R.string.zero_of_zero);
4588 } else if (isDoneCounting) { // There are matches.
4589 // `activeMatchOrdinal` is zero-based.
4590 int activeMatch = activeMatchOrdinal + 1;
4592 // Build the match string.
4593 String matchString = activeMatch + "/" + numberOfMatches;
4595 // Set `findOnPageCountTextView`.
4596 findOnPageCountTextView.setText(matchString);
4601 // Update the status of swipe to refresh based on the scroll position of the nested scroll WebView.
4602 // Once the minimum API >= 23 this can be replaced with `nestedScrollWebView.setOnScrollChangeListener()`.
4603 nestedScrollWebView.getViewTreeObserver().addOnScrollChangedListener(() -> {
4604 if (nestedScrollWebView.getSwipeToRefresh()) {
4605 // Only enable swipe to refresh if the WebView is scrolled to the top.
4606 swipeRefreshLayout.setEnabled(nestedScrollWebView.getScrollY() == 0);
4610 // Set the web chrome client.
4611 nestedScrollWebView.setWebChromeClient(new WebChromeClient() {
4612 // Update the progress bar when a page is loading.
4614 public void onProgressChanged(WebView view, int progress) {
4615 // Inject the night mode CSS if night mode is enabled.
4616 if (nestedScrollWebView.getNightMode()) { // Night mode is enabled.
4617 // `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
4618 // used by WordPress. `text-decoration: none` removes all text underlines. `text-shadow: none` removes text shadows, which usually have a hard coded color.
4619 // `border: none` removes all borders, which can also be used to underline text. `a {color: #1565C0}` sets links to be a dark blue.
4620 // `::selection {background: #0D47A1}' sets the text selection highlight color to be a dark blue. `!important` takes precedent over any existing sub-settings.
4621 nestedScrollWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; " +
4622 "style.innerHTML = '* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important;" +
4623 "text-shadow: none !important; border: none !important;} a {color: #1565C0 !important;} ::selection {background: #0D47A1 !important;}'; parent.appendChild(style)})()", value -> {
4624 // Initialize a handler to display `mainWebView`.
4625 Handler displayWebViewHandler = new Handler();
4627 // Setup a runnable to display `mainWebView` after a delay to allow the CSS to be applied.
4628 Runnable displayWebViewRunnable = () -> {
4629 // Only display `mainWebView` if the progress bar is gone. This prevents the display of the `WebView` while it is still loading.
4630 if (progressBar.getVisibility() == View.GONE) {
4631 nestedScrollWebView.setVisibility(View.VISIBLE);
4635 // Display the WebView after 500 milliseconds.
4636 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
4638 } else { // Night mode is disabled.
4639 // Display the nested scroll WebView if night mode is disabled.
4640 // Because of a race condition between `applyDomainSettings` and `onPageStarted`,
4641 // when night mode is set by domain settings the WebView may be hidden even if night mode is not currently enabled.
4642 nestedScrollWebView.setVisibility(View.VISIBLE);
4645 // Update the progress bar.
4646 progressBar.setProgress(progress);
4648 // Set the visibility of the progress bar.
4649 if (progress < 100) {
4650 // Show the progress bar.
4651 progressBar.setVisibility(View.VISIBLE);
4653 // Hide the progress bar.
4654 progressBar.setVisibility(View.GONE);
4656 //Stop the swipe to refresh indicator if it is running
4657 swipeRefreshLayout.setRefreshing(false);
4661 // Set the favorite icon when it changes.
4663 public void onReceivedIcon(WebView view, Bitmap icon) {
4664 // Only update the favorite icon if the website has finished loading.
4665 if (progressBar.getVisibility() == View.GONE) {
4666 // Store the new favorite icon.
4667 nestedScrollWebView.setFavoriteOrDefaultIcon(icon);
4669 // Get the current page position.
4670 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
4672 // Get the current tab.
4673 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
4675 // Check to see if the tab has been populated.
4677 // Get the custom view from the tab.
4678 View tabView = tab.getCustomView();
4680 // Check to see if the custom tab view has been populated.
4681 if (tabView != null) {
4682 // Get the favorite icon image view from the tab.
4683 ImageView tabFavoriteIconImageView = tabView.findViewById(R.id.favorite_icon_imageview);
4685 // Display the favorite icon in the tab.
4686 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
4692 // Save a copy of the title when it changes.
4694 public void onReceivedTitle(WebView view, String title) {
4695 // Get the current page position.
4696 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
4698 // Get the current tab.
4699 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
4701 // Only populate the title text view if the tab has been fully created.
4703 // Get the custom view from the tab.
4704 View tabView = tab.getCustomView();
4706 // Remove the incorrect warning below that the current tab view might be null.
4707 assert tabView != null;
4709 // Get the title text view from the tab.
4710 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
4712 // Set the title according to the URL.
4713 if (title.equals("about:blank")) {
4714 // Set the title to indicate a new tab.
4715 tabTitleTextView.setText(R.string.new_tab);
4717 // Set the title as the tab text.
4718 tabTitleTextView.setText(title);
4723 // Enter full screen video.
4725 public void onShowCustomView(View video, CustomViewCallback callback) {
4726 // Get a handle for the full screen video frame layout.
4727 FrameLayout fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
4729 // Set the full screen video flag.
4730 displayingFullScreenVideo = true;
4732 // Pause the ad if this is the free flavor.
4733 if (BuildConfig.FLAVOR.contentEquals("free")) {
4734 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
4735 AdHelper.pauseAd(findViewById(R.id.adview));
4738 // Hide the keyboard.
4739 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
4741 // Hide the main content relative layout.
4742 mainContentRelativeLayout.setVisibility(View.GONE);
4744 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
4745 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
4747 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
4748 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4750 /* Hide the system bars.
4751 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4752 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4753 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4754 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4756 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
4757 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
4759 // Disable the sliding drawers.
4760 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
4762 // Add the video view to the full screen video frame layout.
4763 fullScreenVideoFrameLayout.addView(video);
4765 // Show the full screen video frame layout.
4766 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
4769 // Exit full screen video.
4771 public void onHideCustomView() {
4772 // Get a handle for the full screen video frame layout.
4773 FrameLayout fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
4775 // Unset the full screen video flag.
4776 displayingFullScreenVideo = false;
4778 // Remove all the views from the full screen video frame layout.
4779 fullScreenVideoFrameLayout.removeAllViews();
4781 // Hide the full screen video frame layout.
4782 fullScreenVideoFrameLayout.setVisibility(View.GONE);
4784 // Enable the sliding drawers.
4785 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
4787 // Show the main content relative layout.
4788 mainContentRelativeLayout.setVisibility(View.VISIBLE);
4790 // Apply the appropriate full screen mode flags.
4791 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
4792 // Hide the app bar if specified.
4794 // Hide the tab linear layout.
4795 tabsLinearLayout.setVisibility(View.GONE);
4797 // Hide the action bar.
4801 // Hide the banner ad in the free flavor.
4802 if (BuildConfig.FLAVOR.contentEquals("free")) {
4803 AdHelper.hideAd(findViewById(R.id.adview));
4806 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
4807 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4809 /* Hide the system bars.
4810 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4811 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4812 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4813 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4815 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
4816 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
4817 } else { // Switch to normal viewing mode.
4818 // Remove the `SYSTEM_UI` flags from the root frame layout.
4819 rootFrameLayout.setSystemUiVisibility(0);
4821 // Add the translucent status flag.
4822 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4825 // Reload the ad for the free flavor if not in full screen mode.
4826 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
4828 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
4834 public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
4835 // Show the file chooser if the device is running API >= 21.
4836 if (Build.VERSION.SDK_INT >= 21) {
4837 // Store the file path callback.
4838 fileChooserCallback = filePathCallback;
4840 // Create an intent to open a chooser based ont the file chooser parameters.
4841 Intent fileChooserIntent = fileChooserParams.createIntent();
4843 // Open the file chooser. Currently only one `startActivityForResult` exists in this activity, so the request code, used to differentiate them, is simply `0`.
4844 startActivityForResult(fileChooserIntent, 0);
4850 nestedScrollWebView.setWebViewClient(new WebViewClient() {
4851 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
4852 // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
4854 public boolean shouldOverrideUrlLoading(WebView view, String url) {
4855 // Sanitize the url.
4856 url = sanitizeUrl(url);
4858 if (url.startsWith("http")) { // Load the URL in Privacy Browser.
4859 // Apply the domain settings for the new URL. This doesn't do anything if the domain has not changed.
4860 boolean userAgentChanged = applyDomainSettings(nestedScrollWebView, url, true, false);
4862 // Check if the user agent has changed.
4863 if (userAgentChanged) {
4864 // Manually load the URL. The changing of the user agent will cause WebView to reload the previous URL.
4865 nestedScrollWebView.loadUrl(url, customHeaders);
4867 // Returning true indicates that Privacy Browser is manually handling the loading of the URL.
4870 // Returning false causes the current WebView to handle the URL and prevents it from adding redirects to the history list.
4873 } else if (url.startsWith("mailto:")) { // Load the email address in an external email program.
4874 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
4875 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
4877 // Parse the url and set it as the data for the intent.
4878 emailIntent.setData(Uri.parse(url));
4880 // Open the email program in a new task instead of as part of Privacy Browser.
4881 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4884 startActivity(emailIntent);
4886 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
4888 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
4889 // Open the dialer and load the phone number, but wait for the user to place the call.
4890 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
4892 // Add the phone number to the intent.
4893 dialIntent.setData(Uri.parse(url));
4895 // Open the dialer in a new task instead of as part of Privacy Browser.
4896 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4899 startActivity(dialIntent);
4901 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
4903 } else { // Load a system chooser to select an app that can handle the URL.
4904 // Open an app that can handle the URL.
4905 Intent genericIntent = new Intent(Intent.ACTION_VIEW);
4907 // Add the URL to the intent.
4908 genericIntent.setData(Uri.parse(url));
4910 // List all apps that can handle the URL instead of just opening the first one.
4911 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
4913 // Open the app in a new task instead of as part of Privacy Browser.
4914 genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4916 // Start the app or display a snackbar if no app is available to handle the URL.
4918 startActivity(genericIntent);
4919 } catch (ActivityNotFoundException exception) {
4920 Snackbar.make(nestedScrollWebView, getString(R.string.unrecognized_url) + " " + url, Snackbar.LENGTH_SHORT).show();
4923 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
4928 // Check requests against the block lists. The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
4930 public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
4931 // Sanitize the URL.
4932 url = sanitizeUrl(url);
4934 // Get a handle for the navigation view.
4935 NavigationView navigationView = findViewById(R.id.navigationview);
4937 // Get a handle for the navigation menu.
4938 Menu navigationMenu = navigationView.getMenu();
4940 // Get a handle for the navigation requests menu item. The menu is 0 based.
4941 MenuItem navigationRequestsMenuItem = navigationMenu.getItem(5);
4943 // Create an empty web resource response to be used if the resource request is blocked.
4944 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
4946 // Reset the whitelist results tracker.
4947 String[] whitelistResultStringArray = null;
4949 // Initialize the third party request tracker.
4950 boolean isThirdPartyRequest = false;
4952 // Get the current URL. `.getUrl()` throws an error because operations on the WebView cannot be made from this thread.
4953 String currentBaseDomain = nestedScrollWebView.getCurrentDomainName();
4955 // Store a copy of the current domain for use in later requests.
4956 String currentDomain = currentBaseDomain;
4958 // Nobody is happy when comparing null strings.
4959 if ((currentBaseDomain != null) && (url != null)) {
4960 // Convert the request URL to a URI.
4961 Uri requestUri = Uri.parse(url);
4963 // Get the request host name.
4964 String requestBaseDomain = requestUri.getHost();
4966 // Only check for third-party requests if the current base domain is not empty and the request domain is not null.
4967 if (!currentBaseDomain.isEmpty() && (requestBaseDomain != null)) {
4968 // Determine the current base domain.
4969 while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
4970 // Remove the first subdomain.
4971 currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
4974 // Determine the request base domain.
4975 while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
4976 // Remove the first subdomain.
4977 requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
4980 // Update the third party request tracker.
4981 isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
4985 // Get the current WebView page position.
4986 int webViewPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
4988 // Determine if the WebView is currently displayed.
4989 boolean webViewDisplayed = (webViewPagePosition == tabLayout.getSelectedTabPosition());
4991 // Block third-party requests if enabled.
4992 if (isThirdPartyRequest && nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS)) {
4993 // Add the result to the resource requests.
4994 nestedScrollWebView.addResourceRequest(new String[]{BlocklistHelper.REQUEST_THIRD_PARTY, url});
4996 // Increment the blocked requests counters.
4997 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
4998 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS);
5000 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5001 if (webViewDisplayed) {
5002 // Updating the UI must be run from the UI thread.
5003 activity.runOnUiThread(() -> {
5004 // Update the menu item titles.
5005 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5007 // Update the options menu if it has been populated.
5008 if (optionsMenu != null) {
5009 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5010 optionsMenu.findItem(R.id.block_all_third_party_requests).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " +
5011 getString(R.string.block_all_third_party_requests));
5016 // Return an empty web resource response.
5017 return emptyWebResourceResponse;
5020 // Check UltraPrivacy if it is enabled.
5021 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY)) {
5022 // Check the URL against UltraPrivacy.
5023 String[] ultraPrivacyResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraPrivacy);
5025 // Process the UltraPrivacy results.
5026 if (ultraPrivacyResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched UltraPrivacy's blacklist.
5027 // Add the result to the resource requests.
5028 nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5029 ultraPrivacyResults[5]});
5031 // Increment the blocked requests counters.
5032 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5033 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRA_PRIVACY);
5035 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5036 if (webViewDisplayed) {
5037 // Updating the UI must be run from the UI thread.
5038 activity.runOnUiThread(() -> {
5039 // Update the menu item titles.
5040 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5042 // Update the options menu if it has been populated.
5043 if (optionsMenu != null) {
5044 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5045 optionsMenu.findItem(R.id.ultraprivacy).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRA_PRIVACY) + " - " + getString(R.string.ultraprivacy));
5050 // The resource request was blocked. Return an empty web resource response.
5051 return emptyWebResourceResponse;
5052 } else if (ultraPrivacyResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched UltraPrivacy's whitelist.
5053 // Add a whitelist entry to the resource requests array.
5054 nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5055 ultraPrivacyResults[5]});
5057 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
5062 // Check EasyList if it is enabled.
5063 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST)) {
5064 // Check the URL against EasyList.
5065 String[] easyListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyList);
5067 // Process the EasyList results.
5068 if (easyListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched EasyList's blacklist.
5069 // Add the result to the resource requests.
5070 nestedScrollWebView.addResourceRequest(new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]});
5072 // Increment the blocked requests counters.
5073 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5074 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASY_LIST);
5076 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5077 if (webViewDisplayed) {
5078 // Updating the UI must be run from the UI thread.
5079 activity.runOnUiThread(() -> {
5080 // Update the menu item titles.
5081 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5083 // Update the options menu if it has been populated.
5084 if (optionsMenu != null) {
5085 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5086 optionsMenu.findItem(R.id.easylist).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASY_LIST) + " - " + getString(R.string.easylist));
5091 // The resource request was blocked. Return an empty web resource response.
5092 return emptyWebResourceResponse;
5093 } else if (easyListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched EasyList's whitelist.
5094 // Update the whitelist result string array tracker.
5095 whitelistResultStringArray = new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]};
5099 // Check EasyPrivacy if it is enabled.
5100 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY)) {
5101 // Check the URL against EasyPrivacy.
5102 String[] easyPrivacyResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyPrivacy);
5104 // Process the EasyPrivacy results.
5105 if (easyPrivacyResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched EasyPrivacy's blacklist.
5106 // Add the result to the resource requests.
5107 nestedScrollWebView.addResourceRequest(new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4],
5108 easyPrivacyResults[5]});
5110 // Increment the blocked requests counters.
5111 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5112 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASY_PRIVACY);
5114 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5115 if (webViewDisplayed) {
5116 // Updating the UI must be run from the UI thread.
5117 activity.runOnUiThread(() -> {
5118 // Update the menu item titles.
5119 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5121 // Update the options menu if it has been populated.
5122 if (optionsMenu != null) {
5123 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5124 optionsMenu.findItem(R.id.easyprivacy).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASY_PRIVACY) + " - " + getString(R.string.easyprivacy));
5129 // The resource request was blocked. Return an empty web resource response.
5130 return emptyWebResourceResponse;
5131 } else if (easyPrivacyResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched EasyPrivacy's whitelist.
5132 // Update the whitelist result string array tracker.
5133 whitelistResultStringArray = new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5]};
5137 // Check Fanboy’s Annoyance List if it is enabled.
5138 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST)) {
5139 // Check the URL against Fanboy's Annoyance List.
5140 String[] fanboysAnnoyanceListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList);
5142 // Process the Fanboy's Annoyance List results.
5143 if (fanboysAnnoyanceListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched Fanboy's Annoyance List's blacklist.
5144 // Add the result to the resource requests.
5145 nestedScrollWebView.addResourceRequest(new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5146 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]});
5148 // Increment the blocked requests counters.
5149 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5150 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST);
5152 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5153 if (webViewDisplayed) {
5154 // Updating the UI must be run from the UI thread.
5155 activity.runOnUiThread(() -> {
5156 // Update the menu item titles.
5157 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5159 // Update the options menu if it has been populated.
5160 if (optionsMenu != null) {
5161 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5162 optionsMenu.findItem(R.id.fanboys_annoyance_list).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " +
5163 getString(R.string.fanboys_annoyance_list));
5168 // The resource request was blocked. Return an empty web resource response.
5169 return emptyWebResourceResponse;
5170 } else if (fanboysAnnoyanceListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)){ // The resource request matched Fanboy's Annoyance List's whitelist.
5171 // Update the whitelist result string array tracker.
5172 whitelistResultStringArray = new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5173 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]};
5175 } else if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST)) { // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
5176 // Check the URL against Fanboy's Annoyance List.
5177 String[] fanboysSocialListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysSocialList);
5179 // Process the Fanboy's Social Blocking List results.
5180 if (fanboysSocialListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched Fanboy's Social Blocking List's blacklist.
5181 // Add the result to the resource requests.
5182 nestedScrollWebView.addResourceRequest(new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5183 fanboysSocialListResults[4], fanboysSocialListResults[5]});
5185 // Increment the blocked requests counters.
5186 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5187 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST);
5189 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5190 if (webViewDisplayed) {
5191 // Updating the UI must be run from the UI thread.
5192 activity.runOnUiThread(() -> {
5193 // Update the menu item titles.
5194 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5196 // Update the options menu if it has been populated.
5197 if (optionsMenu != null) {
5198 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5199 optionsMenu.findItem(R.id.fanboys_social_blocking_list).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " +
5200 getString(R.string.fanboys_social_blocking_list));
5205 // The resource request was blocked. Return an empty web resource response.
5206 return emptyWebResourceResponse;
5207 } else if (fanboysSocialListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched Fanboy's Social Blocking List's whitelist.
5208 // Update the whitelist result string array tracker.
5209 whitelistResultStringArray = new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5210 fanboysSocialListResults[4], fanboysSocialListResults[5]};
5214 // Add the request to the log because it hasn't been processed by any of the previous checks.
5215 if (whitelistResultStringArray != null) { // The request was processed by a whitelist.
5216 nestedScrollWebView.addResourceRequest(whitelistResultStringArray);
5217 } else { // The request didn't match any blocklist entry. Log it as a default request.
5218 nestedScrollWebView.addResourceRequest(new String[]{BlocklistHelper.REQUEST_DEFAULT, url});
5221 // The resource request has not been blocked. `return null` loads the requested resource.
5225 // Handle HTTP authentication requests.
5227 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
5228 // Store the handler.
5229 nestedScrollWebView.setHttpAuthHandler(handler);
5231 // Instantiate an HTTP authentication dialog.
5232 DialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm, nestedScrollWebView.getWebViewFragmentId());
5234 // Show the HTTP authentication dialog.
5235 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
5239 public void onPageStarted(WebView view, String url, Bitmap favicon) {
5240 // Get the preferences.
5241 boolean scrollAppBar = sharedPreferences.getBoolean("scroll_app_bar", true);
5242 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
5244 // Get a handler for the app bar layout.
5245 AppBarLayout appBarLayout = findViewById(R.id.appbar_layout);
5247 // Set the top padding of the swipe refresh layout according to the app bar scrolling preference.
5249 // No padding is needed because it will automatically be placed below the app bar layout due to the scrolling layout behavior.
5250 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5252 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5253 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10, defaultProgressViewEndOffset);
5255 // Get the app bar layout height. This can't be done in `applyAppSettings()` because the app bar is not yet populated.
5256 int appBarHeight = appBarLayout.getHeight();
5258 // The swipe refresh layout must be manually moved below the app bar layout.
5259 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0);
5261 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5262 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight);
5265 // Reset the list of resource requests.
5266 nestedScrollWebView.clearResourceRequests();
5268 // Reset the requests counters.
5269 nestedScrollWebView.resetRequestsCounters();
5271 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
5272 if (nestedScrollWebView.getNightMode()) {
5273 nestedScrollWebView.setVisibility(View.INVISIBLE);
5275 nestedScrollWebView.setVisibility(View.VISIBLE);
5278 // Hide the keyboard.
5279 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
5281 // Check to see if Privacy Browser is waiting on Orbot.
5282 if (!waitingForOrbot) { // Process the URL.
5283 // Get the current page position.
5284 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5286 // Update the URL text bar if the page is currently selected.
5287 if (tabLayout.getSelectedTabPosition() == currentPagePosition) {
5288 // Clear the focus from the URL edit text.
5289 urlEditText.clearFocus();
5291 // Display the formatted URL text.
5292 urlEditText.setText(url);
5294 // Apply text highlighting to `urlTextBox`.
5298 // Reset the list of host IP addresses.
5299 nestedScrollWebView.clearCurrentIpAddresses();
5301 // Get a URI for the current URL.
5302 Uri currentUri = Uri.parse(url);
5304 // Get the IP addresses for the host.
5305 new GetHostIpAddresses(activity, getSupportFragmentManager(), nestedScrollWebView).execute(currentUri.getHost());
5307 // Apply any custom domain settings if the URL was loaded by navigating history.
5308 if (nestedScrollWebView.getNavigatingHistory()) {
5309 // Reset navigating history.
5310 nestedScrollWebView.setNavigatingHistory(false);
5312 // Apply the domain settings.
5313 boolean userAgentChanged = applyDomainSettings(nestedScrollWebView, url, true, false);
5315 // Manually load the URL if the user agent has changed, which will have caused the previous URL to be reloaded.
5316 if (userAgentChanged) {
5321 // Replace Refresh with Stop if the options menu has been created. (The first WebView typically begins loading before the menu items are instantiated.)
5322 if (optionsMenu != null) {
5323 // Get a handle for the refresh menu item.
5324 MenuItem refreshMenuItem = optionsMenu.findItem(R.id.refresh);
5327 refreshMenuItem.setTitle(R.string.stop);
5329 // Get the app bar and theme preferences.
5330 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
5332 // If the icon is displayed in the AppBar, set it according to the theme.
5333 if (displayAdditionalAppBarIcons) {
5335 refreshMenuItem.setIcon(R.drawable.close_dark);
5337 refreshMenuItem.setIcon(R.drawable.close_light);
5345 public void onPageFinished(WebView view, String url) {
5346 // Flush any cookies to persistent storage. The cookie manager has become very lazy about flushing cookies in recent versions.
5347 if (nestedScrollWebView.getAcceptFirstPartyCookies() && Build.VERSION.SDK_INT >= 21) {
5348 CookieManager.getInstance().flush();
5351 // Update the Refresh menu item if the options menu has been created.
5352 if (optionsMenu != null) {
5353 // Get a handle for the refresh menu item.
5354 MenuItem refreshMenuItem = optionsMenu.findItem(R.id.refresh);
5356 // Reset the Refresh title.
5357 refreshMenuItem.setTitle(R.string.refresh);
5359 // Get the app bar and theme preferences.
5360 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
5361 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
5363 // If the icon is displayed in the AppBar, reset it according to the theme.
5364 if (displayAdditionalAppBarIcons) {
5366 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
5368 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
5373 // Clear the cache and history if Incognito Mode is enabled.
5374 if (incognitoModeEnabled) {
5375 // Clear the cache. `true` includes disk files.
5376 nestedScrollWebView.clearCache(true);
5378 // Clear the back/forward history.
5379 nestedScrollWebView.clearHistory();
5381 // Manually delete cache folders.
5383 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
5384 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
5385 String privateDataDirectoryString = getApplicationInfo().dataDir;
5387 // Delete the main cache directory.
5388 Runtime.getRuntime().exec("rm -rf " + privateDataDirectoryString + "/cache");
5390 // Delete the secondary `Service Worker` cache directory.
5391 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
5392 Runtime.getRuntime().exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
5393 } catch (IOException e) {
5394 // Do nothing if an error is thrown.
5398 // Update the URL text box and apply domain settings if not waiting on Orbot.
5399 if (!waitingForOrbot) {
5400 // Get the current page position.
5401 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5403 // Check the current website information against any pinned domain information if the current IP addresses have been loaded.
5404 if ((nestedScrollWebView.hasPinnedSslCertificate() || nestedScrollWebView.hasPinnedIpAddresses()) && nestedScrollWebView.hasCurrentIpAddresses() &&
5405 !nestedScrollWebView.ignorePinnedDomainInformation()) {
5406 CheckPinnedMismatchHelper.checkPinnedMismatch(getSupportFragmentManager(), nestedScrollWebView);
5409 // 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.
5410 String currentUrl = nestedScrollWebView.getUrl();
5412 // Get the current tab.
5413 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
5415 // Update the URL text bar if the page is currently selected and the user is not currently typing in the URL edit text.
5416 // Crash records show that, in some crazy way, it is possible for the current URL to be blank at this point.
5417 // Probably some sort of race condition when Privacy Browser is being resumed.
5418 if ((tabLayout.getSelectedTabPosition() == currentPagePosition) && !urlEditText.hasFocus() && (currentUrl != null)) {
5419 // Check to see if the URL is `about:blank`.
5420 if (currentUrl.equals("about:blank")) { // The WebView is blank.
5421 // Display the hint in the URL edit text.
5422 urlEditText.setText("");
5424 // Request focus for the URL text box.
5425 urlEditText.requestFocus();
5427 // Display the keyboard.
5428 inputMethodManager.showSoftInput(urlEditText, 0);
5430 // Apply the domain settings. This clears any settings from the previous domain.
5431 applyDomainSettings(nestedScrollWebView, "", true, false);
5433 // Only populate the title text view if the tab has been fully created.
5435 // Get the custom view from the tab.
5436 View tabView = tab.getCustomView();
5438 // Remove the incorrect warning below that the current tab view might be null.
5439 assert tabView != null;
5441 // Get the title text view from the tab.
5442 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
5444 // Set the title as the tab text.
5445 tabTitleTextView.setText(R.string.new_tab);
5447 } else { // The WebView has loaded a webpage.
5448 // Display the final URL. Getting the URL from the WebView instead of using the one provided by `onPageFinished()` makes websites like YouTube function correctly.
5449 urlEditText.setText(currentUrl);
5451 // Apply text highlighting to the URL.
5454 // Only populate the title text view if the tab has been fully created.
5456 // Get the custom view from the tab.
5457 View tabView = tab.getCustomView();
5459 // Remove the incorrect warning below that the current tab view might be null.
5460 assert tabView != null;
5462 // Get the title text view from the tab.
5463 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
5465 // Set the title as the tab text. Sometimes `onReceivedTitle()` is not called, especially when navigating history.
5466 tabTitleTextView.setText(nestedScrollWebView.getTitle());
5473 // Handle SSL Certificate errors.
5475 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
5476 // Get the current website SSL certificate.
5477 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
5479 // Extract the individual pieces of information from the current website SSL certificate.
5480 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
5481 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
5482 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
5483 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
5484 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
5485 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
5486 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
5487 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
5489 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
5490 if (nestedScrollWebView.hasPinnedSslCertificate()) {
5491 // Get the pinned SSL certificate.
5492 ArrayList<Object> pinnedSslCertificateArrayList = nestedScrollWebView.getPinnedSslCertificate();
5494 // Extract the arrays from the array list.
5495 String[] pinnedSslCertificateStringArray = (String[]) pinnedSslCertificateArrayList.get(0);
5496 Date[] pinnedSslCertificateDateArray = (Date[]) pinnedSslCertificateArrayList.get(1);
5498 // Check if the current SSL certificate matches the pinned certificate.
5499 if (currentWebsiteIssuedToCName.equals(pinnedSslCertificateStringArray[0]) && currentWebsiteIssuedToOName.equals(pinnedSslCertificateStringArray[1]) &&
5500 currentWebsiteIssuedToUName.equals(pinnedSslCertificateStringArray[2]) && currentWebsiteIssuedByCName.equals(pinnedSslCertificateStringArray[3]) &&
5501 currentWebsiteIssuedByOName.equals(pinnedSslCertificateStringArray[4]) && currentWebsiteIssuedByUName.equals(pinnedSslCertificateStringArray[5]) &&
5502 currentWebsiteSslStartDate.equals(pinnedSslCertificateDateArray[0]) && currentWebsiteSslEndDate.equals(pinnedSslCertificateDateArray[1])) {
5504 // An SSL certificate is pinned and matches the current domain certificate. Proceed to the website without displaying an error.
5507 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
5508 // Store the SSL error handler.
5509 nestedScrollWebView.setSslErrorHandler(handler);
5511 // Instantiate an SSL certificate error alert dialog.
5512 DialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error, nestedScrollWebView.getWebViewFragmentId());
5514 // Show the SSL certificate error dialog.
5515 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
5520 // Check to see if this is the first page.
5521 if (pageNumber == 0) {
5522 // Set this nested scroll WebView as the current WebView.
5523 currentWebView = nestedScrollWebView;
5525 // Apply the app settings from the shared preferences.
5528 // Load the website if not waiting for Orbot to connect.
5529 if (!waitingForOrbot) {
5530 // Get the intent that started the app.
5531 Intent launchingIntent = getIntent();
5533 // Get the information from the intent.
5534 String launchingIntentAction = launchingIntent.getAction();
5535 Uri launchingIntentUriData = launchingIntent.getData();
5537 // If the intent action is a web search, perform the search.
5538 if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) {
5539 // Create an encoded URL string.
5540 String encodedUrlString;
5542 // Sanitize the search input and convert it to a search.
5544 encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
5545 } catch (UnsupportedEncodingException exception) {
5546 encodedUrlString = "";
5549 // Load the completed search URL.
5550 loadUrl(searchURL + encodedUrlString);
5551 } else if (launchingIntentUriData != null){ // Check to see if the intent contains a new URL.
5552 // Load the URL from the intent.
5553 loadUrl(launchingIntentUriData.toString());
5554 } else { // The is no URL in the intent.
5555 // Select the homepage based on the proxy through Orbot status.
5556 if (proxyThroughOrbot) {
5557 // Load the Tor homepage.
5558 loadUrl(sharedPreferences.getString("tor_homepage", getString(R.string.tor_homepage_default_value)));
5560 // Load the normal homepage.
5561 loadUrl(sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
5565 } else { // This is not the first tab.
5566 // Apply the domain settings.
5567 applyDomainSettings(nestedScrollWebView, url, false, false);
5570 nestedScrollWebView.loadUrl(url, customHeaders);
5572 // Set the focus and display the keyboard if the URL is blank.
5573 if (url.equals("")) {
5574 // Request focus for the URL text box.
5575 urlEditText.requestFocus();
5577 // Create a display keyboard handler.
5578 Handler displayKeyboardHandler = new Handler();
5580 // Create a display keyboard runnable.
5581 Runnable displayKeyboardRunnable = () -> {
5582 // Display the keyboard.
5583 inputMethodManager.showSoftInput(urlEditText, 0);
5586 // Display the keyboard after 100 milliseconds, which leaves enough time for the tab to transition.
5587 displayKeyboardHandler.postDelayed(displayKeyboardRunnable, 100);