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 // Listen for touches on the navigation menu.
460 navigationView.setNavigationItemSelectedListener(this);
462 // Get handles for the navigation menu and the back and forward menu items. The menu is zero-based.
463 Menu navigationMenu = navigationView.getMenu();
464 MenuItem navigationBackMenuItem = navigationMenu.getItem(2);
465 MenuItem navigationForwardMenuItem = navigationMenu.getItem(3);
466 MenuItem navigationHistoryMenuItem = navigationMenu.getItem(4);
467 MenuItem navigationRequestsMenuItem = navigationMenu.getItem(5);
469 // Initialize the web view pager adapter.
470 webViewPagerAdapter = new WebViewPagerAdapter(getSupportFragmentManager());
472 // Set the pager adapter on the web view pager.
473 webViewPager.setAdapter(webViewPagerAdapter);
475 // Store up to 100 tabs in memory.
476 webViewPager.setOffscreenPageLimit(100);
478 // Update the web view pager every time a tab is modified.
479 webViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
481 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
486 public void onPageSelected(int position) {
487 // Close the find on page bar if it is open.
488 closeFindOnPage(null);
490 // Set the current WebView.
491 setCurrentWebView(position);
493 // 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.
494 if (tabLayout.getSelectedTabPosition() != position) {
495 // Create a handler to select the tab.
496 Handler selectTabHandler = new Handler();
498 // Create a runnable to select the tab.
499 Runnable selectTabRunnable = () -> {
500 // Get a handle for the tab.
501 TabLayout.Tab tab = tabLayout.getTabAt(position);
503 // Assert that the tab is not null.
510 // Select the tab layout after 150 milliseconds, which leaves enough time for a new tab to be inflated.
511 selectTabHandler.postDelayed(selectTabRunnable, 150);
516 public void onPageScrollStateChanged(int state) {
521 // Display the View SSL Certificate dialog when the currently selected tab is reselected.
522 tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
524 public void onTabSelected(TabLayout.Tab tab) {
525 // Select the same page in the view pager.
526 webViewPager.setCurrentItem(tab.getPosition());
530 public void onTabUnselected(TabLayout.Tab tab) {
535 public void onTabReselected(TabLayout.Tab tab) {
536 // Instantiate the View SSL Certificate dialog.
537 DialogFragment viewSslCertificateDialogFragment = ViewSslCertificateDialog.displayDialog(currentWebView.getWebViewFragmentId());
539 // Display the View SSL Certificate dialog.
540 viewSslCertificateDialogFragment.show(getSupportFragmentManager(), getString(R.string.view_ssl_certificate));
544 // 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.
545 // The deprecated `getResources().getDrawable()` must be used until the minimum API >= 21 and and `getResources().getColor()` must be used until the minimum API >= 23.
547 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
548 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
549 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
550 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
552 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
553 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
554 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
555 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
558 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
559 launchBookmarksActivityFab.setOnClickListener(v -> {
560 // Get a copy of the favorite icon bitmap.
561 Bitmap favoriteIconBitmap = currentWebView.getFavoriteOrDefaultIcon();
563 // Create a favorite icon byte array output stream.
564 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
566 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
567 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
569 // Convert the favorite icon byte array stream to a byte array.
570 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
572 // Create an intent to launch the bookmarks activity.
573 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
575 // Add the extra information to the intent.
576 bookmarksIntent.putExtra("current_url", currentWebView.getUrl());
577 bookmarksIntent.putExtra("current_title", currentWebView.getTitle());
578 bookmarksIntent.putExtra("current_folder", currentBookmarksFolder);
579 bookmarksIntent.putExtra("favorite_icon_byte_array", favoriteIconByteArray);
582 startActivity(bookmarksIntent);
585 // Set the create new bookmark folder FAB to display an alert dialog.
586 createBookmarkFolderFab.setOnClickListener(v -> {
587 // Create a create bookmark folder dialog.
588 DialogFragment createBookmarkFolderDialog = CreateBookmarkFolderDialog.createBookmarkFolder(currentWebView.getFavoriteOrDefaultIcon());
590 // Show the create bookmark folder dialog.
591 createBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.create_folder));
594 // Set the create new bookmark FAB to display an alert dialog.
595 createBookmarkFab.setOnClickListener(view -> {
596 // Instantiate the create bookmark dialog.
597 DialogFragment createBookmarkDialog = CreateBookmarkDialog.createBookmark(currentWebView.getUrl(), currentWebView.getTitle(), currentWebView.getFavoriteOrDefaultIcon());
599 // Display the create bookmark dialog.
600 createBookmarkDialog.show(getSupportFragmentManager(), getString(R.string.create_bookmark));
603 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
604 findOnPageEditText.addTextChangedListener(new TextWatcher() {
606 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
611 public void onTextChanged(CharSequence s, int start, int before, int count) {
616 public void afterTextChanged(Editable s) {
617 // 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.
618 if (currentWebView != null) {
619 currentWebView.findAllAsync(findOnPageEditText.getText().toString());
624 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
625 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
626 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
627 // Hide the soft keyboard.
628 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
630 // Consume the event.
632 } else { // A different key was pressed.
633 // Do not consume the event.
638 // Implement swipe to refresh.
639 swipeRefreshLayout.setOnRefreshListener(() -> currentWebView.reload());
641 // Store the default progress view offsets for use later in `initializeWebView()`.
642 defaultProgressViewStartOffset = swipeRefreshLayout.getProgressViewStartOffset();
643 defaultProgressViewEndOffset = swipeRefreshLayout.getProgressViewEndOffset();
645 // Set the swipe to refresh color according to the theme.
647 swipeRefreshLayout.setColorSchemeResources(R.color.blue_800);
648 swipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.gray_850);
650 swipeRefreshLayout.setColorSchemeResources(R.color.blue_500);
653 // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
654 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
655 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
657 // Initialize the bookmarks database helper. The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
658 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
660 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
661 currentBookmarksFolder = "";
663 // Load the home folder, which is `""` in the database.
664 loadBookmarksFolder();
666 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
667 // Convert the id from long to int to match the format of the bookmarks database.
668 int databaseID = (int) id;
670 // Get the bookmark cursor for this ID and move it to the first row.
671 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseID);
672 bookmarkCursor.moveToFirst();
674 // Act upon the bookmark according to the type.
675 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
676 // Store the new folder name in `currentBookmarksFolder`.
677 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
679 // Load the new folder.
680 loadBookmarksFolder();
681 } else { // The selected bookmark is not a folder.
682 // Load the bookmark URL.
683 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
685 // Close the bookmarks drawer.
686 drawerLayout.closeDrawer(GravityCompat.END);
689 // Close the `Cursor`.
690 bookmarkCursor.close();
693 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
694 // Convert the database ID from `long` to `int`.
695 int databaseId = (int) id;
697 // Find out if the selected bookmark is a folder.
698 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
701 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
702 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
704 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
705 DialogFragment editBookmarkFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId, currentWebView.getFavoriteOrDefaultIcon());
706 editBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.edit_folder));
708 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
709 DialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId, currentWebView.getFavoriteOrDefaultIcon());
710 editBookmarkDialog.show(getSupportFragmentManager(), getString(R.string.edit_bookmark));
713 // Consume the event.
717 // Get the status bar pixel size.
718 int statusBarResourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
719 int statusBarPixelSize = getResources().getDimensionPixelSize(statusBarResourceId);
721 // Get the resource density.
722 float screenDensity = getResources().getDisplayMetrics().density;
724 // Calculate the drawer header padding. This is used to move the text in the drawer headers below any cutouts.
725 drawerHeaderPaddingLeftAndRight = (int) (15 * screenDensity);
726 drawerHeaderPaddingTop = statusBarPixelSize + (int) (4 * screenDensity);
727 drawerHeaderPaddingBottom = (int) (8 * screenDensity);
729 // The drawer listener is used to update the navigation menu.`
730 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
732 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
736 public void onDrawerOpened(@NonNull View drawerView) {
740 public void onDrawerClosed(@NonNull View drawerView) {
744 public void onDrawerStateChanged(int newState) {
745 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // A drawer is opening or closing.
746 // Get handles for the drawer headers.
747 TextView navigationHeaderTextView = findViewById(R.id.navigationText);
748 TextView bookmarksHeaderTextView = findViewById(R.id.bookmarks_title_textview);
750 // 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.
751 if (navigationHeaderTextView != null) {
752 navigationHeaderTextView.setPadding(drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingTop, drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingBottom);
755 // 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.
756 if (bookmarksHeaderTextView != null) {
757 bookmarksHeaderTextView.setPadding(drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingTop, drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingBottom);
760 // Update the navigation menu items.
761 navigationBackMenuItem.setEnabled(currentWebView.canGoBack());
762 navigationForwardMenuItem.setEnabled(currentWebView.canGoForward());
763 navigationHistoryMenuItem.setEnabled((currentWebView.canGoBack() || currentWebView.canGoForward()));
764 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
766 // Hide the keyboard (if displayed).
767 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
769 // 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.
770 urlEditText.clearFocus();
771 currentWebView.clearFocus();
776 // Create the hamburger icon at the start of the AppBar.
777 actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
779 // 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).
780 customHeaders.put("X-Requested-With", "");
782 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
783 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
785 // Inflate a bare WebView to get the default user agent. It is not used to render content on the screen.
786 @SuppressLint("InflateParams") View webViewLayout = getLayoutInflater().inflate(R.layout.bare_webview, null, false);
788 // Get a handle for the WebView.
789 WebView bareWebView = webViewLayout.findViewById(R.id.bare_webview);
791 // Store the default user agent.
792 webViewDefaultUserAgent = bareWebView.getSettings().getUserAgentString();
794 // Destroy the bare WebView.
795 bareWebView.destroy();
797 // Populate the blocklists.
798 new PopulateBlocklists(this, this).execute();
802 protected void onNewIntent(Intent intent) {
803 // Get the information from the intent.
804 String intentAction = intent.getAction();
805 Uri intentUriData = intent.getData();
807 // Determine if this is a web search.
808 boolean isWebSearch = ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH));
810 // 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.
811 if (intentUriData != null || isWebSearch) {
812 // Get the shared preferences.
813 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
815 // Create a URL string.
818 // If the intent action is a web search, perform the search.
820 // Create an encoded URL string.
821 String encodedUrlString;
823 // Sanitize the search input and convert it to a search.
825 encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
826 } catch (UnsupportedEncodingException exception) {
827 encodedUrlString = "";
830 // Add the base search URL.
831 url = searchURL + encodedUrlString;
832 } else { // The intent should contain a URL.
833 // Set the intent data as the URL.
834 url = intentUriData.toString();
837 // Add a new tab if specified in the preferences.
838 if (sharedPreferences.getBoolean("open_intents_in_new_tab", true)) { // Load the URL in a new tab.
839 // Set the loading new intent flag.
840 loadingNewIntent = true;
844 } else { // Load the URL in the current tab.
849 // Get a handle for the drawer layout.
850 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
852 // Close the navigation drawer if it is open.
853 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
854 drawerLayout.closeDrawer(GravityCompat.START);
857 // Close the bookmarks drawer if it is open.
858 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
859 drawerLayout.closeDrawer(GravityCompat.END);
865 public void onRestart() {
866 // Run the default commands.
869 // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
870 if (proxyThroughOrbot) {
871 // Request Orbot to start. If Orbot is already running no hard will be caused by this request.
872 Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
874 // Send the intent to the Orbot package.
875 orbotIntent.setPackage("org.torproject.android");
878 sendBroadcast(orbotIntent);
881 // Apply the app settings if returning from the Settings activity.
882 if (reapplyAppSettingsOnRestart) {
883 // Reset the reapply app settings on restart tracker.
884 reapplyAppSettingsOnRestart = false;
886 // Apply the app settings.
890 // Apply the domain settings if returning from the settings or domains activity.
891 if (reapplyDomainSettingsOnRestart) {
892 // Reset the reapply domain settings on restart tracker.
893 reapplyDomainSettingsOnRestart = false;
895 // Reapply the domain settings for each tab.
896 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
897 // Get the WebView tab fragment.
898 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
900 // Get the fragment view.
901 View fragmentView = webViewTabFragment.getView();
903 // Only reload the WebViews if they exist.
904 if (fragmentView != null) {
905 // Get the nested scroll WebView from the tab fragment.
906 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
908 // Reset the current domain name so the domain settings will be reapplied.
909 nestedScrollWebView.resetCurrentDomainName();
911 // Reapply the domain settings if the URL is not null, which can happen if an empty tab is active when returning from settings.
912 if (nestedScrollWebView.getUrl() != null) {
913 applyDomainSettings(nestedScrollWebView, nestedScrollWebView.getUrl(), false, true);
919 // Load the URL on restart (used when loading a bookmark).
920 if (loadUrlOnRestart) {
921 // Load the specified URL.
922 loadUrl(urlToLoadOnRestart);
924 // Reset the load on restart tracker.
925 loadUrlOnRestart = false;
928 // Update the bookmarks drawer if returning from the Bookmarks activity.
929 if (restartFromBookmarksActivity) {
930 // Get a handle for the drawer layout.
931 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
933 // Close the bookmarks drawer.
934 drawerLayout.closeDrawer(GravityCompat.END);
936 // Reload the bookmarks drawer.
937 loadBookmarksFolder();
939 // Reset `restartFromBookmarksActivity`.
940 restartFromBookmarksActivity = false;
943 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
944 updatePrivacyIcons(true);
947 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
949 public void onResume() {
950 // Run the default commands.
953 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
954 // Get the WebView tab fragment.
955 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
957 // Get the fragment view.
958 View fragmentView = webViewTabFragment.getView();
960 // Only resume the WebViews if they exist (they won't when the app is first created).
961 if (fragmentView != null) {
962 // Get the nested scroll WebView from the tab fragment.
963 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
965 // Resume the nested scroll WebView JavaScript timers.
966 nestedScrollWebView.resumeTimers();
968 // Resume the nested scroll WebView.
969 nestedScrollWebView.onResume();
973 // Display a message to the user if waiting for Orbot.
974 if (waitingForOrbot && !orbotStatus.equals("ON")) {
975 // Disable the wide view port so that the waiting for Orbot text is displayed correctly.
976 currentWebView.getSettings().setUseWideViewPort(false);
978 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
979 currentWebView.loadData("<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>", "text/html", null);
982 if (displayingFullScreenVideo || inFullScreenBrowsingMode) {
983 // Get a handle for the root frame layouts.
984 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
986 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
987 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
989 /* Hide the system bars.
990 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
991 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
992 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
993 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
995 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
996 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
997 } else if (BuildConfig.FLAVOR.contentEquals("free")) { // Resume the adView for the free flavor.
999 AdHelper.resumeAd(findViewById(R.id.adview));
1004 public void onPause() {
1005 // Run the default commands.
1008 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
1009 // Get the WebView tab fragment.
1010 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
1012 // Get the fragment view.
1013 View fragmentView = webViewTabFragment.getView();
1015 // Only pause the WebViews if they exist (they won't when the app is first created).
1016 if (fragmentView != null) {
1017 // Get the nested scroll WebView from the tab fragment.
1018 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
1020 // Pause the nested scroll WebView.
1021 nestedScrollWebView.onPause();
1023 // Pause the nested scroll WebView JavaScript timers.
1024 nestedScrollWebView.pauseTimers();
1028 // Pause the ad or it will continue to consume resources in the background on the free flavor.
1029 if (BuildConfig.FLAVOR.contentEquals("free")) {
1031 AdHelper.pauseAd(findViewById(R.id.adview));
1036 public void onDestroy() {
1037 // Unregister the Orbot status broadcast receiver.
1038 this.unregisterReceiver(orbotStatusBroadcastReceiver);
1040 // Close the bookmarks cursor and database.
1041 bookmarksCursor.close();
1042 bookmarksDatabaseHelper.close();
1044 // Run the default commands.
1049 public boolean onCreateOptionsMenu(Menu menu) {
1050 // Inflate the menu. This adds items to the action bar if it is present.
1051 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1053 // Store a handle for the options menu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons()`.
1056 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1057 updatePrivacyIcons(false);
1059 // Get handles for the menu items.
1060 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1061 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1062 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1063 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
1064 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
1065 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1066 MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
1068 // Only display third-party cookies if API >= 21
1069 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1071 // Only display the form data menu items if the API < 26.
1072 toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1073 clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1075 // Disable the clear form data menu item if the API >= 26 so that the status of the main Clear Data is calculated correctly.
1076 clearFormDataMenuItem.setEnabled(Build.VERSION.SDK_INT < 26);
1078 // Only show Ad Consent if this is the free flavor.
1079 adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
1081 // Get the shared preferences.
1082 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1084 // Get the dark theme and app bar preferences..
1085 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
1086 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
1088 // 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.
1089 if (displayAdditionalAppBarIcons) {
1090 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1091 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1092 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
1093 } else { //Do not display the additional icons.
1094 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1095 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1096 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1099 // Replace Refresh with Stop if a URL is already loading.
1100 if (currentWebView != null && currentWebView.getProgress() != 100) {
1102 refreshMenuItem.setTitle(R.string.stop);
1104 // If the icon is displayed in the AppBar, set it according to the theme.
1105 if (displayAdditionalAppBarIcons) {
1107 refreshMenuItem.setIcon(R.drawable.close_dark);
1109 refreshMenuItem.setIcon(R.drawable.close_light);
1118 public boolean onPrepareOptionsMenu(Menu menu) {
1119 // Get handles for the menu items.
1120 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
1121 MenuItem firstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1122 MenuItem thirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1123 MenuItem domStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1124 MenuItem saveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
1125 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
1126 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1127 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1128 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
1129 MenuItem blocklistsMenuItem = menu.findItem(R.id.blocklists);
1130 MenuItem easyListMenuItem = menu.findItem(R.id.easylist);
1131 MenuItem easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
1132 MenuItem fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
1133 MenuItem fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
1134 MenuItem ultraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
1135 MenuItem blockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
1136 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1137 MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
1138 MenuItem wideViewportMenuItem = menu.findItem(R.id.wide_viewport);
1139 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1140 MenuItem nightModeMenuItem = menu.findItem(R.id.night_mode);
1141 MenuItem proxyThroughOrbotMenuItem = menu.findItem(R.id.proxy_through_orbot);
1143 // Get a handle for the cookie manager.
1144 CookieManager cookieManager = CookieManager.getInstance();
1146 // Initialize the current user agent string and the font size.
1147 String currentUserAgent = getString(R.string.user_agent_privacy_browser);
1150 // 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.
1151 if (currentWebView != null) {
1152 // Set the add or edit domain text.
1153 if (currentWebView.getDomainSettingsApplied()) {
1154 addOrEditDomain.setTitle(R.string.edit_domain_settings);
1156 addOrEditDomain.setTitle(R.string.add_domain_settings);
1159 // Get the current user agent from the WebView.
1160 currentUserAgent = currentWebView.getSettings().getUserAgentString();
1162 // Get the current font size from the
1163 fontSize = currentWebView.getSettings().getTextZoom();
1165 // Set the status of the menu item checkboxes.
1166 domStorageMenuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1167 saveFormDataMenuItem.setChecked(currentWebView.getSettings().getSaveFormData()); // Form data can be removed once the minimum API >= 26.
1168 easyListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST));
1169 easyPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY));
1170 fanboysAnnoyanceListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1171 fanboysSocialBlockingListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1172 ultraPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY));
1173 blockAllThirdPartyRequestsMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1174 swipeToRefreshMenuItem.setChecked(currentWebView.getSwipeToRefresh());
1175 wideViewportMenuItem.setChecked(currentWebView.getSettings().getUseWideViewPort());
1176 displayImagesMenuItem.setChecked(currentWebView.getSettings().getLoadsImagesAutomatically());
1177 nightModeMenuItem.setChecked(currentWebView.getNightMode());
1179 // Initialize the display names for the blocklists with the number of blocked requests.
1180 blocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
1181 easyListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASY_LIST) + " - " + getString(R.string.easylist));
1182 easyPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASY_PRIVACY) + " - " + getString(R.string.easyprivacy));
1183 fanboysAnnoyanceListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " + getString(R.string.fanboys_annoyance_list));
1184 fanboysSocialBlockingListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " + getString(R.string.fanboys_social_blocking_list));
1185 ultraPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRA_PRIVACY) + " - " + getString(R.string.ultraprivacy));
1186 blockAllThirdPartyRequestsMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " + getString(R.string.block_all_third_party_requests));
1188 // Only modify third-party cookies if the API >= 21.
1189 if (Build.VERSION.SDK_INT >= 21) {
1190 // Set the status of the third-party cookies checkbox.
1191 thirdPartyCookiesMenuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
1193 // Enable third-party cookies if first-party cookies are enabled.
1194 thirdPartyCookiesMenuItem.setEnabled(cookieManager.acceptCookie());
1197 // Enable DOM Storage if JavaScript is enabled.
1198 domStorageMenuItem.setEnabled(currentWebView.getSettings().getJavaScriptEnabled());
1201 // Set the status of the menu item checkboxes.
1202 firstPartyCookiesMenuItem.setChecked(cookieManager.acceptCookie());
1203 proxyThroughOrbotMenuItem.setChecked(proxyThroughOrbot);
1205 // Enable Clear Cookies if there are any.
1206 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1208 // 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`.
1209 String privateDataDirectoryString = getApplicationInfo().dataDir;
1211 // Get a count of the number of files in the Local Storage directory.
1212 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1213 int localStorageDirectoryNumberOfFiles = 0;
1214 if (localStorageDirectory.exists()) {
1215 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1218 // Get a count of the number of files in the IndexedDB directory.
1219 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1220 int indexedDBDirectoryNumberOfFiles = 0;
1221 if (indexedDBDirectory.exists()) {
1222 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1225 // Enable Clear DOM Storage if there is any.
1226 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1228 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
1229 if (Build.VERSION.SDK_INT < 26) {
1230 // Get the WebView database.
1231 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1233 // Enable the clear form data menu item if there is anything to clear.
1234 clearFormDataMenuItem.setEnabled(webViewDatabase.hasFormData());
1237 // Enable Clear Data if any of the submenu items are enabled.
1238 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
1240 // Disable Fanboy's Social Blocking List menu item if Fanboy's Annoyance List is checked.
1241 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListMenuItem.isChecked());
1243 // Select the current user agent menu item. A switch statement cannot be used because the user agents are not compile time constants.
1244 if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) { // Privacy Browser.
1245 menu.findItem(R.id.user_agent_privacy_browser).setChecked(true);
1246 } else if (currentUserAgent.equals(webViewDefaultUserAgent)) { // WebView Default.
1247 menu.findItem(R.id.user_agent_webview_default).setChecked(true);
1248 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) { // Firefox on Android.
1249 menu.findItem(R.id.user_agent_firefox_on_android).setChecked(true);
1250 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) { // Chrome on Android.
1251 menu.findItem(R.id.user_agent_chrome_on_android).setChecked(true);
1252 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) { // Safari on iOS.
1253 menu.findItem(R.id.user_agent_safari_on_ios).setChecked(true);
1254 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) { // Firefox on Linux.
1255 menu.findItem(R.id.user_agent_firefox_on_linux).setChecked(true);
1256 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) { // Chromium on Linux.
1257 menu.findItem(R.id.user_agent_chromium_on_linux).setChecked(true);
1258 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) { // Firefox on Windows.
1259 menu.findItem(R.id.user_agent_firefox_on_windows).setChecked(true);
1260 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) { // Chrome on Windows.
1261 menu.findItem(R.id.user_agent_chrome_on_windows).setChecked(true);
1262 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) { // Edge on Windows.
1263 menu.findItem(R.id.user_agent_edge_on_windows).setChecked(true);
1264 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) { // Internet Explorer on Windows.
1265 menu.findItem(R.id.user_agent_internet_explorer_on_windows).setChecked(true);
1266 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) { // Safari on macOS.
1267 menu.findItem(R.id.user_agent_safari_on_macos).setChecked(true);
1268 } else { // Custom user agent.
1269 menu.findItem(R.id.user_agent_custom).setChecked(true);
1272 // Instantiate the font size title and the selected font size menu item.
1273 String fontSizeTitle;
1274 MenuItem selectedFontSizeMenuItem;
1276 // Prepare the font size title and current size menu item.
1279 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
1280 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1284 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
1285 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1289 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
1290 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1294 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1295 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1299 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
1300 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1304 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
1305 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1309 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
1310 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1314 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
1315 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1319 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1320 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1324 // Set the font size title and select the current size menu item.
1325 fontSizeMenuItem.setTitle(fontSizeTitle);
1326 selectedFontSizeMenuItem.setChecked(true);
1328 // Run all the other default commands.
1329 super.onPrepareOptionsMenu(menu);
1331 // Display the menu.
1336 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1337 @SuppressLint("SetJavaScriptEnabled")
1338 public boolean onOptionsItemSelected(MenuItem menuItem) {
1339 // Reenter full screen browsing mode if it was interrupted by the options menu. <https://redmine.stoutner.com/issues/389>
1340 if (inFullScreenBrowsingMode) {
1341 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
1342 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1344 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
1346 /* Hide the system bars.
1347 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1348 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
1349 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1350 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1352 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
1353 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1356 // Get the selected menu item ID.
1357 int menuItemId = menuItem.getItemId();
1359 // Get a handle for the shared preferences.
1360 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1362 // Get a handle for the cookie manager.
1363 CookieManager cookieManager = CookieManager.getInstance();
1365 // Run the commands that correlate to the selected menu item.
1366 switch (menuItemId) {
1367 case R.id.toggle_javascript:
1368 // Toggle the JavaScript status.
1369 currentWebView.getSettings().setJavaScriptEnabled(!currentWebView.getSettings().getJavaScriptEnabled());
1371 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1372 updatePrivacyIcons(true);
1374 // Display a `Snackbar`.
1375 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScrip is enabled.
1376 Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1377 } else if (cookieManager.acceptCookie()) { // JavaScript is disabled, but first-party cookies are enabled.
1378 Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1379 } else { // Privacy mode.
1380 Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1383 // Reload the current WebView.
1384 currentWebView.reload();
1387 case R.id.add_or_edit_domain:
1388 if (currentWebView.getDomainSettingsApplied()) { // Edit the current domain settings.
1389 // Reapply the domain settings on returning to `MainWebViewActivity`.
1390 reapplyDomainSettingsOnRestart = true;
1392 // Create an intent to launch the domains activity.
1393 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1395 // Add the extra information to the intent.
1396 domainsIntent.putExtra("load_domain", currentWebView.getDomainSettingsDatabaseId());
1397 domainsIntent.putExtra("close_on_back", true);
1398 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1400 // Get the current certificate.
1401 SslCertificate sslCertificate = currentWebView.getCertificate();
1403 // Check to see if the SSL certificate is populated.
1404 if (sslCertificate != null) {
1405 // Extract the certificate to strings.
1406 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1407 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1408 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1409 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1410 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1411 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1412 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1413 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1415 // Add the certificate to the intent.
1416 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1417 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1418 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1419 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1420 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1421 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1422 domainsIntent.putExtra("ssl_start_date", startDateLong);
1423 domainsIntent.putExtra("ssl_end_date", endDateLong);
1426 // Check to see if the current IP addresses have been received.
1427 if (currentWebView.hasCurrentIpAddresses()) {
1428 // Add the current IP addresses to the intent.
1429 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1433 startActivity(domainsIntent);
1434 } else { // Add a new domain.
1435 // Apply the new domain settings on returning to `MainWebViewActivity`.
1436 reapplyDomainSettingsOnRestart = true;
1438 // Get the current domain
1439 Uri currentUri = Uri.parse(currentWebView.getUrl());
1440 String currentDomain = currentUri.getHost();
1442 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1443 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1445 // Create the domain and store the database ID.
1446 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1448 // Create an intent to launch the domains activity.
1449 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1451 // Add the extra information to the intent.
1452 domainsIntent.putExtra("load_domain", newDomainDatabaseId);
1453 domainsIntent.putExtra("close_on_back", true);
1454 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1456 // Get the current certificate.
1457 SslCertificate sslCertificate = currentWebView.getCertificate();
1459 // Check to see if the SSL certificate is populated.
1460 if (sslCertificate != null) {
1461 // Extract the certificate to strings.
1462 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1463 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1464 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1465 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1466 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1467 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1468 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1469 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1471 // Add the certificate to the intent.
1472 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1473 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1474 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1475 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1476 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1477 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1478 domainsIntent.putExtra("ssl_start_date", startDateLong);
1479 domainsIntent.putExtra("ssl_end_date", endDateLong);
1482 // Check to see if the current IP addresses have been received.
1483 if (currentWebView.hasCurrentIpAddresses()) {
1484 // Add the current IP addresses to the intent.
1485 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1489 startActivity(domainsIntent);
1493 case R.id.toggle_first_party_cookies:
1494 // Switch the first-party cookie status.
1495 cookieManager.setAcceptCookie(!cookieManager.acceptCookie());
1497 // Store the first-party cookie status.
1498 currentWebView.setAcceptFirstPartyCookies(cookieManager.acceptCookie());
1500 // Update the menu checkbox.
1501 menuItem.setChecked(cookieManager.acceptCookie());
1503 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1504 updatePrivacyIcons(true);
1506 // Display a snackbar.
1507 if (cookieManager.acceptCookie()) { // First-party cookies are enabled.
1508 Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1509 } else if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is still enabled.
1510 Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1511 } else { // Privacy mode.
1512 Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1515 // Reload the current WebView.
1516 currentWebView.reload();
1519 case R.id.toggle_third_party_cookies:
1520 if (Build.VERSION.SDK_INT >= 21) {
1521 // Switch the status of thirdPartyCookiesEnabled.
1522 cookieManager.setAcceptThirdPartyCookies(currentWebView, !cookieManager.acceptThirdPartyCookies(currentWebView));
1524 // Update the menu checkbox.
1525 menuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
1527 // Display a snackbar.
1528 if (cookieManager.acceptThirdPartyCookies(currentWebView)) {
1529 Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1531 Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1534 // Reload the current WebView.
1535 currentWebView.reload();
1536 } // Else do nothing because SDK < 21.
1539 case R.id.toggle_dom_storage:
1540 // Toggle the status of domStorageEnabled.
1541 currentWebView.getSettings().setDomStorageEnabled(!currentWebView.getSettings().getDomStorageEnabled());
1543 // Update the menu checkbox.
1544 menuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1546 // Update the privacy icon. `true` refreshes the app bar icons.
1547 updatePrivacyIcons(true);
1549 // Display a snackbar.
1550 if (currentWebView.getSettings().getDomStorageEnabled()) {
1551 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1553 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1556 // Reload the current WebView.
1557 currentWebView.reload();
1560 // Form data can be removed once the minimum API >= 26.
1561 case R.id.toggle_save_form_data:
1562 // Switch the status of saveFormDataEnabled.
1563 currentWebView.getSettings().setSaveFormData(!currentWebView.getSettings().getSaveFormData());
1565 // Update the menu checkbox.
1566 menuItem.setChecked(currentWebView.getSettings().getSaveFormData());
1568 // Display a snackbar.
1569 if (currentWebView.getSettings().getSaveFormData()) {
1570 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1572 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1575 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1576 updatePrivacyIcons(true);
1578 // Reload the current WebView.
1579 currentWebView.reload();
1582 case R.id.clear_cookies:
1583 Snackbar.make(findViewById(R.id.webviewpager), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1584 .setAction(R.string.undo, v -> {
1585 // Do nothing because everything will be handled by `onDismissed()` below.
1587 .addCallback(new Snackbar.Callback() {
1588 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1590 public void onDismissed(Snackbar snackbar, int event) {
1591 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1592 // Delete the cookies, which command varies by SDK.
1593 if (Build.VERSION.SDK_INT < 21) {
1594 cookieManager.removeAllCookie();
1596 cookieManager.removeAllCookies(null);
1604 case R.id.clear_dom_storage:
1605 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1606 .setAction(R.string.undo, v -> {
1607 // Do nothing because everything will be handled by `onDismissed()` below.
1609 .addCallback(new Snackbar.Callback() {
1610 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1612 public void onDismissed(Snackbar snackbar, int event) {
1613 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1614 // Delete the DOM Storage.
1615 WebStorage webStorage = WebStorage.getInstance();
1616 webStorage.deleteAllData();
1618 // Initialize a handler to manually delete the DOM storage files and directories.
1619 Handler deleteDomStorageHandler = new Handler();
1621 // Setup a runnable to manually delete the DOM storage files and directories.
1622 Runnable deleteDomStorageRunnable = () -> {
1624 // Get a handle for the runtime.
1625 Runtime runtime = Runtime.getRuntime();
1627 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
1628 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
1629 String privateDataDirectoryString = getApplicationInfo().dataDir;
1631 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1632 Process deleteLocalStorageProcess = runtime.exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1634 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1635 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1636 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1637 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1638 Process deleteDatabasesProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1640 // Wait for the processes to finish.
1641 deleteLocalStorageProcess.waitFor();
1642 deleteIndexProcess.waitFor();
1643 deleteQuotaManagerProcess.waitFor();
1644 deleteQuotaManagerJournalProcess.waitFor();
1645 deleteDatabasesProcess.waitFor();
1646 } catch (Exception exception) {
1647 // Do nothing if an error is thrown.
1651 // Manually delete the DOM storage files after 200 milliseconds.
1652 deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200);
1659 // Form data can be remove once the minimum API >= 26.
1660 case R.id.clear_form_data:
1661 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1662 .setAction(R.string.undo, v -> {
1663 // Do nothing because everything will be handled by `onDismissed()` below.
1665 .addCallback(new Snackbar.Callback() {
1666 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1668 public void onDismissed(Snackbar snackbar, int event) {
1669 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1670 // Delete the form data.
1671 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1672 mainWebViewDatabase.clearFormData();
1680 // Toggle the EasyList status.
1681 currentWebView.enableBlocklist(NestedScrollWebView.EASY_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST));
1683 // Update the menu checkbox.
1684 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST));
1686 // Reload the current WebView.
1687 currentWebView.reload();
1690 case R.id.easyprivacy:
1691 // Toggle the EasyPrivacy status.
1692 currentWebView.enableBlocklist(NestedScrollWebView.EASY_PRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY));
1694 // Update the menu checkbox.
1695 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY));
1697 // Reload the current WebView.
1698 currentWebView.reload();
1701 case R.id.fanboys_annoyance_list:
1702 // Toggle Fanboy's Annoyance List status.
1703 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1705 // Update the menu checkbox.
1706 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1708 // Update the staus of Fanboy's Social Blocking List.
1709 MenuItem fanboysSocialBlockingListMenuItem = optionsMenu.findItem(R.id.fanboys_social_blocking_list);
1710 fanboysSocialBlockingListMenuItem.setEnabled(!currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1712 // Reload the current WebView.
1713 currentWebView.reload();
1716 case R.id.fanboys_social_blocking_list:
1717 // Toggle Fanboy's Social Blocking List status.
1718 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1720 // Update the menu checkbox.
1721 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1723 // Reload the current WebView.
1724 currentWebView.reload();
1727 case R.id.ultraprivacy:
1728 // Toggle the UltraPrivacy status.
1729 currentWebView.enableBlocklist(NestedScrollWebView.ULTRA_PRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY));
1731 // Update the menu checkbox.
1732 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY));
1734 // Reload the current WebView.
1735 currentWebView.reload();
1738 case R.id.block_all_third_party_requests:
1739 //Toggle the third-party requests blocker status.
1740 currentWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, !currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1742 // Update the menu checkbox.
1743 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1745 // Reload the current WebView.
1746 currentWebView.reload();
1749 case R.id.user_agent_privacy_browser:
1750 // Update the user agent.
1751 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
1753 // Reload the current WebView.
1754 currentWebView.reload();
1757 case R.id.user_agent_webview_default:
1758 // Update the user agent.
1759 currentWebView.getSettings().setUserAgentString("");
1761 // Reload the current WebView.
1762 currentWebView.reload();
1765 case R.id.user_agent_firefox_on_android:
1766 // Update the user agent.
1767 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
1769 // Reload the current WebView.
1770 currentWebView.reload();
1773 case R.id.user_agent_chrome_on_android:
1774 // Update the user agent.
1775 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
1777 // Reload the current WebView.
1778 currentWebView.reload();
1781 case R.id.user_agent_safari_on_ios:
1782 // Update the user agent.
1783 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
1785 // Reload the current WebView.
1786 currentWebView.reload();
1789 case R.id.user_agent_firefox_on_linux:
1790 // Update the user agent.
1791 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
1793 // Reload the current WebView.
1794 currentWebView.reload();
1797 case R.id.user_agent_chromium_on_linux:
1798 // Update the user agent.
1799 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
1801 // Reload the current WebView.
1802 currentWebView.reload();
1805 case R.id.user_agent_firefox_on_windows:
1806 // Update the user agent.
1807 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
1809 // Reload the current WebView.
1810 currentWebView.reload();
1813 case R.id.user_agent_chrome_on_windows:
1814 // Update the user agent.
1815 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
1817 // Reload the current WebView.
1818 currentWebView.reload();
1821 case R.id.user_agent_edge_on_windows:
1822 // Update the user agent.
1823 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
1825 // Reload the current WebView.
1826 currentWebView.reload();
1829 case R.id.user_agent_internet_explorer_on_windows:
1830 // Update the user agent.
1831 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
1833 // Reload the current WebView.
1834 currentWebView.reload();
1837 case R.id.user_agent_safari_on_macos:
1838 // Update the user agent.
1839 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
1841 // Reload the current WebView.
1842 currentWebView.reload();
1845 case R.id.user_agent_custom:
1846 // Update the user agent.
1847 currentWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
1849 // Reload the current WebView.
1850 currentWebView.reload();
1853 case R.id.font_size_twenty_five_percent:
1854 currentWebView.getSettings().setTextZoom(25);
1857 case R.id.font_size_fifty_percent:
1858 currentWebView.getSettings().setTextZoom(50);
1861 case R.id.font_size_seventy_five_percent:
1862 currentWebView.getSettings().setTextZoom(75);
1865 case R.id.font_size_one_hundred_percent:
1866 currentWebView.getSettings().setTextZoom(100);
1869 case R.id.font_size_one_hundred_twenty_five_percent:
1870 currentWebView.getSettings().setTextZoom(125);
1873 case R.id.font_size_one_hundred_fifty_percent:
1874 currentWebView.getSettings().setTextZoom(150);
1877 case R.id.font_size_one_hundred_seventy_five_percent:
1878 currentWebView.getSettings().setTextZoom(175);
1881 case R.id.font_size_two_hundred_percent:
1882 currentWebView.getSettings().setTextZoom(200);
1885 case R.id.swipe_to_refresh:
1886 // Toggle the stored status of swipe to refresh.
1887 currentWebView.setSwipeToRefresh(!currentWebView.getSwipeToRefresh());
1889 // Get a handle for the swipe refresh layout.
1890 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
1892 // Update the swipe refresh layout.
1893 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
1894 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
1895 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
1896 } else { // Swipe to refresh is disabled.
1897 // Disable the swipe refresh layout.
1898 swipeRefreshLayout.setEnabled(false);
1902 case R.id.wide_viewport:
1903 // Toggle the viewport.
1904 currentWebView.getSettings().setUseWideViewPort(!currentWebView.getSettings().getUseWideViewPort());
1907 case R.id.display_images:
1908 if (currentWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1909 // Disable loading of images.
1910 currentWebView.getSettings().setLoadsImagesAutomatically(false);
1912 // Reload the website to remove existing images.
1913 currentWebView.reload();
1914 } else { // Images are not currently loaded automatically.
1915 // Enable loading of images. Missing images will be loaded without the need for a reload.
1916 currentWebView.getSettings().setLoadsImagesAutomatically(true);
1920 case R.id.night_mode:
1921 // Toggle night mode.
1922 currentWebView.setNightMode(!currentWebView.getNightMode());
1924 // Enable or disable JavaScript according to night mode, the global preference, and any domain settings.
1925 if (currentWebView.getNightMode()) { // Night mode is enabled, which requires JavaScript.
1926 // Enable JavaScript.
1927 currentWebView.getSettings().setJavaScriptEnabled(true);
1928 } else if (currentWebView.getDomainSettingsApplied()) { // Night mode is disabled and domain settings are applied. Set JavaScript according to the domain settings.
1929 // Apply the JavaScript preference that was stored the last time domain settings were loaded.
1930 currentWebView.getSettings().setJavaScriptEnabled(currentWebView.getDomainSettingsJavaScriptEnabled());
1931 } else { // Night mode is disabled and domain settings are not applied. Set JavaScript according to the global preference.
1932 // Apply the JavaScript preference.
1933 currentWebView.getSettings().setJavaScriptEnabled(sharedPreferences.getBoolean("javascript", false));
1936 // Update the privacy icons.
1937 updatePrivacyIcons(false);
1939 // Reload the website.
1940 currentWebView.reload();
1943 case R.id.find_on_page:
1944 // Get a handle for the views.
1945 Toolbar toolbar = findViewById(R.id.toolbar);
1946 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
1947 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
1949 // Set the minimum height of the find on page linear layout to match the toolbar.
1950 findOnPageLinearLayout.setMinimumHeight(toolbar.getHeight());
1952 // Hide the toolbar.
1953 toolbar.setVisibility(View.GONE);
1955 // Show the find on page linear layout.
1956 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1958 // Display the keyboard. The app must wait 200 ms before running the command to work around a bug in Android.
1959 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1960 findOnPageEditText.postDelayed(() -> {
1961 // Set the focus on `findOnPageEditText`.
1962 findOnPageEditText.requestFocus();
1964 // Get a handle for the input method manager.
1965 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1967 // Remove the lint warning below that the input method manager might be null.
1968 assert inputMethodManager != null;
1970 // Display the keyboard. `0` sets no input flags.
1971 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1976 // Get a print manager instance.
1977 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1979 // Remove the lint error below that print manager might be null.
1980 assert printManager != null;
1982 // Create a print document adapter from the current WebView.
1983 PrintDocumentAdapter printDocumentAdapter = currentWebView.createPrintDocumentAdapter();
1985 // Print the document.
1986 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1989 case R.id.add_to_homescreen:
1990 // Instantiate the create home screen shortcut dialog.
1991 DialogFragment createHomeScreenShortcutDialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView.getTitle(), currentWebView.getUrl(),
1992 currentWebView.getFavoriteOrDefaultIcon());
1994 // Show the create home screen shortcut dialog.
1995 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
1998 case R.id.view_source:
1999 // Create an intent to launch the view source activity.
2000 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
2002 // Add the variables to the intent.
2003 viewSourceIntent.putExtra("user_agent", currentWebView.getSettings().getUserAgentString());
2004 viewSourceIntent.putExtra("current_url", currentWebView.getUrl());
2007 startActivity(viewSourceIntent);
2010 case R.id.share_url:
2011 // Setup the share string.
2012 String shareString = currentWebView.getTitle() + " – " + currentWebView.getUrl();
2014 // Create the share intent.
2015 Intent shareIntent = new Intent(Intent.ACTION_SEND);
2016 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
2017 shareIntent.setType("text/plain");
2020 startActivity(Intent.createChooser(shareIntent, getString(R.string.share_url)));
2023 case R.id.open_with_app:
2024 openWithApp(currentWebView.getUrl());
2027 case R.id.open_with_browser:
2028 openWithBrowser(currentWebView.getUrl());
2031 case R.id.proxy_through_orbot:
2032 // Toggle the proxy through Orbot variable.
2033 proxyThroughOrbot = !proxyThroughOrbot;
2035 // Apply the proxy through Orbot settings.
2036 applyProxyThroughOrbot(true);
2040 if (menuItem.getTitle().equals(getString(R.string.refresh))) { // The refresh button was pushed.
2041 // Reload the current WebView.
2042 currentWebView.reload();
2043 } else { // The stop button was pushed.
2044 // Stop the loading of the WebView.
2045 currentWebView.stopLoading();
2049 case R.id.ad_consent:
2050 // Display the ad consent dialog.
2051 DialogFragment adConsentDialogFragment = new AdConsentDialog();
2052 adConsentDialogFragment.show(getSupportFragmentManager(), getString(R.string.ad_consent));
2056 // Don't consume the event.
2057 return super.onOptionsItemSelected(menuItem);
2061 // removeAllCookies is deprecated, but it is required for API < 21.
2063 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2064 // Get the menu item ID.
2065 int menuItemId = menuItem.getItemId();
2067 // Get a handle for the shared preferences.
2068 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2070 // Run the commands that correspond to the selected menu item.
2071 switch (menuItemId) {
2072 case R.id.clear_and_exit:
2073 // Clear and exit Privacy Browser.
2078 // Select the homepage based on the proxy through Orbot status.
2079 if (proxyThroughOrbot) {
2080 // Load the Tor homepage.
2081 loadUrl(sharedPreferences.getString("tor_homepage", getString(R.string.tor_homepage_default_value)));
2083 // Load the normal homepage.
2084 loadUrl(sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
2089 if (currentWebView.canGoBack()) {
2090 // Reset the current domain name so that navigation works if third-party requests are blocked.
2091 currentWebView.resetCurrentDomainName();
2093 // Set navigating history so that the domain settings are applied when the new URL is loaded.
2094 currentWebView.setNavigatingHistory(true);
2096 // Load the previous website in the history.
2097 currentWebView.goBack();
2102 if (currentWebView.canGoForward()) {
2103 // Reset the current domain name so that navigation works if third-party requests are blocked.
2104 currentWebView.resetCurrentDomainName();
2106 // Set navigating history so that the domain settings are applied when the new URL is loaded.
2107 currentWebView.setNavigatingHistory(true);
2109 // Load the next website in the history.
2110 currentWebView.goForward();
2115 // Instantiate the URL history dialog.
2116 DialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(currentWebView.getWebViewFragmentId());
2118 // Show the URL history dialog.
2119 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2123 // Populate the resource requests.
2124 RequestsActivity.resourceRequests = currentWebView.getResourceRequests();
2126 // Create an intent to launch the Requests activity.
2127 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2129 // Add the block third-party requests status to the intent.
2130 requestsIntent.putExtra("block_all_third_party_requests", currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
2133 startActivity(requestsIntent);
2136 case R.id.downloads:
2137 // Launch the system Download Manager.
2138 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2140 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2141 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2143 startActivity(downloadManagerIntent);
2147 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2148 reapplyDomainSettingsOnRestart = true;
2150 // Launch the domains activity.
2151 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2153 // Add the extra information to the intent.
2154 domainsIntent.putExtra("current_url", currentWebView.getUrl());
2156 // Get the current certificate.
2157 SslCertificate sslCertificate = currentWebView.getCertificate();
2159 // Check to see if the SSL certificate is populated.
2160 if (sslCertificate != null) {
2161 // Extract the certificate to strings.
2162 String issuedToCName = sslCertificate.getIssuedTo().getCName();
2163 String issuedToOName = sslCertificate.getIssuedTo().getOName();
2164 String issuedToUName = sslCertificate.getIssuedTo().getUName();
2165 String issuedByCName = sslCertificate.getIssuedBy().getCName();
2166 String issuedByOName = sslCertificate.getIssuedBy().getOName();
2167 String issuedByUName = sslCertificate.getIssuedBy().getUName();
2168 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
2169 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
2171 // Add the certificate to the intent.
2172 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
2173 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
2174 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
2175 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
2176 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
2177 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
2178 domainsIntent.putExtra("ssl_start_date", startDateLong);
2179 domainsIntent.putExtra("ssl_end_date", endDateLong);
2182 // Check to see if the current IP addresses have been received.
2183 if (currentWebView.hasCurrentIpAddresses()) {
2184 // Add the current IP addresses to the intent.
2185 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
2189 startActivity(domainsIntent);
2193 // Set the flag to reapply app settings on restart when returning from Settings.
2194 reapplyAppSettingsOnRestart = true;
2196 // Set the flag to reapply the domain settings on restart when returning from Settings.
2197 reapplyDomainSettingsOnRestart = true;
2199 // Launch the settings activity.
2200 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2201 startActivity(settingsIntent);
2204 case R.id.import_export:
2205 // Launch the import/export activity.
2206 Intent importExportIntent = new Intent (this, ImportExportActivity.class);
2207 startActivity(importExportIntent);
2211 // Launch the logcat activity.
2212 Intent logcatIntent = new Intent(this, LogcatActivity.class);
2213 startActivity(logcatIntent);
2217 // Launch `GuideActivity`.
2218 Intent guideIntent = new Intent(this, GuideActivity.class);
2219 startActivity(guideIntent);
2223 // Create an intent to launch the about activity.
2224 Intent aboutIntent = new Intent(this, AboutActivity.class);
2226 // Create a string array for the blocklist versions.
2227 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],
2228 ultraPrivacy.get(0).get(0)[0]};
2230 // Add the blocklist versions to the intent.
2231 aboutIntent.putExtra("blocklist_versions", blocklistVersions);
2234 startActivity(aboutIntent);
2238 // Get a handle for the drawer layout.
2239 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
2241 // Close the navigation drawer.
2242 drawerLayout.closeDrawer(GravityCompat.START);
2247 public void onPostCreate(Bundle savedInstanceState) {
2248 // Run the default commands.
2249 super.onPostCreate(savedInstanceState);
2251 // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished. This creates the navigation drawer icon.
2252 actionBarDrawerToggle.syncState();
2256 public void onConfigurationChanged(Configuration newConfig) {
2257 // Run the default commands.
2258 super.onConfigurationChanged(newConfig);
2260 // Get the status bar pixel size.
2261 int statusBarResourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
2262 int statusBarPixelSize = getResources().getDimensionPixelSize(statusBarResourceId);
2264 // Get the resource density.
2265 float screenDensity = getResources().getDisplayMetrics().density;
2267 // Recalculate the drawer header padding.
2268 drawerHeaderPaddingLeftAndRight = (int) (15 * screenDensity);
2269 drawerHeaderPaddingTop = statusBarPixelSize + (int) (4 * screenDensity);
2270 drawerHeaderPaddingBottom = (int) (8 * screenDensity);
2272 // Reload the ad for the free flavor if not in full screen mode.
2273 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2274 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2275 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
2278 // `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:
2279 // https://code.google.com/p/android/issues/detail?id=20493#c8
2280 // ActivityCompat.invalidateOptionsMenu(this);
2284 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2285 // Store the hit test result.
2286 final WebView.HitTestResult hitTestResult = currentWebView.getHitTestResult();
2288 // Create the URL strings.
2289 final String imageUrl;
2290 final String linkUrl;
2292 // Get handles for the system managers.
2293 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2294 FragmentManager fragmentManager = getSupportFragmentManager();
2295 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2297 // Remove the lint errors below that the clipboard manager might be null.
2298 assert clipboardManager != null;
2300 // Process the link according to the type.
2301 switch (hitTestResult.getType()) {
2302 // `SRC_ANCHOR_TYPE` is a link.
2303 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2304 // Get the target URL.
2305 linkUrl = hitTestResult.getExtra();
2307 // Set the target URL as the title of the `ContextMenu`.
2308 menu.setHeaderTitle(linkUrl);
2310 // Add an Open in New Tab entry.
2311 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2312 // Load the link URL in a new tab.
2317 // Add an Open with App entry.
2318 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2319 openWithApp(linkUrl);
2323 // Add an Open with Browser entry.
2324 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2325 openWithBrowser(linkUrl);
2329 // Add a Copy URL entry.
2330 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2331 // Save the link URL in a `ClipData`.
2332 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2334 // Set the `ClipData` as the clipboard's primary clip.
2335 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2339 // Add a Download URL entry.
2340 menu.add(R.string.download_url).setOnMenuItemClickListener((MenuItem item) -> {
2341 // Check if the download should be processed by an external app.
2342 if (sharedPreferences.getBoolean("download_with_external_app", false)) { // Download with an external app.
2343 openUrlWithExternalApp(linkUrl);
2344 } else { // Download with Android's download manager.
2345 // Check to see if the storage permission has already been granted.
2346 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission needs to be requested.
2347 // Store the variables for future use by `onRequestPermissionsResult()`.
2348 downloadUrl = linkUrl;
2349 downloadContentDisposition = "none";
2350 downloadContentLength = -1;
2352 // Show a dialog if the user has previously denied the permission.
2353 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2354 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
2355 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
2357 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
2358 downloadLocationPermissionDialogFragment.show(fragmentManager, getString(R.string.download_location));
2359 } else { // Show the permission request directly.
2360 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
2361 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2363 } else { // The storage permission has already been granted.
2364 // Get a handle for the download file alert dialog.
2365 DialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(linkUrl, "none", -1);
2367 // Show the download file alert dialog.
2368 downloadFileDialogFragment.show(fragmentManager, getString(R.string.download));
2374 // Add a Cancel entry, which by default closes the context menu.
2375 menu.add(R.string.cancel);
2378 case WebView.HitTestResult.EMAIL_TYPE:
2379 // Get the target URL.
2380 linkUrl = hitTestResult.getExtra();
2382 // Set the target URL as the title of the `ContextMenu`.
2383 menu.setHeaderTitle(linkUrl);
2385 // Add a Write Email entry.
2386 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2387 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2388 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2390 // Parse the url and set it as the data for the `Intent`.
2391 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2393 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2394 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2397 startActivity(emailIntent);
2401 // Add a Copy Email Address entry.
2402 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2403 // Save the email address in a `ClipData`.
2404 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2406 // Set the `ClipData` as the clipboard's primary clip.
2407 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2411 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2412 menu.add(R.string.cancel);
2415 // `IMAGE_TYPE` is an image. `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link. Privacy Browser processes them the same.
2416 case WebView.HitTestResult.IMAGE_TYPE:
2417 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2418 // Get the image URL.
2419 imageUrl = hitTestResult.getExtra();
2421 // Set the image URL as the title of the context menu.
2422 menu.setHeaderTitle(imageUrl);
2424 // Add an Open in New Tab entry.
2425 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2426 // Load the image URL in a new tab.
2427 addNewTab(imageUrl);
2431 // Add a View Image entry.
2432 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2437 // Add a `Download Image` entry.
2438 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2439 // Check if the download should be processed by an external app.
2440 if (sharedPreferences.getBoolean("download_with_external_app", false)) { // Download with an external app.
2441 openUrlWithExternalApp(imageUrl);
2442 } else { // Download with Android's download manager.
2443 // Check to see if the storage permission has already been granted.
2444 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission needs to be requested.
2445 // Store the image URL for use by `onRequestPermissionResult()`.
2446 downloadImageUrl = imageUrl;
2448 // Show a dialog if the user has previously denied the permission.
2449 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2450 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2451 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2453 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
2454 downloadLocationPermissionDialogFragment.show(fragmentManager, getString(R.string.download_location));
2455 } else { // Show the permission request directly.
2456 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
2457 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2459 } else { // The storage permission has already been granted.
2460 // Get a handle for the download image alert dialog.
2461 DialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2463 // Show the download image alert dialog.
2464 downloadImageDialogFragment.show(fragmentManager, getString(R.string.download));
2470 // Add a `Copy URL` entry.
2471 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2472 // Save the image URL in a `ClipData`.
2473 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2475 // Set the `ClipData` as the clipboard's primary clip.
2476 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2480 // Add an Open with App entry.
2481 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2482 openWithApp(imageUrl);
2486 // Add an Open with Browser entry.
2487 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2488 openWithBrowser(imageUrl);
2492 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2493 menu.add(R.string.cancel);
2499 public void onCreateBookmark(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2500 // Get a handle for the bookmarks list view.
2501 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2503 // Get the views from the dialog fragment.
2504 EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
2505 EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
2507 // Extract the strings from the edit texts.
2508 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2509 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2511 // Create a favorite icon byte array output stream.
2512 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2514 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2515 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2517 // Convert the favorite icon byte array stream to a byte array.
2518 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2520 // Display the new bookmark below the current items in the (0 indexed) list.
2521 int newBookmarkDisplayOrder = bookmarksListView.getCount();
2523 // Create the bookmark.
2524 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2526 // Update the bookmarks cursor with the current contents of this folder.
2527 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2529 // Update the list view.
2530 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2532 // Scroll to the new bookmark.
2533 bookmarksListView.setSelection(newBookmarkDisplayOrder);
2537 public void onCreateBookmarkFolder(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2538 // Get a handle for the bookmarks list view.
2539 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2541 // Get handles for the views in the dialog fragment.
2542 EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
2543 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
2544 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
2546 // Get new folder name string.
2547 String folderNameString = createFolderNameEditText.getText().toString();
2549 // Create a folder icon bitmap.
2550 Bitmap folderIconBitmap;
2552 // Set the folder icon bitmap according to the dialog.
2553 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
2554 // Get the default folder icon drawable.
2555 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2557 // Convert the folder icon drawable to a bitmap drawable.
2558 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2560 // Convert the folder icon bitmap drawable to a bitmap.
2561 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2562 } else { // Use the WebView favorite icon.
2563 // Copy the favorite icon bitmap to the folder icon bitmap.
2564 folderIconBitmap = favoriteIconBitmap;
2567 // Create a folder icon byte array output stream.
2568 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2570 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2571 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2573 // Convert the folder icon byte array stream to a byte array.
2574 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2576 // Move all the bookmarks down one in the display order.
2577 for (int i = 0; i < bookmarksListView.getCount(); i++) {
2578 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2579 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2582 // Create the folder, which will be placed at the top of the `ListView`.
2583 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2585 // Update the bookmarks cursor with the current contents of this folder.
2586 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2588 // Update the `ListView`.
2589 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2591 // Scroll to the new folder.
2592 bookmarksListView.setSelection(0);
2596 public void onSaveBookmark(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, Bitmap favoriteIconBitmap) {
2597 // Get handles for the views from `dialogFragment`.
2598 EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
2599 EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
2600 RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
2602 // Store the bookmark strings.
2603 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
2604 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
2606 // Update the bookmark.
2607 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
2608 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
2609 } else { // Update the bookmark using the `WebView` favorite icon.
2610 // Create a favorite icon byte array output stream.
2611 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2613 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2614 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
2616 // Convert the favorite icon byte array stream to a byte array.
2617 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
2619 // Update the bookmark and the favorite icon.
2620 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
2623 // Update the bookmarks cursor with the current contents of this folder.
2624 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2626 // Update the list view.
2627 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2631 public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId, Bitmap favoriteIconBitmap) {
2632 // Get handles for the views from `dialogFragment`.
2633 EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
2634 RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
2635 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
2636 ImageView defaultFolderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
2638 // Get the new folder name.
2639 String newFolderNameString = editFolderNameEditText.getText().toString();
2641 // Check if the favorite icon has changed.
2642 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
2643 // Update the name in the database.
2644 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2645 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
2646 // Create the new folder icon Bitmap.
2647 Bitmap folderIconBitmap;
2649 // Populate the new folder icon bitmap.
2650 if (defaultFolderIconRadioButton.isChecked()) {
2651 // Get the default folder icon drawable.
2652 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2654 // Convert the folder icon drawable to a bitmap drawable.
2655 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2657 // Convert the folder icon bitmap drawable to a bitmap.
2658 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2659 } else { // Use the `WebView` favorite icon.
2660 // Copy the favorite icon bitmap to the folder icon bitmap.
2661 folderIconBitmap = favoriteIconBitmap;
2664 // Create a folder icon byte array output stream.
2665 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2667 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2668 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2670 // Convert the folder icon byte array stream to a byte array.
2671 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2673 // Update the folder icon in the database.
2674 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, newFolderIconByteArray);
2675 } else { // The folder icon and the name have changed.
2676 // Get the new folder icon `Bitmap`.
2677 Bitmap folderIconBitmap;
2678 if (defaultFolderIconRadioButton.isChecked()) {
2679 // Get the default folder icon drawable.
2680 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2682 // Convert the folder icon drawable to a bitmap drawable.
2683 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2685 // Convert the folder icon bitmap drawable to a bitmap.
2686 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2687 } else { // Use the `WebView` favorite icon.
2688 // Copy the favorite icon bitmap to the folder icon bitmap.
2689 folderIconBitmap = favoriteIconBitmap;
2692 // Create a folder icon byte array output stream.
2693 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2695 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2696 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2698 // Convert the folder icon byte array stream to a byte array.
2699 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2701 // Update the folder name and icon in the database.
2702 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, newFolderIconByteArray);
2705 // Update the bookmarks cursor with the current contents of this folder.
2706 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2708 // Update the `ListView`.
2709 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2713 public void onCloseDownloadLocationPermissionDialog(int downloadType) {
2714 switch (downloadType) {
2715 case DownloadLocationPermissionDialog.DOWNLOAD_FILE:
2716 // Request the WRITE_EXTERNAL_STORAGE permission with a file request code.
2717 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2720 case DownloadLocationPermissionDialog.DOWNLOAD_IMAGE:
2721 // Request the WRITE_EXTERNAL_STORAGE permission with an image request code.
2722 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2728 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
2729 // Get a handle for the fragment manager.
2730 FragmentManager fragmentManager = getSupportFragmentManager();
2732 switch (requestCode) {
2733 case DOWNLOAD_FILE_REQUEST_CODE:
2734 // Show the download file alert dialog. When the dialog closes, the correct command will be used based on the permission status.
2735 DialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(downloadUrl, downloadContentDisposition, downloadContentLength);
2737 // On API 23, displaying the fragment must be delayed or the app will crash.
2738 if (Build.VERSION.SDK_INT == 23) {
2739 new Handler().postDelayed(() -> downloadFileDialogFragment.show(fragmentManager, getString(R.string.download)), 500);
2741 downloadFileDialogFragment.show(fragmentManager, getString(R.string.download));
2744 // Reset the download variables.
2746 downloadContentDisposition = "";
2747 downloadContentLength = 0;
2750 case DOWNLOAD_IMAGE_REQUEST_CODE:
2751 // Show the download image alert dialog. When the dialog closes, the correct command will be used based on the permission status.
2752 DialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(downloadImageUrl);
2754 // On API 23, displaying the fragment must be delayed or the app will crash.
2755 if (Build.VERSION.SDK_INT == 23) {
2756 new Handler().postDelayed(() -> downloadImageDialogFragment.show(fragmentManager, getString(R.string.download)), 500);
2758 downloadImageDialogFragment.show(fragmentManager, getString(R.string.download));
2761 // Reset the image URL variable.
2762 downloadImageUrl = "";
2768 public void onDownloadImage(DialogFragment dialogFragment, String imageUrl) {
2769 // Download the image if it has an HTTP or HTTPS URI.
2770 if (imageUrl.startsWith("http")) {
2771 // Get a handle for the system `DOWNLOAD_SERVICE`.
2772 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2774 // Parse `imageUrl`.
2775 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
2777 // Get a handle for the cookie manager.
2778 CookieManager cookieManager = CookieManager.getInstance();
2780 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
2781 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2782 if (cookieManager.acceptCookie()) {
2783 // Get the cookies for `imageUrl`.
2784 String cookies = cookieManager.getCookie(imageUrl);
2786 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2787 downloadRequest.addRequestHeader("Cookie", cookies);
2790 // Get the file name from the dialog fragment.
2791 EditText downloadImageNameEditText = dialogFragment.getDialog().findViewById(R.id.download_image_name);
2792 String imageName = downloadImageNameEditText.getText().toString();
2794 // Specify the download location.
2795 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
2796 // Download to the public download directory.
2797 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, imageName);
2798 } else { // External write permission denied.
2799 // Download to the app's external download directory.
2800 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, imageName);
2803 // Allow `MediaScanner` to index the download if it is a media file.
2804 downloadRequest.allowScanningByMediaScanner();
2806 // Add the URL as the description for the download.
2807 downloadRequest.setDescription(imageUrl);
2809 // Show the download notification after the download is completed.
2810 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2812 // Remove the lint warning below that `downloadManager` might be `null`.
2813 assert downloadManager != null;
2815 // Initiate the download.
2816 downloadManager.enqueue(downloadRequest);
2817 } else { // The image is not an HTTP or HTTPS URI.
2818 Snackbar.make(currentWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
2823 public void onDownloadFile(DialogFragment dialogFragment, String downloadUrl) {
2824 // Download the file if it has an HTTP or HTTPS URI.
2825 if (downloadUrl.startsWith("http")) {
2826 // Get a handle for the system `DOWNLOAD_SERVICE`.
2827 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2829 // Parse `downloadUrl`.
2830 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
2832 // Get a handle for the cookie manager.
2833 CookieManager cookieManager = CookieManager.getInstance();
2835 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
2836 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2837 if (cookieManager.acceptCookie()) {
2838 // Get the cookies for `downloadUrl`.
2839 String cookies = cookieManager.getCookie(downloadUrl);
2841 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2842 downloadRequest.addRequestHeader("Cookie", cookies);
2845 // Get the file name from the dialog fragment.
2846 EditText downloadFileNameEditText = dialogFragment.getDialog().findViewById(R.id.download_file_name);
2847 String fileName = downloadFileNameEditText.getText().toString();
2849 // Specify the download location.
2850 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
2851 // Download to the public download directory.
2852 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
2853 } else { // External write permission denied.
2854 // Download to the app's external download directory.
2855 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, fileName);
2858 // Allow `MediaScanner` to index the download if it is a media file.
2859 downloadRequest.allowScanningByMediaScanner();
2861 // Add the URL as the description for the download.
2862 downloadRequest.setDescription(downloadUrl);
2864 // Show the download notification after the download is completed.
2865 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2867 // Remove the lint warning below that `downloadManager` might be `null`.
2868 assert downloadManager != null;
2870 // Initiate the download.
2871 downloadManager.enqueue(downloadRequest);
2872 } else { // The download is not an HTTP or HTTPS URI.
2873 Snackbar.make(currentWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
2877 // Override `onBackPressed` to handle the navigation drawer and and the WebView.
2879 public void onBackPressed() {
2880 // Get a handle for the drawer layout and the tab layout.
2881 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
2882 TabLayout tabLayout = findViewById(R.id.tablayout);
2884 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
2885 // Close the navigation drawer.
2886 drawerLayout.closeDrawer(GravityCompat.START);
2887 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
2888 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
2889 // close the bookmarks drawer.
2890 drawerLayout.closeDrawer(GravityCompat.END);
2891 } else { // A subfolder is displayed.
2892 // Place the former parent folder in `currentFolder`.
2893 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolderName(currentBookmarksFolder);
2895 // Load the new folder.
2896 loadBookmarksFolder();
2898 } else if (currentWebView.canGoBack()) { // There is at least one item in the current WebView history.
2899 // Reset the current domain name so that navigation works if third-party requests are blocked.
2900 currentWebView.resetCurrentDomainName();
2902 // Set navigating history so that the domain settings are applied when the new URL is loaded.
2903 currentWebView.setNavigatingHistory(true);
2906 currentWebView.goBack();
2907 } else if (tabLayout.getTabCount() > 1) { // There are at least two tabs.
2908 // Close the current tab.
2910 } else { // There isn't anything to do in Privacy Browser.
2911 // Run the default commands.
2912 super.onBackPressed();
2914 // Manually kill Privacy Browser. Otherwise, it is glitchy when restarted.
2919 // 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.
2921 public void onActivityResult(int requestCode, int resultCode, Intent data) {
2922 // File uploads only work on API >= 21.
2923 if (Build.VERSION.SDK_INT >= 21) {
2924 // Pass the file to the WebView.
2925 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
2929 private void loadUrlFromTextBox() {
2930 // Get a handle for the URL edit text.
2931 EditText urlEditText = findViewById(R.id.url_edittext);
2933 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
2934 String unformattedUrlString = urlEditText.getText().toString().trim();
2936 // Initialize the formatted URL string.
2939 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
2940 if (unformattedUrlString.startsWith("content://")) { // This is a Content URL.
2941 // Load the entire content URL.
2942 url = unformattedUrlString;
2943 } else if (Patterns.WEB_URL.matcher(unformattedUrlString).matches() || unformattedUrlString.startsWith("http://") || unformattedUrlString.startsWith("https://") ||
2944 unformattedUrlString.startsWith("file://")) { // This is a standard URL.
2945 // Add `https://` at the beginning if there is no protocol. Otherwise the app will segfault.
2946 if (!unformattedUrlString.startsWith("http") && !unformattedUrlString.startsWith("file://") && !unformattedUrlString.startsWith("content://")) {
2947 unformattedUrlString = "https://" + unformattedUrlString;
2950 // Initialize `unformattedUrl`.
2951 URL unformattedUrl = null;
2953 // 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.
2955 unformattedUrl = new URL(unformattedUrlString);
2956 } catch (MalformedURLException e) {
2957 e.printStackTrace();
2960 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2961 String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2962 String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2963 String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2964 String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2965 String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2968 Uri.Builder uri = new Uri.Builder();
2969 uri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2971 // Decode the URI as a UTF-8 string in.
2973 url = URLDecoder.decode(uri.build().toString(), "UTF-8");
2974 } catch (UnsupportedEncodingException exception) {
2975 // Do nothing. The formatted URL string will remain blank.
2977 } else if (!unformattedUrlString.isEmpty()){ // This is not a URL, but rather a search string.
2978 // Create an encoded URL String.
2979 String encodedUrlString;
2981 // Sanitize the search input.
2983 encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2984 } catch (UnsupportedEncodingException exception) {
2985 encodedUrlString = "";
2988 // Add the base search URL.
2989 url = searchURL + encodedUrlString;
2992 // 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.
2993 urlEditText.clearFocus();
2999 private void loadUrl(String url) {
3000 // Sanitize the URL.
3001 url = sanitizeUrl(url);
3003 // Apply the domain settings.
3004 applyDomainSettings(currentWebView, url, true, false);
3007 currentWebView.loadUrl(url, customHeaders);
3010 public void findPreviousOnPage(View view) {
3011 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
3012 currentWebView.findNext(false);
3015 public void findNextOnPage(View view) {
3016 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
3017 currentWebView.findNext(true);
3020 public void closeFindOnPage(View view) {
3021 // Get a handle for the views.
3022 Toolbar toolbar = findViewById(R.id.toolbar);
3023 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
3024 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
3026 // Delete the contents of `find_on_page_edittext`.
3027 findOnPageEditText.setText(null);
3029 // Clear the highlighted phrases if the WebView is not null.
3030 if (currentWebView != null) {
3031 currentWebView.clearMatches();
3034 // Hide the find on page linear layout.
3035 findOnPageLinearLayout.setVisibility(View.GONE);
3037 // Show the toolbar.
3038 toolbar.setVisibility(View.VISIBLE);
3040 // Get a handle for the input method manager.
3041 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
3043 // Remove the lint warning below that the input method manager might be null.
3044 assert inputMethodManager != null;
3046 // Hide the keyboard.
3047 inputMethodManager.hideSoftInputFromWindow(toolbar.getWindowToken(), 0);
3050 private void applyAppSettings() {
3051 // Get a handle for the shared preferences.
3052 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3054 // Store the values from the shared preferences in variables.
3055 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3056 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
3057 sanitizeGoogleAnalytics = sharedPreferences.getBoolean("google_analytics", true);
3058 sanitizeFacebookClickIds = sharedPreferences.getBoolean("facebook_click_ids", true);
3059 sanitizeTwitterAmpRedirects = sharedPreferences.getBoolean("twitter_amp_redirects", true);
3060 proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
3061 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3062 hideAppBar = sharedPreferences.getBoolean("hide_app_bar", true);
3063 scrollAppBar = sharedPreferences.getBoolean("scroll_app_bar", true);
3065 // Get handles for the views that need to be modified.
3066 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
3067 AppBarLayout appBarLayout = findViewById(R.id.appbar_layout);
3068 ActionBar actionBar = getSupportActionBar();
3069 Toolbar toolbar = findViewById(R.id.toolbar);
3070 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
3071 LinearLayout tabsLinearLayout = findViewById(R.id.tabs_linearlayout);
3072 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
3074 // Remove the incorrect lint warning below that the action bar might be null.
3075 assert actionBar != null;
3077 // Apply the proxy through Orbot settings.
3078 applyProxyThroughOrbot(false);
3080 // Set Do Not Track status.
3081 if (doNotTrackEnabled) {
3082 customHeaders.put("DNT", "1");
3084 customHeaders.remove("DNT");
3087 // Get the current layout parameters. Using coordinator layout parameters allows the `setBehavior()` command and using app bar layout parameters allows the `setScrollFlags()` command.
3088 CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
3089 AppBarLayout.LayoutParams toolbarLayoutParams = (AppBarLayout.LayoutParams) toolbar.getLayoutParams();
3090 AppBarLayout.LayoutParams findOnPageLayoutParams = (AppBarLayout.LayoutParams) findOnPageLinearLayout.getLayoutParams();
3091 AppBarLayout.LayoutParams tabsLayoutParams = (AppBarLayout.LayoutParams) tabsLinearLayout.getLayoutParams();
3093 // Add the scrolling behavior to the layout parameters.
3095 // Enable scrolling of the app bar.
3096 swipeRefreshLayoutParams.setBehavior(new AppBarLayout.ScrollingViewBehavior());
3097 toolbarLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3098 findOnPageLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3099 tabsLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3101 // Disable scrolling of the app bar.
3102 swipeRefreshLayoutParams.setBehavior(null);
3103 toolbarLayoutParams.setScrollFlags(0);
3104 findOnPageLayoutParams.setScrollFlags(0);
3105 tabsLayoutParams.setScrollFlags(0);
3107 // Expand the app bar if it is currently collapsed.
3108 appBarLayout.setExpanded(true);
3111 // Apply the modified layout parameters.
3112 swipeRefreshLayout.setLayoutParams(swipeRefreshLayoutParams);
3113 toolbar.setLayoutParams(toolbarLayoutParams);
3114 findOnPageLinearLayout.setLayoutParams(findOnPageLayoutParams);
3115 tabsLinearLayout.setLayoutParams(tabsLayoutParams);
3117 // Set the app bar scrolling for each WebView.
3118 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3119 // Get the WebView tab fragment.
3120 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3122 // Get the fragment view.
3123 View fragmentView = webViewTabFragment.getView();
3125 // Only modify the WebViews if they exist.
3126 if (fragmentView != null) {
3127 // Get the nested scroll WebView from the tab fragment.
3128 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3130 // Set the app bar scrolling.
3131 nestedScrollWebView.setNestedScrollingEnabled(scrollAppBar);
3135 // Update the full screen browsing mode settings.
3136 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
3137 // Update the visibility of the app bar, which might have changed in the settings.
3139 // Hide the tab linear layout.
3140 tabsLinearLayout.setVisibility(View.GONE);
3142 // Hide the action bar.
3145 // Show the tab linear layout.
3146 tabsLinearLayout.setVisibility(View.VISIBLE);
3148 // Show the action bar.
3152 // Hide the banner ad in the free flavor.
3153 if (BuildConfig.FLAVOR.contentEquals("free")) {
3154 AdHelper.hideAd(findViewById(R.id.adview));
3157 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
3158 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3160 /* Hide the system bars.
3161 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3162 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
3163 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3164 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3166 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
3167 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3168 } else { // Privacy Browser is not in full screen browsing mode.
3169 // 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.
3170 inFullScreenBrowsingMode = false;
3172 // Show the tab linear layout.
3173 tabsLinearLayout.setVisibility(View.VISIBLE);
3175 // Show the action bar.
3178 // Show the banner ad in the free flavor.
3179 if (BuildConfig.FLAVOR.contentEquals("free")) {
3180 // Initialize the ads. If this isn't the first run, `loadAd()` will be automatically called instead.
3181 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getSupportFragmentManager(), getString(R.string.google_app_id), getString(R.string.ad_unit_id));
3184 // Remove the `SYSTEM_UI` flags from the root frame layout.
3185 rootFrameLayout.setSystemUiVisibility(0);
3187 // Add the translucent status flag.
3188 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3193 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
3194 @SuppressLint("SetJavaScriptEnabled")
3195 private boolean applyDomainSettings(NestedScrollWebView nestedScrollWebView, String url, boolean resetTab, boolean reloadWebsite) {
3196 // Store a copy of the current user agent to track changes for the return boolean.
3197 String initialUserAgent = nestedScrollWebView.getSettings().getUserAgentString();
3199 // Parse the URL into a URI.
3200 Uri uri = Uri.parse(url);
3202 // Extract the domain from `uri`.
3203 String newHostName = uri.getHost();
3205 // Strings don't like to be null.
3206 if (newHostName == null) {
3210 // 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.
3211 if (!nestedScrollWebView.getCurrentDomainName().equals(newHostName) || newHostName.equals("")) {
3212 // Set the new host name as the current domain name.
3213 nestedScrollWebView.setCurrentDomainName(newHostName);
3215 // Reset the ignoring of pinned domain information.
3216 nestedScrollWebView.setIgnorePinnedDomainInformation(false);
3218 // Clear any pinned SSL certificate or IP addresses.
3219 nestedScrollWebView.clearPinnedSslCertificate();
3220 nestedScrollWebView.clearPinnedIpAddresses();
3222 // Reset the favorite icon if specified.
3224 // Initialize the favorite icon.
3225 nestedScrollWebView.initializeFavoriteIcon();
3227 // Get the current page position.
3228 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
3230 // Get a handle for the tab layout.
3231 TabLayout tabLayout = findViewById(R.id.tablayout);
3233 // Get the corresponding tab.
3234 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
3236 // Update the tab if it isn't null, which sometimes happens when restarting from the background.
3238 // Get the tab custom view.
3239 View tabCustomView = tab.getCustomView();
3241 // Remove the warning below that the tab custom view might be null.
3242 assert tabCustomView != null;
3244 // Get the tab views.
3245 ImageView tabFavoriteIconImageView = tabCustomView.findViewById(R.id.favorite_icon_imageview);
3246 TextView tabTitleTextView = tabCustomView.findViewById(R.id.title_textview);
3248 // Set the default favorite icon as the favorite icon for this tab.
3249 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(nestedScrollWebView.getFavoriteOrDefaultIcon(), 64, 64, true));
3251 // Set the loading title text.
3252 tabTitleTextView.setText(R.string.loading);
3256 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3257 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3259 // Get a full cursor from `domainsDatabaseHelper`.
3260 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3262 // Initialize `domainSettingsSet`.
3263 Set<String> domainSettingsSet = new HashSet<>();
3265 // Get the domain name column index.
3266 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3268 // Populate `domainSettingsSet`.
3269 for (int i = 0; i < domainNameCursor.getCount(); i++) {
3270 // Move `domainsCursor` to the current row.
3271 domainNameCursor.moveToPosition(i);
3273 // Store the domain name in `domainSettingsSet`.
3274 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3277 // Close `domainNameCursor.
3278 domainNameCursor.close();
3280 // Initialize the domain name in database variable.
3281 String domainNameInDatabase = null;
3283 // Check the hostname against the domain settings set.
3284 if (domainSettingsSet.contains(newHostName)) { // The hostname is contained in the domain settings set.
3285 // Record the domain name in the database.
3286 domainNameInDatabase = newHostName;
3288 // Set the domain settings applied tracker to true.
3289 nestedScrollWebView.setDomainSettingsApplied(true);
3290 } else { // The hostname is not contained in the domain settings set.
3291 // Set the domain settings applied tracker to false.
3292 nestedScrollWebView.setDomainSettingsApplied(false);
3295 // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3296 while (!nestedScrollWebView.getDomainSettingsApplied() && newHostName.contains(".")) { // Stop checking if domain settings are already applied or there are no more `.` in the host name.
3297 if (domainSettingsSet.contains("*." + newHostName)) { // Check the host name prepended by `*.`.
3298 // Set the domain settings applied tracker to true.
3299 nestedScrollWebView.setDomainSettingsApplied(true);
3301 // Store the applied domain names as it appears in the database.
3302 domainNameInDatabase = "*." + newHostName;
3305 // Strip out the lowest subdomain of of the host name.
3306 newHostName = newHostName.substring(newHostName.indexOf(".") + 1);
3310 // Get a handle for the shared preferences.
3311 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3313 // Store the general preference information.
3314 String defaultFontSizeString = sharedPreferences.getString("font_size", getString(R.string.font_size_default_value));
3315 String defaultUserAgentName = sharedPreferences.getString("user_agent", getString(R.string.user_agent_default_value));
3316 boolean defaultSwipeToRefresh = sharedPreferences.getBoolean("swipe_to_refresh", true);
3317 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
3318 boolean wideViewport = sharedPreferences.getBoolean("wide_viewport", true);
3319 boolean displayWebpageImages = sharedPreferences.getBoolean("display_webpage_images", true);
3321 // Get a handle for the cookie manager.
3322 CookieManager cookieManager = CookieManager.getInstance();
3324 // Get handles for the views.
3325 RelativeLayout urlRelativeLayout = findViewById(R.id.url_relativelayout);
3326 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
3328 // Initialize the user agent array adapter and string array.
3329 ArrayAdapter<CharSequence> userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item);
3330 String[] userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
3332 if (nestedScrollWebView.getDomainSettingsApplied()) { // The url has custom domain settings.
3333 // Get a cursor for the current host and move it to the first position.
3334 Cursor currentDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3335 currentDomainSettingsCursor.moveToFirst();
3337 // Get the settings from the cursor.
3338 nestedScrollWebView.setDomainSettingsDatabaseId(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3339 nestedScrollWebView.setDomainSettingsJavaScriptEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3340 nestedScrollWebView.setAcceptFirstPartyCookies(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3341 boolean domainThirdPartyCookiesEnabled = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3342 nestedScrollWebView.getSettings().setDomStorageEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3343 // Form data can be removed once the minimum API >= 26.
3344 boolean saveFormData = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3345 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASY_LIST,
3346 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3347 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASY_PRIVACY,
3348 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3349 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST,
3350 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3351 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST,
3352 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3353 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRA_PRIVACY,
3354 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_ULTRAPRIVACY)) == 1);
3355 nestedScrollWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS,
3356 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
3357 String userAgentName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3358 int fontSize = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3359 int swipeToRefreshInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
3360 int nightModeInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
3361 int wideViewportInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.WIDE_VIEWPORT));
3362 int displayWebpageImagesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3363 boolean pinnedSslCertificate = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3364 String pinnedSslIssuedToCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3365 String pinnedSslIssuedToOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3366 String pinnedSslIssuedToUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3367 String pinnedSslIssuedByCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3368 String pinnedSslIssuedByOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3369 String pinnedSslIssuedByUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3370 boolean pinnedIpAddresses = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_IP_ADDRESSES)) == 1);
3371 String pinnedHostIpAddresses = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.IP_ADDRESSES));
3373 // Create the pinned SSL date variables.
3374 Date pinnedSslStartDate;
3375 Date pinnedSslEndDate;
3377 // 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.
3378 if (currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
3379 pinnedSslStartDate = null;
3381 pinnedSslStartDate = new Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
3384 // 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.
3385 if (currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
3386 pinnedSslEndDate = null;
3388 pinnedSslEndDate = new Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
3391 // If there is a pinned SSL certificate, store it in the WebView.
3392 if (pinnedSslCertificate) {
3393 nestedScrollWebView.setPinnedSslCertificate(pinnedSslIssuedToCName, pinnedSslIssuedToOName, pinnedSslIssuedToUName, pinnedSslIssuedByCName, pinnedSslIssuedByOName, pinnedSslIssuedByUName,
3394 pinnedSslStartDate, pinnedSslEndDate);
3397 // If there is a pinned IP address, store it in the WebView.
3398 if (pinnedIpAddresses) {
3399 nestedScrollWebView.setPinnedIpAddresses(pinnedHostIpAddresses);
3402 // Set night mode according to the night mode int.
3403 switch (nightModeInt) {
3404 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
3405 // Set night mode according to the current default.
3406 nestedScrollWebView.setNightMode(sharedPreferences.getBoolean("night_mode", false));
3409 case DomainsDatabaseHelper.ENABLED:
3410 // Enable night mode.
3411 nestedScrollWebView.setNightMode(true);
3414 case DomainsDatabaseHelper.DISABLED:
3415 // Disable night mode.
3416 nestedScrollWebView.setNightMode(false);
3420 // Enable JavaScript if night mode is enabled.
3421 if (nestedScrollWebView.getNightMode()) {
3422 // Enable JavaScript.
3423 nestedScrollWebView.getSettings().setJavaScriptEnabled(true);
3425 // Set JavaScript according to the domain settings.
3426 nestedScrollWebView.getSettings().setJavaScriptEnabled(nestedScrollWebView.getDomainSettingsJavaScriptEnabled());
3429 // Close the current host domain settings cursor.
3430 currentDomainSettingsCursor.close();
3432 // Apply the domain settings.
3433 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptFirstPartyCookies());
3435 // Set third-party cookies status if API >= 21.
3436 if (Build.VERSION.SDK_INT >= 21) {
3437 cookieManager.setAcceptThirdPartyCookies(nestedScrollWebView, domainThirdPartyCookiesEnabled);
3440 // Apply the form data setting if the API < 26.
3441 if (Build.VERSION.SDK_INT < 26) {
3442 nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
3445 // Apply the font size.
3446 if (fontSize == 0) { // Apply the default font size.
3447 nestedScrollWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3448 } else { // Apply the specified font size.
3449 nestedScrollWebView.getSettings().setTextZoom(fontSize);
3452 // Set the user agent.
3453 if (userAgentName.equals(getString(R.string.system_default_user_agent))) { // Use the system default user agent.
3454 // Get the array position of the default user agent name.
3455 int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3457 // Set the user agent according to the system default.
3458 switch (defaultUserAgentArrayPosition) {
3459 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
3460 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3461 nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
3464 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3465 // Set the user agent to `""`, which uses the default value.
3466 nestedScrollWebView.getSettings().setUserAgentString("");
3469 case SETTINGS_CUSTOM_USER_AGENT:
3470 // Set the default custom user agent.
3471 nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
3475 // Get the user agent string from the user agent data array
3476 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
3478 } else { // Set the user agent according to the stored name.
3479 // Get the array position of the user agent name.
3480 int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
3482 switch (userAgentArrayPosition) {
3483 case UNRECOGNIZED_USER_AGENT: // The user agent name contains a custom user agent.
3484 nestedScrollWebView.getSettings().setUserAgentString(userAgentName);
3487 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3488 // Set the user agent to `""`, which uses the default value.
3489 nestedScrollWebView.getSettings().setUserAgentString("");
3493 // Get the user agent string from the user agent data array.
3494 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3498 // Set swipe to refresh.
3499 switch (swipeToRefreshInt) {
3500 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
3501 // Store the swipe to refresh status in the nested scroll WebView.
3502 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
3504 // 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.
3505 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
3508 case DomainsDatabaseHelper.ENABLED:
3509 // Store the swipe to refresh status in the nested scroll WebView.
3510 nestedScrollWebView.setSwipeToRefresh(true);
3512 // Enable swipe to refresh. This can be removed once the minimum API >= 23 because it is continuously set by an on scroll change listener.
3513 swipeRefreshLayout.setEnabled(true);
3516 case DomainsDatabaseHelper.DISABLED:
3517 // Store the swipe to refresh status in the nested scroll WebView.
3518 nestedScrollWebView.setSwipeToRefresh(false);
3520 // Disable swipe to refresh. This can be removed once the minimum API >= 23 because it is continuously set by an on scroll change listener.
3521 swipeRefreshLayout.setEnabled(false);
3524 // Set the viewport.
3525 switch (wideViewportInt) {
3526 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
3527 nestedScrollWebView.getSettings().setUseWideViewPort(wideViewport);
3530 case DomainsDatabaseHelper.ENABLED:
3531 nestedScrollWebView.getSettings().setUseWideViewPort(true);
3534 case DomainsDatabaseHelper.DISABLED:
3535 nestedScrollWebView.getSettings().setUseWideViewPort(false);
3539 // Set the loading of webpage images.
3540 switch (displayWebpageImagesInt) {
3541 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
3542 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
3545 case DomainsDatabaseHelper.ENABLED:
3546 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(true);
3549 case DomainsDatabaseHelper.DISABLED:
3550 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(false);
3554 // 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.
3556 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
3558 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
3560 } else { // The new URL does not have custom domain settings. Load the defaults.
3561 // Store the values from the shared preferences.
3562 boolean defaultJavaScriptEnabled = sharedPreferences.getBoolean("javascript", false);
3563 nestedScrollWebView.setAcceptFirstPartyCookies(sharedPreferences.getBoolean("first_party_cookies", false));
3564 boolean defaultThirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies", false);
3565 nestedScrollWebView.getSettings().setDomStorageEnabled(sharedPreferences.getBoolean("dom_storage", false));
3566 boolean saveFormData = sharedPreferences.getBoolean("save_form_data", false); // Form data can be removed once the minimum API >= 26.
3567 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASY_LIST, sharedPreferences.getBoolean("easylist", true));
3568 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASY_PRIVACY, sharedPreferences.getBoolean("easyprivacy", true));
3569 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, sharedPreferences.getBoolean("fanboys_annoyance_list", true));
3570 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, sharedPreferences.getBoolean("fanboys_social_blocking_list", true));
3571 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRA_PRIVACY, sharedPreferences.getBoolean("ultraprivacy", true));
3572 nestedScrollWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, sharedPreferences.getBoolean("block_all_third_party_requests", false));
3573 nestedScrollWebView.setNightMode(sharedPreferences.getBoolean("night_mode", false));
3575 // Enable JavaScript if night mode is enabled.
3576 if (nestedScrollWebView.getNightMode()) {
3577 // Enable JavaScript.
3578 nestedScrollWebView.getSettings().setJavaScriptEnabled(true);
3580 // Set JavaScript according to the domain settings.
3581 nestedScrollWebView.getSettings().setJavaScriptEnabled(defaultJavaScriptEnabled);
3584 // Apply the default settings.
3585 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptFirstPartyCookies());
3586 nestedScrollWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3588 // Apply the form data setting if the API < 26.
3589 if (Build.VERSION.SDK_INT < 26) {
3590 nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
3593 // Store the swipe to refresh status in the nested scroll WebView.
3594 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
3596 // Apply swipe to refresh according to the default.
3597 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
3599 // Reset the pinned variables.
3600 nestedScrollWebView.setDomainSettingsDatabaseId(-1);
3602 // Set third-party cookies status if API >= 21.
3603 if (Build.VERSION.SDK_INT >= 21) {
3604 cookieManager.setAcceptThirdPartyCookies(nestedScrollWebView, defaultThirdPartyCookiesEnabled);
3607 // Get the array position of the user agent name.
3608 int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3610 // Set the user agent.
3611 switch (userAgentArrayPosition) {
3612 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
3613 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3614 nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
3617 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3618 // Set the user agent to `""`, which uses the default value.
3619 nestedScrollWebView.getSettings().setUserAgentString("");
3622 case SETTINGS_CUSTOM_USER_AGENT:
3623 // Set the default custom user agent.
3624 nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
3628 // Get the user agent string from the user agent data array
3629 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3632 // Set the viewport.
3633 nestedScrollWebView.getSettings().setUseWideViewPort(wideViewport);
3635 // Set the loading of webpage images.
3636 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
3638 // Set a transparent background on URL edit text. The deprecated `getResources().getDrawable()` must be used until the minimum API >= 21.
3639 urlRelativeLayout.setBackground(getResources().getDrawable(R.color.transparent));
3642 // Close the domains database helper.
3643 domainsDatabaseHelper.close();
3645 // Update the privacy icons.
3646 updatePrivacyIcons(true);
3649 // Reload the website if returning from the Domains activity.
3650 if (reloadWebsite) {
3651 nestedScrollWebView.reload();
3654 // Return the user agent changed status.
3655 return !nestedScrollWebView.getSettings().getUserAgentString().equals(initialUserAgent);
3658 private void applyProxyThroughOrbot(boolean reloadWebsite) {
3659 // Get a handle for the shared preferences.
3660 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3662 // Get the search and theme preferences.
3663 String torSearchString = sharedPreferences.getString("tor_search", getString(R.string.tor_search_default_value));
3664 String torSearchCustomUrlString = sharedPreferences.getString("tor_search_custom_url", getString(R.string.tor_search_custom_url_default_value));
3665 String searchString = sharedPreferences.getString("search", getString(R.string.search_default_value));
3666 String searchCustomUrlString = sharedPreferences.getString("search_custom_url", getString(R.string.search_custom_url_default_value));
3667 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
3669 // Get a handle for the app bar layout.
3670 AppBarLayout appBarLayout = findViewById(R.id.appbar_layout);
3672 // Set the homepage, search, and proxy options.
3673 if (proxyThroughOrbot) { // Set the Tor options.
3674 // Set the search URL.
3675 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
3676 searchURL = torSearchCustomUrlString;
3677 } else { // Use the string from the pre-built list.
3678 searchURL = torSearchString;
3681 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
3682 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
3684 // Set the app bar background to indicate proxying through Orbot is enabled.
3686 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
3688 appBarLayout.setBackgroundResource(R.color.blue_50);
3691 // Check to see if Orbot is ready.
3692 if (!orbotStatus.equals("ON")) { // Orbot is not ready.
3693 // Set `waitingForOrbot`.
3694 waitingForOrbot = true;
3696 // Disable the wide view port so that the waiting for Orbot text is displayed correctly.
3697 currentWebView.getSettings().setUseWideViewPort(false);
3699 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
3700 currentWebView.loadData("<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>", "text/html", null);
3701 } else if (reloadWebsite) { // Orbot is ready and the website should be reloaded.
3702 // Reload the website.
3703 currentWebView.reload();
3705 } else { // Set the non-Tor options.
3706 // Set the search URL.
3707 if (searchString.equals("Custom URL")) { // Get the custom URL string.
3708 searchURL = searchCustomUrlString;
3709 } else { // Use the string from the pre-built list.
3710 searchURL = searchString;
3713 // Reset the proxy to default. The host is `""` and the port is `"0"`.
3714 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
3716 // Set the default app bar layout background.
3718 appBarLayout.setBackgroundResource(R.color.gray_900);
3720 appBarLayout.setBackgroundResource(R.color.gray_100);
3723 // Reset `waitingForOrbot.
3724 waitingForOrbot = false;
3726 // Reload the WebViews if requested.
3727 if (reloadWebsite) {
3728 // Reload the WebViews.
3729 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3730 // Get the WebView tab fragment.
3731 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3733 // Get the fragment view.
3734 View fragmentView = webViewTabFragment.getView();
3736 // Only reload the WebViews if they exist.
3737 if (fragmentView != null) {
3738 // Get the nested scroll WebView from the tab fragment.
3739 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3741 // Reload the WebView.
3742 nestedScrollWebView.reload();
3749 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
3750 // Only update the privacy icons if the options menu and the current WebView have already been populated.
3751 if ((optionsMenu != null) && (currentWebView != null)) {
3752 // Get a handle for the shared preferences.
3753 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3755 // Get the theme and screenshot preferences.
3756 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
3758 // Get handles for the menu items.
3759 MenuItem privacyMenuItem = optionsMenu.findItem(R.id.toggle_javascript);
3760 MenuItem firstPartyCookiesMenuItem = optionsMenu.findItem(R.id.toggle_first_party_cookies);
3761 MenuItem domStorageMenuItem = optionsMenu.findItem(R.id.toggle_dom_storage);
3762 MenuItem refreshMenuItem = optionsMenu.findItem(R.id.refresh);
3764 // Update the privacy icon.
3765 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is enabled.
3766 privacyMenuItem.setIcon(R.drawable.javascript_enabled);
3767 } else if (currentWebView.getAcceptFirstPartyCookies()) { // JavaScript is disabled but cookies are enabled.
3768 privacyMenuItem.setIcon(R.drawable.warning);
3769 } else { // All the dangerous features are disabled.
3770 privacyMenuItem.setIcon(R.drawable.privacy_mode);
3773 // Update the first-party cookies icon.
3774 if (currentWebView.getAcceptFirstPartyCookies()) { // First-party cookies are enabled.
3775 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
3776 } else { // First-party cookies are disabled.
3778 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_dark);
3780 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_light);
3784 // Update the DOM storage icon.
3785 if (currentWebView.getSettings().getJavaScriptEnabled() && currentWebView.getSettings().getDomStorageEnabled()) { // Both JavaScript and DOM storage are enabled.
3786 domStorageMenuItem.setIcon(R.drawable.dom_storage_enabled);
3787 } else if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is enabled but DOM storage is disabled.
3789 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
3791 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
3793 } else { // JavaScript is disabled, so DOM storage is ghosted.
3795 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
3797 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
3801 // Update the refresh icon.
3803 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
3805 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
3808 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
3809 if (runInvalidateOptionsMenu) {
3810 invalidateOptionsMenu();
3815 private void openUrlWithExternalApp(String url) {
3816 // Create a download intent. Not specifying the action type will display the maximum number of options.
3817 Intent downloadIntent = new Intent();
3819 // Set the URI and the MIME type. Specifying `text/html` displays a good number of options.
3820 downloadIntent.setDataAndType(Uri.parse(url), "text/html");
3822 // Flag the intent to open in a new task.
3823 downloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3825 // Show the chooser.
3826 startActivity(Intent.createChooser(downloadIntent, getString(R.string.open_with)));
3829 private void highlightUrlText() {
3830 // Get a handle for the URL edit text.
3831 EditText urlEditText = findViewById(R.id.url_edittext);
3833 // Only highlight the URL text if the box is not currently selected.
3834 if (!urlEditText.hasFocus()) {
3835 // Get the URL string.
3836 String urlString = urlEditText.getText().toString();
3838 // Highlight the URL according to the protocol.
3839 if (urlString.startsWith("file://")) { // This is a file URL.
3840 // De-emphasize only the protocol.
3841 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3842 } else if (urlString.startsWith("content://")) {
3843 // De-emphasize only the protocol.
3844 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 10, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3845 } else { // This is a web URL.
3846 // Get the index of the `/` immediately after the domain name.
3847 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
3849 // Create a base URL string.
3852 // Get the base URL.
3853 if (endOfDomainName > 0) { // There is at least one character after the base URL.
3854 // Get the base URL.
3855 baseUrl = urlString.substring(0, endOfDomainName);
3856 } else { // There are no characters after the base URL.
3857 // Set the base URL to be the entire URL string.
3858 baseUrl = urlString;
3861 // Get the index of the last `.` in the domain.
3862 int lastDotIndex = baseUrl.lastIndexOf(".");
3864 // Get the index of the penultimate `.` in the domain.
3865 int penultimateDotIndex = baseUrl.lastIndexOf(".", lastDotIndex - 1);
3867 // Markup the beginning of the URL.
3868 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
3869 urlEditText.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3871 // De-emphasize subdomains.
3872 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
3873 urlEditText.getText().setSpan(initialGrayColorSpan, 7, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3875 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
3876 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
3877 // De-emphasize the protocol and the additional subdomains.
3878 urlEditText.getText().setSpan(initialGrayColorSpan, 0, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3879 } else { // There is only one subdomain in the domain name.
3880 // De-emphasize only the protocol.
3881 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3885 // De-emphasize the text after the domain name.
3886 if (endOfDomainName > 0) {
3887 urlEditText.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3893 private void loadBookmarksFolder() {
3894 // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
3895 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
3897 // Populate the bookmarks cursor adapter. `this` specifies the `Context`. `false` disables `autoRequery`.
3898 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
3900 public View newView(Context context, Cursor cursor, ViewGroup parent) {
3901 // Inflate the individual item layout. `false` does not attach it to the root.
3902 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
3906 public void bindView(View view, Context context, Cursor cursor) {
3907 // Get handles for the views.
3908 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
3909 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
3911 // Get the favorite icon byte array from the cursor.
3912 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
3914 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
3915 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
3917 // Display the bitmap in `bookmarkFavoriteIcon`.
3918 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
3920 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
3921 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
3922 bookmarkNameTextView.setText(bookmarkNameString);
3924 // Make the font bold for folders.
3925 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
3926 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
3927 } else { // Reset the font to default for normal bookmarks.
3928 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
3933 // Get a handle for the bookmarks list view.
3934 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
3936 // Populate the list view with the adapter.
3937 bookmarksListView.setAdapter(bookmarksCursorAdapter);
3939 // Get a handle for the bookmarks title text view.
3940 TextView bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
3942 // Set the bookmarks drawer title.
3943 if (currentBookmarksFolder.isEmpty()) {
3944 bookmarksTitleTextView.setText(R.string.bookmarks);
3946 bookmarksTitleTextView.setText(currentBookmarksFolder);
3950 private void openWithApp(String url) {
3951 // Create the open with intent with `ACTION_VIEW`.
3952 Intent openWithAppIntent = new Intent(Intent.ACTION_VIEW);
3954 // Set the URI but not the MIME type. This should open all available apps.
3955 openWithAppIntent.setData(Uri.parse(url));
3957 // Flag the intent to open in a new task.
3958 openWithAppIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3960 // Show the chooser.
3961 startActivity(openWithAppIntent);
3964 private void openWithBrowser(String url) {
3965 // Create the open with intent with `ACTION_VIEW`.
3966 Intent openWithBrowserIntent = new Intent(Intent.ACTION_VIEW);
3968 // Set the URI and the MIME type. `"text/html"` should load browser options.
3969 openWithBrowserIntent.setDataAndType(Uri.parse(url), "text/html");
3971 // Flag the intent to open in a new task.
3972 openWithBrowserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3974 // Show the chooser.
3975 startActivity(openWithBrowserIntent);
3978 private String sanitizeUrl(String url) {
3979 // Sanitize Google Analytics.
3980 if (sanitizeGoogleAnalytics) {
3982 if (url.contains("?utm_")) {
3983 url = url.substring(0, url.indexOf("?utm_"));
3987 if (url.contains("&utm_")) {
3988 url = url.substring(0, url.indexOf("&utm_"));
3992 // Sanitize Facebook Click IDs.
3993 if (sanitizeFacebookClickIds) {
3994 // Remove `?fbclid=`.
3995 if (url.contains("?fbclid=")) {
3996 url = url.substring(0, url.indexOf("?fbclid="));
3999 // Remove `&fbclid=`.
4000 if (url.contains("&fbclid=")) {
4001 url = url.substring(0, url.indexOf("&fbclid="));
4005 // Sanitize Twitter AMP redirects.
4006 if (sanitizeTwitterAmpRedirects) {
4008 if (url.contains("?amp=1")) {
4009 url = url.substring(0, url.indexOf("?amp=1"));
4013 // Return the sanitized URL.
4017 public void finishedPopulatingBlocklists(ArrayList<ArrayList<List<String[]>>> combinedBlocklists) {
4018 // Store the blocklists.
4019 easyList = combinedBlocklists.get(0);
4020 easyPrivacy = combinedBlocklists.get(1);
4021 fanboysAnnoyanceList = combinedBlocklists.get(2);
4022 fanboysSocialList = combinedBlocklists.get(3);
4023 ultraPrivacy = combinedBlocklists.get(4);
4025 // Add the first tab.
4029 public void addTab(View view) {
4030 // Add a new tab with a blank URL.
4034 private void addNewTab(String url) {
4035 // Sanitize the URL.
4036 url = sanitizeUrl(url);
4038 // Get a handle for the tab layout and the view pager.
4039 TabLayout tabLayout = findViewById(R.id.tablayout);
4040 ViewPager webViewPager = findViewById(R.id.webviewpager);
4042 // Get the new page number. The page numbers are 0 indexed, so the new page number will match the current count.
4043 int newTabNumber = tabLayout.getTabCount();
4046 tabLayout.addTab(tabLayout.newTab());
4049 TabLayout.Tab newTab = tabLayout.getTabAt(newTabNumber);
4051 // Remove the lint warning below that the current tab might be null.
4052 assert newTab != null;
4054 // Set a custom view on the new tab.
4055 newTab.setCustomView(R.layout.tab_custom_view);
4057 // Add the new WebView page.
4058 webViewPagerAdapter.addPage(newTabNumber, webViewPager, url);
4061 public void closeTab(View view) {
4062 // Get a handle for the tab layout.
4063 TabLayout tabLayout = findViewById(R.id.tablayout);
4065 // Run the command according to the number of tabs.
4066 if (tabLayout.getTabCount() > 1) { // There is more than one tab open.
4067 // Close the current tab.
4069 } else { // There is only one tab open.
4074 private void closeCurrentTab() {
4075 // Get handles for the views.
4076 AppBarLayout appBarLayout = findViewById(R.id.appbar_layout);
4077 TabLayout tabLayout = findViewById(R.id.tablayout);
4078 ViewPager webViewPager = findViewById(R.id.webviewpager);
4080 // Get the current tab number.
4081 int currentTabNumber = tabLayout.getSelectedTabPosition();
4083 // Delete the current tab.
4084 tabLayout.removeTabAt(currentTabNumber);
4086 // 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.
4087 if (webViewPagerAdapter.deletePage(currentTabNumber, webViewPager)) {
4088 setCurrentWebView(currentTabNumber);
4091 // Expand the app bar if it is currently collapsed.
4092 appBarLayout.setExpanded(true);
4095 private void clearAndExit() {
4096 // Get a handle for the shared preferences.
4097 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4099 // Close the bookmarks cursor and database.
4100 bookmarksCursor.close();
4101 bookmarksDatabaseHelper.close();
4103 // Get the status of the clear everything preference.
4104 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
4106 // Get a handle for the runtime.
4107 Runtime runtime = Runtime.getRuntime();
4109 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
4110 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
4111 String privateDataDirectoryString = getApplicationInfo().dataDir;
4114 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
4115 // The command to remove cookies changed slightly in API 21.
4116 if (Build.VERSION.SDK_INT >= 21) {
4117 CookieManager.getInstance().removeAllCookies(null);
4119 CookieManager.getInstance().removeAllCookie();
4122 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4124 // Two commands must be used because `Runtime.exec()` does not like `*`.
4125 Process deleteCookiesProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
4126 Process deleteCookiesJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
4128 // Wait until the processes have finished.
4129 deleteCookiesProcess.waitFor();
4130 deleteCookiesJournalProcess.waitFor();
4131 } catch (Exception exception) {
4132 // Do nothing if an error is thrown.
4136 // Clear DOM storage.
4137 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
4138 // Ask `WebStorage` to clear the DOM storage.
4139 WebStorage webStorage = WebStorage.getInstance();
4140 webStorage.deleteAllData();
4142 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4144 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4145 Process deleteLocalStorageProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
4147 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
4148 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
4149 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
4150 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
4151 Process deleteDatabaseProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
4153 // Wait until the processes have finished.
4154 deleteLocalStorageProcess.waitFor();
4155 deleteIndexProcess.waitFor();
4156 deleteQuotaManagerProcess.waitFor();
4157 deleteQuotaManagerJournalProcess.waitFor();
4158 deleteDatabaseProcess.waitFor();
4159 } catch (Exception exception) {
4160 // Do nothing if an error is thrown.
4164 // Clear form data if the API < 26.
4165 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
4166 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
4167 webViewDatabase.clearFormData();
4169 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4171 // A string array must be used because the database contains a space and `Runtime.exec` will not otherwise escape the string correctly.
4172 Process deleteWebDataProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
4173 Process deleteWebDataJournalProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
4175 // Wait until the processes have finished.
4176 deleteWebDataProcess.waitFor();
4177 deleteWebDataJournalProcess.waitFor();
4178 } catch (Exception exception) {
4179 // Do nothing if an error is thrown.
4184 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
4185 // Clear the cache from each WebView.
4186 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4187 // Get the WebView tab fragment.
4188 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4190 // Get the fragment view.
4191 View fragmentView = webViewTabFragment.getView();
4193 // Only clear the cache if the WebView exists.
4194 if (fragmentView != null) {
4195 // Get the nested scroll WebView from the tab fragment.
4196 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4198 // Clear the cache for this WebView.
4199 nestedScrollWebView.clearCache(true);
4203 // Manually delete the cache directories.
4205 // Delete the main cache directory.
4206 Process deleteCacheProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/cache");
4208 // Delete the secondary `Service Worker` cache directory.
4209 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4210 Process deleteServiceWorkerProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
4212 // Wait until the processes have finished.
4213 deleteCacheProcess.waitFor();
4214 deleteServiceWorkerProcess.waitFor();
4215 } catch (Exception exception) {
4216 // Do nothing if an error is thrown.
4220 // Wipe out each WebView.
4221 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4222 // Get the WebView tab fragment.
4223 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4225 // Get the fragment view.
4226 View fragmentView = webViewTabFragment.getView();
4228 // Only wipe out the WebView if it exists.
4229 if (fragmentView != null) {
4230 // Get the nested scroll WebView from the tab fragment.
4231 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4233 // Clear SSL certificate preferences for this WebView.
4234 nestedScrollWebView.clearSslPreferences();
4236 // Clear the back/forward history for this WebView.
4237 nestedScrollWebView.clearHistory();
4239 // Destroy the internal state of `mainWebView`.
4240 nestedScrollWebView.destroy();
4244 // Clear the custom headers.
4245 customHeaders.clear();
4247 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
4248 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
4249 if (clearEverything) {
4251 // Delete the folder.
4252 Process deleteAppWebviewProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
4254 // Wait until the process has finished.
4255 deleteAppWebviewProcess.waitFor();
4256 } catch (Exception exception) {
4257 // Do nothing if an error is thrown.
4261 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
4262 if (Build.VERSION.SDK_INT >= 21) {
4263 finishAndRemoveTask();
4268 // Remove the terminated program from RAM. The status code is `0`.
4272 private void setCurrentWebView(int pageNumber) {
4273 // Get a handle for the shared preferences.
4274 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4276 // Get the theme preference.
4277 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
4279 // Get handles for the URL views.
4280 RelativeLayout urlRelativeLayout = findViewById(R.id.url_relativelayout);
4281 EditText urlEditText = findViewById(R.id.url_edittext);
4282 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
4284 // Stop the swipe to refresh indicator if it is running
4285 swipeRefreshLayout.setRefreshing(false);
4287 // Get the WebView tab fragment.
4288 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(pageNumber);
4290 // Get the fragment view.
4291 View fragmentView = webViewTabFragment.getView();
4293 // Set the current WebView if the fragment view is not null.
4294 if (fragmentView != null) { // The fragment has been populated.
4295 // Store the current WebView.
4296 currentWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4298 // Update the status of swipe to refresh.
4299 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
4300 // Enable the swipe refresh layout if the WebView is scrolled all the way to the top. It is updated every time the scroll changes.
4301 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
4302 } else { // Swipe to refresh is disabled.
4303 // Disable the swipe refresh layout.
4304 swipeRefreshLayout.setEnabled(false);
4307 // Get a handle for the cookie manager.
4308 CookieManager cookieManager = CookieManager.getInstance();
4310 // Set the first-party cookie status.
4311 cookieManager.setAcceptCookie(currentWebView.getAcceptFirstPartyCookies());
4313 // Update the privacy icons. `true` redraws the icons in the app bar.
4314 updatePrivacyIcons(true);
4316 // Get a handle for the input method manager.
4317 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
4319 // Remove the lint warning below that the input method manager might be null.
4320 assert inputMethodManager != null;
4322 // Get the current URL.
4323 String url = currentWebView.getUrl();
4325 // Update the URL edit text if not loading a new intent. Otherwise, this will be handled by `onPageStarted()` (if called) and `onPageFinished()`.
4326 if (!loadingNewIntent) { // A new intent is not being loaded.
4327 if ((url == null) || url.equals("about:blank")) { // The WebView is blank.
4328 // Display the hint in the URL edit text.
4329 urlEditText.setText("");
4331 // Request focus for the URL text box.
4332 urlEditText.requestFocus();
4334 // Display the keyboard.
4335 inputMethodManager.showSoftInput(urlEditText, 0);
4336 } else { // The WebView has a loaded URL.
4337 // Clear the focus from the URL text box.
4338 urlEditText.clearFocus();
4340 // Hide the soft keyboard.
4341 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
4343 // Display the current URL in the URL text box.
4344 urlEditText.setText(url);
4346 // Highlight the URL text.
4349 } else { // A new intent is being loaded.
4350 // Reset the loading new intent tracker.
4351 loadingNewIntent = false;
4354 // Set the background to indicate the domain settings status.
4355 if (currentWebView.getDomainSettingsApplied()) {
4356 // 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.
4358 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
4360 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
4363 urlRelativeLayout.setBackground(getResources().getDrawable(R.color.transparent));
4365 } else { // The fragment has not been populated. Try again in 100 milliseconds.
4366 // Create a handler to set the current WebView.
4367 Handler setCurrentWebViewHandler = new Handler();
4369 // Create a runnable to set the current WebView.
4370 Runnable setCurrentWebWebRunnable = () -> {
4371 // Set the current WebView.
4372 setCurrentWebView(pageNumber);
4375 // Try setting the current WebView again after 100 milliseconds.
4376 setCurrentWebViewHandler.postDelayed(setCurrentWebWebRunnable, 100);
4381 public void initializeWebView(NestedScrollWebView nestedScrollWebView, int pageNumber, ProgressBar progressBar, String url) {
4382 // Get handles for the activity views.
4383 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
4384 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
4385 RelativeLayout mainContentRelativeLayout = findViewById(R.id.main_content_relativelayout);
4386 ActionBar actionBar = getSupportActionBar();
4387 LinearLayout tabsLinearLayout = findViewById(R.id.tabs_linearlayout);
4388 EditText urlEditText = findViewById(R.id.url_edittext);
4389 TabLayout tabLayout = findViewById(R.id.tablayout);
4390 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
4392 // Remove the incorrect lint warning below that the action bar might be null.
4393 assert actionBar != null;
4395 // Get a handle for the activity
4396 Activity activity = this;
4398 // Get a handle for the input method manager.
4399 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
4401 // Instantiate the blocklist helper.
4402 BlockListHelper blockListHelper = new BlockListHelper();
4404 // Remove the lint warning below that the input method manager might be null.
4405 assert inputMethodManager != null;
4407 // Get a handle for the shared preferences.
4408 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4410 // Initialize the favorite icon.
4411 nestedScrollWebView.initializeFavoriteIcon();
4413 // Set the app bar scrolling.
4414 nestedScrollWebView.setNestedScrollingEnabled(sharedPreferences.getBoolean("scroll_app_bar", true));
4416 // Allow pinch to zoom.
4417 nestedScrollWebView.getSettings().setBuiltInZoomControls(true);
4419 // Hide zoom controls.
4420 nestedScrollWebView.getSettings().setDisplayZoomControls(false);
4422 // Don't allow mixed content (HTTP and HTTPS) on the same website.
4423 if (Build.VERSION.SDK_INT >= 21) {
4424 nestedScrollWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW);
4427 // Set the WebView to load in overview mode (zoomed out to the maximum width).
4428 nestedScrollWebView.getSettings().setLoadWithOverviewMode(true);
4430 // Explicitly disable geolocation.
4431 nestedScrollWebView.getSettings().setGeolocationEnabled(false);
4433 // Create a double-tap gesture detector to toggle full-screen mode.
4434 GestureDetector doubleTapGestureDetector = new GestureDetector(getApplicationContext(), new GestureDetector.SimpleOnGestureListener() {
4435 // Override `onDoubleTap()`. All other events are handled using the default settings.
4437 public boolean onDoubleTap(MotionEvent event) {
4438 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
4439 // Toggle the full screen browsing mode tracker.
4440 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
4442 // Toggle the full screen browsing mode.
4443 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
4444 // Store the swipe refresh layout top padding.
4445 swipeRefreshLayoutPaddingTop = swipeRefreshLayout.getPaddingTop();
4447 // Hide the app bar if specified.
4449 // Close the find on page bar if it is visible.
4450 closeFindOnPage(null);
4452 // Hide the tab linear layout.
4453 tabsLinearLayout.setVisibility(View.GONE);
4455 // Hide the action bar.
4458 // Check to see if app bar scrolling is disabled.
4459 if (!scrollAppBar) {
4460 // Remove the padding from the top of the swipe refresh layout.
4461 swipeRefreshLayout.setPadding(0, 0, 0, 0);
4465 // Hide the banner ad in the free flavor.
4466 if (BuildConfig.FLAVOR.contentEquals("free")) {
4467 AdHelper.hideAd(findViewById(R.id.adview));
4470 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
4471 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4473 /* Hide the system bars.
4474 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4475 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4476 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4477 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4479 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
4480 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
4481 } else { // Switch to normal viewing mode.
4482 // Show the tab linear layout.
4483 tabsLinearLayout.setVisibility(View.VISIBLE);
4485 // Show the action bar.
4488 // Check to see if app bar scrolling is disabled.
4489 if (!scrollAppBar) {
4490 // Add the padding from the top of the swipe refresh layout.
4491 swipeRefreshLayout.setPadding(0, swipeRefreshLayoutPaddingTop, 0, 0);
4494 // Show the banner ad in the free flavor.
4495 if (BuildConfig.FLAVOR.contentEquals("free")) {
4497 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
4500 // Remove the `SYSTEM_UI` flags from the root frame layout.
4501 rootFrameLayout.setSystemUiVisibility(0);
4503 // Add the translucent status flag.
4504 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4507 // Consume the double-tap.
4509 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
4515 // Pass all touch events on the WebView through the double-tap gesture detector.
4516 nestedScrollWebView.setOnTouchListener((View view, MotionEvent event) -> {
4517 // Call `performClick()` on the view, which is required for accessibility.
4518 view.performClick();
4520 // Send the event to the gesture detector.
4521 return doubleTapGestureDetector.onTouchEvent(event);
4524 // Register the WebView for a context menu. This is used to see link targets and download images.
4525 registerForContextMenu(nestedScrollWebView);
4527 // Allow the downloading of files.
4528 nestedScrollWebView.setDownloadListener((String downloadUrl, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
4529 // Check if the download should be processed by an external app.
4530 if (sharedPreferences.getBoolean("download_with_external_app", false)) { // Download with an external app.
4531 // Create a download intent. Not specifying the action type will display the maximum number of options.
4532 Intent downloadIntent = new Intent();
4534 // Set the URI and the MIME type. Specifying `text/html` displays a good number of options.
4535 downloadIntent.setDataAndType(Uri.parse(downloadUrl), "text/html");
4537 // Flag the intent to open in a new task.
4538 downloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4540 // Show the chooser.
4541 startActivity(Intent.createChooser(downloadIntent, getString(R.string.open_with)));
4542 } else { // Download with Android's download manager.
4543 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
4544 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission has not been granted.
4545 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
4547 // Store the variables for future use by `onRequestPermissionsResult()`.
4548 this.downloadUrl = downloadUrl;
4549 downloadContentDisposition = contentDisposition;
4550 downloadContentLength = contentLength;
4552 // Show a dialog if the user has previously denied the permission.
4553 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
4554 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
4555 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
4557 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
4558 downloadLocationPermissionDialogFragment.show(getSupportFragmentManager(), getString(R.string.download_location));
4559 } else { // Show the permission request directly.
4560 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
4561 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
4563 } else { // The storage permission has already been granted.
4564 // Get a handle for the download file alert dialog.
4565 DialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(downloadUrl, contentDisposition, contentLength);
4567 // Show the download file alert dialog.
4568 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
4573 // Update the find on page count.
4574 nestedScrollWebView.setFindListener(new WebView.FindListener() {
4575 // Get a handle for `findOnPageCountTextView`.
4576 final TextView findOnPageCountTextView = findViewById(R.id.find_on_page_count_textview);
4579 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
4580 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
4581 // Set `findOnPageCountTextView` to `0/0`.
4582 findOnPageCountTextView.setText(R.string.zero_of_zero);
4583 } else if (isDoneCounting) { // There are matches.
4584 // `activeMatchOrdinal` is zero-based.
4585 int activeMatch = activeMatchOrdinal + 1;
4587 // Build the match string.
4588 String matchString = activeMatch + "/" + numberOfMatches;
4590 // Set `findOnPageCountTextView`.
4591 findOnPageCountTextView.setText(matchString);
4596 // Update the status of swipe to refresh based on the scroll position of the nested scroll WebView.
4597 // Once the minimum API >= 23 this can be replaced with `nestedScrollWebView.setOnScrollChangeListener()`.
4598 nestedScrollWebView.getViewTreeObserver().addOnScrollChangedListener(() -> {
4599 if (nestedScrollWebView.getSwipeToRefresh()) {
4600 // Only enable swipe to refresh if the WebView is scrolled to the top.
4601 swipeRefreshLayout.setEnabled(nestedScrollWebView.getScrollY() == 0);
4605 // Set the web chrome client.
4606 nestedScrollWebView.setWebChromeClient(new WebChromeClient() {
4607 // Update the progress bar when a page is loading.
4609 public void onProgressChanged(WebView view, int progress) {
4610 // Inject the night mode CSS if night mode is enabled.
4611 if (nestedScrollWebView.getNightMode()) { // Night mode is enabled.
4612 // `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
4613 // used by WordPress. `text-decoration: none` removes all text underlines. `text-shadow: none` removes text shadows, which usually have a hard coded color.
4614 // `border: none` removes all borders, which can also be used to underline text. `a {color: #1565C0}` sets links to be a dark blue.
4615 // `::selection {background: #0D47A1}' sets the text selection highlight color to be a dark blue. `!important` takes precedent over any existing sub-settings.
4616 nestedScrollWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; " +
4617 "style.innerHTML = '* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important;" +
4618 "text-shadow: none !important; border: none !important;} a {color: #1565C0 !important;} ::selection {background: #0D47A1 !important;}'; parent.appendChild(style)})()", value -> {
4619 // Initialize a handler to display `mainWebView`.
4620 Handler displayWebViewHandler = new Handler();
4622 // Setup a runnable to display `mainWebView` after a delay to allow the CSS to be applied.
4623 Runnable displayWebViewRunnable = () -> {
4624 // Only display `mainWebView` if the progress bar is gone. This prevents the display of the `WebView` while it is still loading.
4625 if (progressBar.getVisibility() == View.GONE) {
4626 nestedScrollWebView.setVisibility(View.VISIBLE);
4630 // Display the WebView after 500 milliseconds.
4631 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
4633 } else { // Night mode is disabled.
4634 // Display the nested scroll WebView if night mode is disabled.
4635 // Because of a race condition between `applyDomainSettings` and `onPageStarted`,
4636 // when night mode is set by domain settings the WebView may be hidden even if night mode is not currently enabled.
4637 nestedScrollWebView.setVisibility(View.VISIBLE);
4640 // Update the progress bar.
4641 progressBar.setProgress(progress);
4643 // Set the visibility of the progress bar.
4644 if (progress < 100) {
4645 // Show the progress bar.
4646 progressBar.setVisibility(View.VISIBLE);
4648 // Hide the progress bar.
4649 progressBar.setVisibility(View.GONE);
4651 //Stop the swipe to refresh indicator if it is running
4652 swipeRefreshLayout.setRefreshing(false);
4656 // Set the favorite icon when it changes.
4658 public void onReceivedIcon(WebView view, Bitmap icon) {
4659 // Only update the favorite icon if the website has finished loading.
4660 if (progressBar.getVisibility() == View.GONE) {
4661 // Store the new favorite icon.
4662 nestedScrollWebView.setFavoriteOrDefaultIcon(icon);
4664 // Get the current page position.
4665 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
4667 // Get the current tab.
4668 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
4670 // Check to see if the tab has been populated.
4672 // Get the custom view from the tab.
4673 View tabView = tab.getCustomView();
4675 // Check to see if the custom tab view has been populated.
4676 if (tabView != null) {
4677 // Get the favorite icon image view from the tab.
4678 ImageView tabFavoriteIconImageView = tabView.findViewById(R.id.favorite_icon_imageview);
4680 // Display the favorite icon in the tab.
4681 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
4687 // Save a copy of the title when it changes.
4689 public void onReceivedTitle(WebView view, String title) {
4690 // Get the current page position.
4691 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
4693 // Get the current tab.
4694 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
4696 // Only populate the title text view if the tab has been fully created.
4698 // Get the custom view from the tab.
4699 View tabView = tab.getCustomView();
4701 // Remove the incorrect warning below that the current tab view might be null.
4702 assert tabView != null;
4704 // Get the title text view from the tab.
4705 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
4707 // Set the title according to the URL.
4708 if (title.equals("about:blank")) {
4709 // Set the title to indicate a new tab.
4710 tabTitleTextView.setText(R.string.new_tab);
4712 // Set the title as the tab text.
4713 tabTitleTextView.setText(title);
4718 // Enter full screen video.
4720 public void onShowCustomView(View video, CustomViewCallback callback) {
4721 // Get a handle for the full screen video frame layout.
4722 FrameLayout fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
4724 // Set the full screen video flag.
4725 displayingFullScreenVideo = true;
4727 // Pause the ad if this is the free flavor.
4728 if (BuildConfig.FLAVOR.contentEquals("free")) {
4729 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
4730 AdHelper.pauseAd(findViewById(R.id.adview));
4733 // Hide the keyboard.
4734 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
4736 // Hide the main content relative layout.
4737 mainContentRelativeLayout.setVisibility(View.GONE);
4739 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
4740 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
4742 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
4743 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4745 /* Hide the system bars.
4746 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4747 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4748 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4749 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4751 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
4752 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
4754 // Disable the sliding drawers.
4755 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
4757 // Add the video view to the full screen video frame layout.
4758 fullScreenVideoFrameLayout.addView(video);
4760 // Show the full screen video frame layout.
4761 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
4764 // Exit full screen video.
4766 public void onHideCustomView() {
4767 // Get a handle for the full screen video frame layout.
4768 FrameLayout fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
4770 // Unset the full screen video flag.
4771 displayingFullScreenVideo = false;
4773 // Remove all the views from the full screen video frame layout.
4774 fullScreenVideoFrameLayout.removeAllViews();
4776 // Hide the full screen video frame layout.
4777 fullScreenVideoFrameLayout.setVisibility(View.GONE);
4779 // Enable the sliding drawers.
4780 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
4782 // Show the main content relative layout.
4783 mainContentRelativeLayout.setVisibility(View.VISIBLE);
4785 // Apply the appropriate full screen mode flags.
4786 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
4787 // Hide the app bar if specified.
4789 // Hide the tab linear layout.
4790 tabsLinearLayout.setVisibility(View.GONE);
4792 // Hide the action bar.
4796 // Hide the banner ad in the free flavor.
4797 if (BuildConfig.FLAVOR.contentEquals("free")) {
4798 AdHelper.hideAd(findViewById(R.id.adview));
4801 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
4802 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4804 /* Hide the system bars.
4805 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4806 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4807 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4808 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4810 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
4811 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
4812 } else { // Switch to normal viewing mode.
4813 // Remove the `SYSTEM_UI` flags from the root frame layout.
4814 rootFrameLayout.setSystemUiVisibility(0);
4816 // Add the translucent status flag.
4817 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4820 // Reload the ad for the free flavor if not in full screen mode.
4821 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
4823 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
4829 public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
4830 // Show the file chooser if the device is running API >= 21.
4831 if (Build.VERSION.SDK_INT >= 21) {
4832 // Store the file path callback.
4833 fileChooserCallback = filePathCallback;
4835 // Create an intent to open a chooser based ont the file chooser parameters.
4836 Intent fileChooserIntent = fileChooserParams.createIntent();
4838 // Open the file chooser. Currently only one `startActivityForResult` exists in this activity, so the request code, used to differentiate them, is simply `0`.
4839 startActivityForResult(fileChooserIntent, 0);
4845 nestedScrollWebView.setWebViewClient(new WebViewClient() {
4846 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
4847 // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
4849 public boolean shouldOverrideUrlLoading(WebView view, String url) {
4850 // Sanitize the url.
4851 url = sanitizeUrl(url);
4853 if (url.startsWith("http")) { // Load the URL in Privacy Browser.
4854 // Apply the domain settings for the new URL. This doesn't do anything if the domain has not changed.
4855 boolean userAgentChanged = applyDomainSettings(nestedScrollWebView, url, true, false);
4857 // Check if the user agent has changed.
4858 if (userAgentChanged) {
4859 // Manually load the URL. The changing of the user agent will cause WebView to reload the previous URL.
4860 nestedScrollWebView.loadUrl(url, customHeaders);
4862 // Returning true indicates that Privacy Browser is manually handling the loading of the URL.
4865 // Returning false causes the current WebView to handle the URL and prevents it from adding redirects to the history list.
4868 } else if (url.startsWith("mailto:")) { // Load the email address in an external email program.
4869 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
4870 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
4872 // Parse the url and set it as the data for the intent.
4873 emailIntent.setData(Uri.parse(url));
4875 // Open the email program in a new task instead of as part of Privacy Browser.
4876 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4879 startActivity(emailIntent);
4881 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
4883 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
4884 // Open the dialer and load the phone number, but wait for the user to place the call.
4885 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
4887 // Add the phone number to the intent.
4888 dialIntent.setData(Uri.parse(url));
4890 // Open the dialer in a new task instead of as part of Privacy Browser.
4891 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4894 startActivity(dialIntent);
4896 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
4898 } else { // Load a system chooser to select an app that can handle the URL.
4899 // Open an app that can handle the URL.
4900 Intent genericIntent = new Intent(Intent.ACTION_VIEW);
4902 // Add the URL to the intent.
4903 genericIntent.setData(Uri.parse(url));
4905 // List all apps that can handle the URL instead of just opening the first one.
4906 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
4908 // Open the app in a new task instead of as part of Privacy Browser.
4909 genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4911 // Start the app or display a snackbar if no app is available to handle the URL.
4913 startActivity(genericIntent);
4914 } catch (ActivityNotFoundException exception) {
4915 Snackbar.make(nestedScrollWebView, getString(R.string.unrecognized_url) + " " + url, Snackbar.LENGTH_SHORT).show();
4918 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
4923 // Check requests against the block lists. The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
4925 public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
4926 // Sanitize the URL.
4927 url = sanitizeUrl(url);
4929 // Get a handle for the navigation view.
4930 NavigationView navigationView = findViewById(R.id.navigationview);
4932 // Get a handle for the navigation menu.
4933 Menu navigationMenu = navigationView.getMenu();
4935 // Get a handle for the navigation requests menu item. The menu is 0 based.
4936 MenuItem navigationRequestsMenuItem = navigationMenu.getItem(5);
4938 // Create an empty web resource response to be used if the resource request is blocked.
4939 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
4941 // Reset the whitelist results tracker.
4942 String[] whitelistResultStringArray = null;
4944 // Initialize the third party request tracker.
4945 boolean isThirdPartyRequest = false;
4947 // Get the current URL. `.getUrl()` throws an error because operations on the WebView cannot be made from this thread.
4948 String currentBaseDomain = nestedScrollWebView.getCurrentDomainName();
4950 // Store a copy of the current domain for use in later requests.
4951 String currentDomain = currentBaseDomain;
4953 // Nobody is happy when comparing null strings.
4954 if ((currentBaseDomain != null) && (url != null)) {
4955 // Convert the request URL to a URI.
4956 Uri requestUri = Uri.parse(url);
4958 // Get the request host name.
4959 String requestBaseDomain = requestUri.getHost();
4961 // Only check for third-party requests if the current base domain is not empty and the request domain is not null.
4962 if (!currentBaseDomain.isEmpty() && (requestBaseDomain != null)) {
4963 // Determine the current base domain.
4964 while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
4965 // Remove the first subdomain.
4966 currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
4969 // Determine the request base domain.
4970 while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
4971 // Remove the first subdomain.
4972 requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
4975 // Update the third party request tracker.
4976 isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
4980 // Get the current WebView page position.
4981 int webViewPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
4983 // Determine if the WebView is currently displayed.
4984 boolean webViewDisplayed = (webViewPagePosition == tabLayout.getSelectedTabPosition());
4986 // Block third-party requests if enabled.
4987 if (isThirdPartyRequest && nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS)) {
4988 // Add the result to the resource requests.
4989 nestedScrollWebView.addResourceRequest(new String[]{BlockListHelper.REQUEST_THIRD_PARTY, url});
4991 // Increment the blocked requests counters.
4992 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
4993 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS);
4995 // Update the titles of the blocklist menu items if the WebView is currently displayed.
4996 if (webViewDisplayed) {
4997 // Updating the UI must be run from the UI thread.
4998 activity.runOnUiThread(() -> {
4999 // Update the menu item titles.
5000 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5002 // Update the options menu if it has been populated.
5003 if (optionsMenu != null) {
5004 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5005 optionsMenu.findItem(R.id.block_all_third_party_requests).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " +
5006 getString(R.string.block_all_third_party_requests));
5011 // Return an empty web resource response.
5012 return emptyWebResourceResponse;
5015 // Check UltraPrivacy if it is enabled.
5016 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY)) {
5017 // Check the URL against UltraPrivacy.
5018 String[] ultraPrivacyResults = blockListHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraPrivacy);
5020 // Process the UltraPrivacy results.
5021 if (ultraPrivacyResults[0].equals(BlockListHelper.REQUEST_BLOCKED)) { // The resource request matched UltraPrivacy's blacklist.
5022 // Add the result to the resource requests.
5023 nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5024 ultraPrivacyResults[5]});
5026 // Increment the blocked requests counters.
5027 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5028 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRA_PRIVACY);
5030 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5031 if (webViewDisplayed) {
5032 // Updating the UI must be run from the UI thread.
5033 activity.runOnUiThread(() -> {
5034 // Update the menu item titles.
5035 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5037 // Update the options menu if it has been populated.
5038 if (optionsMenu != null) {
5039 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5040 optionsMenu.findItem(R.id.ultraprivacy).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRA_PRIVACY) + " - " + getString(R.string.ultraprivacy));
5045 // The resource request was blocked. Return an empty web resource response.
5046 return emptyWebResourceResponse;
5047 } else if (ultraPrivacyResults[0].equals(BlockListHelper.REQUEST_ALLOWED)) { // The resource request matched UltraPrivacy's whitelist.
5048 // Add a whitelist entry to the resource requests array.
5049 nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5050 ultraPrivacyResults[5]});
5052 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
5057 // Check EasyList if it is enabled.
5058 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST)) {
5059 // Check the URL against EasyList.
5060 String[] easyListResults = blockListHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyList);
5062 // Process the EasyList results.
5063 if (easyListResults[0].equals(BlockListHelper.REQUEST_BLOCKED)) { // The resource request matched EasyList's blacklist.
5064 // Add the result to the resource requests.
5065 nestedScrollWebView.addResourceRequest(new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]});
5067 // Increment the blocked requests counters.
5068 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5069 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASY_LIST);
5071 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5072 if (webViewDisplayed) {
5073 // Updating the UI must be run from the UI thread.
5074 activity.runOnUiThread(() -> {
5075 // Update the menu item titles.
5076 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5078 // Update the options menu if it has been populated.
5079 if (optionsMenu != null) {
5080 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5081 optionsMenu.findItem(R.id.easylist).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASY_LIST) + " - " + getString(R.string.easylist));
5086 // The resource request was blocked. Return an empty web resource response.
5087 return emptyWebResourceResponse;
5088 } else if (easyListResults[0].equals(BlockListHelper.REQUEST_ALLOWED)) { // The resource request matched EasyList's whitelist.
5089 // Update the whitelist result string array tracker.
5090 whitelistResultStringArray = new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]};
5094 // Check EasyPrivacy if it is enabled.
5095 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY)) {
5096 // Check the URL against EasyPrivacy.
5097 String[] easyPrivacyResults = blockListHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyPrivacy);
5099 // Process the EasyPrivacy results.
5100 if (easyPrivacyResults[0].equals(BlockListHelper.REQUEST_BLOCKED)) { // The resource request matched EasyPrivacy's blacklist.
5101 // Add the result to the resource requests.
5102 nestedScrollWebView.addResourceRequest(new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4],
5103 easyPrivacyResults[5]});
5105 // Increment the blocked requests counters.
5106 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5107 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASY_PRIVACY);
5109 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5110 if (webViewDisplayed) {
5111 // Updating the UI must be run from the UI thread.
5112 activity.runOnUiThread(() -> {
5113 // Update the menu item titles.
5114 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5116 // Update the options menu if it has been populated.
5117 if (optionsMenu != null) {
5118 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5119 optionsMenu.findItem(R.id.easyprivacy).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASY_PRIVACY) + " - " + getString(R.string.easyprivacy));
5124 // The resource request was blocked. Return an empty web resource response.
5125 return emptyWebResourceResponse;
5126 } else if (easyPrivacyResults[0].equals(BlockListHelper.REQUEST_ALLOWED)) { // The resource request matched EasyPrivacy's whitelist.
5127 // Update the whitelist result string array tracker.
5128 whitelistResultStringArray = new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5]};
5132 // Check Fanboy’s Annoyance List if it is enabled.
5133 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST)) {
5134 // Check the URL against Fanboy's Annoyance List.
5135 String[] fanboysAnnoyanceListResults = blockListHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList);
5137 // Process the Fanboy's Annoyance List results.
5138 if (fanboysAnnoyanceListResults[0].equals(BlockListHelper.REQUEST_BLOCKED)) { // The resource request matched Fanboy's Annoyance List's blacklist.
5139 // Add the result to the resource requests.
5140 nestedScrollWebView.addResourceRequest(new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5141 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]});
5143 // Increment the blocked requests counters.
5144 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5145 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST);
5147 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5148 if (webViewDisplayed) {
5149 // Updating the UI must be run from the UI thread.
5150 activity.runOnUiThread(() -> {
5151 // Update the menu item titles.
5152 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5154 // Update the options menu if it has been populated.
5155 if (optionsMenu != null) {
5156 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5157 optionsMenu.findItem(R.id.fanboys_annoyance_list).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " +
5158 getString(R.string.fanboys_annoyance_list));
5163 // The resource request was blocked. Return an empty web resource response.
5164 return emptyWebResourceResponse;
5165 } else if (fanboysAnnoyanceListResults[0].equals(BlockListHelper.REQUEST_ALLOWED)){ // The resource request matched Fanboy's Annoyance List's whitelist.
5166 // Update the whitelist result string array tracker.
5167 whitelistResultStringArray = new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5168 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]};
5170 } else if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST)) { // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
5171 // Check the URL against Fanboy's Annoyance List.
5172 String[] fanboysSocialListResults = blockListHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysSocialList);
5174 // Process the Fanboy's Social Blocking List results.
5175 if (fanboysSocialListResults[0].equals(BlockListHelper.REQUEST_BLOCKED)) { // The resource request matched Fanboy's Social Blocking List's blacklist.
5176 // Add the result to the resource requests.
5177 nestedScrollWebView.addResourceRequest(new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5178 fanboysSocialListResults[4], fanboysSocialListResults[5]});
5180 // Increment the blocked requests counters.
5181 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5182 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST);
5184 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5185 if (webViewDisplayed) {
5186 // Updating the UI must be run from the UI thread.
5187 activity.runOnUiThread(() -> {
5188 // Update the menu item titles.
5189 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5191 // Update the options menu if it has been populated.
5192 if (optionsMenu != null) {
5193 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5194 optionsMenu.findItem(R.id.fanboys_social_blocking_list).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " +
5195 getString(R.string.fanboys_social_blocking_list));
5200 // The resource request was blocked. Return an empty web resource response.
5201 return emptyWebResourceResponse;
5202 } else if (fanboysSocialListResults[0].equals(BlockListHelper.REQUEST_ALLOWED)) { // The resource request matched Fanboy's Social Blocking List's whitelist.
5203 // Update the whitelist result string array tracker.
5204 whitelistResultStringArray = new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5205 fanboysSocialListResults[4], fanboysSocialListResults[5]};
5209 // Add the request to the log because it hasn't been processed by any of the previous checks.
5210 if (whitelistResultStringArray != null) { // The request was processed by a whitelist.
5211 nestedScrollWebView.addResourceRequest(whitelistResultStringArray);
5212 } else { // The request didn't match any blocklist entry. Log it as a default request.
5213 nestedScrollWebView.addResourceRequest(new String[]{BlockListHelper.REQUEST_DEFAULT, url});
5216 // The resource request has not been blocked. `return null` loads the requested resource.
5220 // Handle HTTP authentication requests.
5222 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
5223 // Store the handler.
5224 nestedScrollWebView.setHttpAuthHandler(handler);
5226 // Instantiate an HTTP authentication dialog.
5227 DialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm, nestedScrollWebView.getWebViewFragmentId());
5229 // Show the HTTP authentication dialog.
5230 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
5234 public void onPageStarted(WebView view, String url, Bitmap favicon) {
5235 // Get the preferences.
5236 boolean scrollAppBar = sharedPreferences.getBoolean("scroll_app_bar", true);
5237 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
5239 // Get a handler for the app bar layout.
5240 AppBarLayout appBarLayout = findViewById(R.id.appbar_layout);
5242 // Set the top padding of the swipe refresh layout according to the app bar scrolling preference.
5244 // No padding is needed because it will automatically be placed below the app bar layout due to the scrolling layout behavior.
5245 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5247 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5248 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10, defaultProgressViewEndOffset);
5250 // Get the app bar layout height. This can't be done in `applyAppSettings()` because the app bar is not yet populated.
5251 int appBarHeight = appBarLayout.getHeight();
5253 // The swipe refresh layout must be manually moved below the app bar layout.
5254 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0);
5256 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5257 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight);
5260 // Reset the list of resource requests.
5261 nestedScrollWebView.clearResourceRequests();
5263 // Reset the requests counters.
5264 nestedScrollWebView.resetRequestsCounters();
5266 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
5267 if (nestedScrollWebView.getNightMode()) {
5268 nestedScrollWebView.setVisibility(View.INVISIBLE);
5270 nestedScrollWebView.setVisibility(View.VISIBLE);
5273 // Hide the keyboard.
5274 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
5276 // Check to see if Privacy Browser is waiting on Orbot.
5277 if (!waitingForOrbot) { // Process the URL.
5278 // Get the current page position.
5279 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5281 // Update the URL text bar if the page is currently selected.
5282 if (tabLayout.getSelectedTabPosition() == currentPagePosition) {
5283 // Clear the focus from the URL edit text.
5284 urlEditText.clearFocus();
5286 // Display the formatted URL text.
5287 urlEditText.setText(url);
5289 // Apply text highlighting to `urlTextBox`.
5293 // Reset the list of host IP addresses.
5294 nestedScrollWebView.clearCurrentIpAddresses();
5296 // Get a URI for the current URL.
5297 Uri currentUri = Uri.parse(url);
5299 // Get the IP addresses for the host.
5300 new GetHostIpAddresses(activity, getSupportFragmentManager(), nestedScrollWebView).execute(currentUri.getHost());
5302 // Apply any custom domain settings if the URL was loaded by navigating history.
5303 if (nestedScrollWebView.getNavigatingHistory()) {
5304 // Reset navigating history.
5305 nestedScrollWebView.setNavigatingHistory(false);
5307 // Apply the domain settings.
5308 boolean userAgentChanged = applyDomainSettings(nestedScrollWebView, url, true, false);
5310 // Manually load the URL if the user agent has changed, which will have caused the previous URL to be reloaded.
5311 if (userAgentChanged) {
5316 // Replace Refresh with Stop if the options menu has been created. (The first WebView typically begins loading before the menu items are instantiated.)
5317 if (optionsMenu != null) {
5318 // Get a handle for the refresh menu item.
5319 MenuItem refreshMenuItem = optionsMenu.findItem(R.id.refresh);
5322 refreshMenuItem.setTitle(R.string.stop);
5324 // Get the app bar and theme preferences.
5325 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
5327 // If the icon is displayed in the AppBar, set it according to the theme.
5328 if (displayAdditionalAppBarIcons) {
5330 refreshMenuItem.setIcon(R.drawable.close_dark);
5332 refreshMenuItem.setIcon(R.drawable.close_light);
5340 public void onPageFinished(WebView view, String url) {
5341 // Flush any cookies to persistent storage. The cookie manager has become very lazy about flushing cookies in recent versions.
5342 if (nestedScrollWebView.getAcceptFirstPartyCookies() && Build.VERSION.SDK_INT >= 21) {
5343 CookieManager.getInstance().flush();
5346 // Update the Refresh menu item if the options menu has been created.
5347 if (optionsMenu != null) {
5348 // Get a handle for the refresh menu item.
5349 MenuItem refreshMenuItem = optionsMenu.findItem(R.id.refresh);
5351 // Reset the Refresh title.
5352 refreshMenuItem.setTitle(R.string.refresh);
5354 // Get the app bar and theme preferences.
5355 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
5356 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
5358 // If the icon is displayed in the AppBar, reset it according to the theme.
5359 if (displayAdditionalAppBarIcons) {
5361 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
5363 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
5368 // Clear the cache and history if Incognito Mode is enabled.
5369 if (incognitoModeEnabled) {
5370 // Clear the cache. `true` includes disk files.
5371 nestedScrollWebView.clearCache(true);
5373 // Clear the back/forward history.
5374 nestedScrollWebView.clearHistory();
5376 // Manually delete cache folders.
5378 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
5379 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
5380 String privateDataDirectoryString = getApplicationInfo().dataDir;
5382 // Delete the main cache directory.
5383 Runtime.getRuntime().exec("rm -rf " + privateDataDirectoryString + "/cache");
5385 // Delete the secondary `Service Worker` cache directory.
5386 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
5387 Runtime.getRuntime().exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
5388 } catch (IOException e) {
5389 // Do nothing if an error is thrown.
5393 // Update the URL text box and apply domain settings if not waiting on Orbot.
5394 if (!waitingForOrbot) {
5395 // Get the current page position.
5396 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5398 // Check the current website information against any pinned domain information if the current IP addresses have been loaded.
5399 if ((nestedScrollWebView.hasPinnedSslCertificate() || nestedScrollWebView.hasPinnedIpAddresses()) && nestedScrollWebView.hasCurrentIpAddresses() &&
5400 !nestedScrollWebView.ignorePinnedDomainInformation()) {
5401 CheckPinnedMismatchHelper.checkPinnedMismatch(getSupportFragmentManager(), nestedScrollWebView);
5404 // 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.
5405 String currentUrl = nestedScrollWebView.getUrl();
5407 // Get the current tab.
5408 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
5410 // Update the URL text bar if the page is currently selected and the user is not currently typing in the URL edit text.
5411 // Crash records show that, in some crazy way, it is possible for the current URL to be blank at this point.
5412 // Probably some sort of race condition when Privacy Browser is being resumed.
5413 if ((tabLayout.getSelectedTabPosition() == currentPagePosition) && !urlEditText.hasFocus() && (currentUrl != null)) {
5414 // Check to see if the URL is `about:blank`.
5415 if (currentUrl.equals("about:blank")) { // The WebView is blank.
5416 // Display the hint in the URL edit text.
5417 urlEditText.setText("");
5419 // Request focus for the URL text box.
5420 urlEditText.requestFocus();
5422 // Display the keyboard.
5423 inputMethodManager.showSoftInput(urlEditText, 0);
5425 // Apply the domain settings. This clears any settings from the previous domain.
5426 applyDomainSettings(nestedScrollWebView, "", true, false);
5428 // Only populate the title text view if the tab has been fully created.
5430 // Get the custom view from the tab.
5431 View tabView = tab.getCustomView();
5433 // Remove the incorrect warning below that the current tab view might be null.
5434 assert tabView != null;
5436 // Get the title text view from the tab.
5437 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
5439 // Set the title as the tab text.
5440 tabTitleTextView.setText(R.string.new_tab);
5442 } else { // The WebView has loaded a webpage.
5443 // Display the final URL. Getting the URL from the WebView instead of using the one provided by `onPageFinished()` makes websites like YouTube function correctly.
5444 urlEditText.setText(currentUrl);
5446 // Apply text highlighting to the URL.
5449 // Only populate the title text view if the tab has been fully created.
5451 // Get the custom view from the tab.
5452 View tabView = tab.getCustomView();
5454 // Remove the incorrect warning below that the current tab view might be null.
5455 assert tabView != null;
5457 // Get the title text view from the tab.
5458 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
5460 // Set the title as the tab text. Sometimes `onReceivedTitle()` is not called, especially when navigating history.
5461 tabTitleTextView.setText(nestedScrollWebView.getTitle());
5468 // Handle SSL Certificate errors.
5470 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
5471 // Get the current website SSL certificate.
5472 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
5474 // Extract the individual pieces of information from the current website SSL certificate.
5475 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
5476 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
5477 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
5478 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
5479 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
5480 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
5481 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
5482 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
5484 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
5485 if (nestedScrollWebView.hasPinnedSslCertificate()) {
5486 // Get the pinned SSL certificate.
5487 ArrayList<Object> pinnedSslCertificateArrayList = nestedScrollWebView.getPinnedSslCertificate();
5489 // Extract the arrays from the array list.
5490 String[] pinnedSslCertificateStringArray = (String[]) pinnedSslCertificateArrayList.get(0);
5491 Date[] pinnedSslCertificateDateArray = (Date[]) pinnedSslCertificateArrayList.get(1);
5493 // Check if the current SSL certificate matches the pinned certificate.
5494 if (currentWebsiteIssuedToCName.equals(pinnedSslCertificateStringArray[0]) && currentWebsiteIssuedToOName.equals(pinnedSslCertificateStringArray[1]) &&
5495 currentWebsiteIssuedToUName.equals(pinnedSslCertificateStringArray[2]) && currentWebsiteIssuedByCName.equals(pinnedSslCertificateStringArray[3]) &&
5496 currentWebsiteIssuedByOName.equals(pinnedSslCertificateStringArray[4]) && currentWebsiteIssuedByUName.equals(pinnedSslCertificateStringArray[5]) &&
5497 currentWebsiteSslStartDate.equals(pinnedSslCertificateDateArray[0]) && currentWebsiteSslEndDate.equals(pinnedSslCertificateDateArray[1])) {
5499 // An SSL certificate is pinned and matches the current domain certificate. Proceed to the website without displaying an error.
5502 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
5503 // Store the SSL error handler.
5504 nestedScrollWebView.setSslErrorHandler(handler);
5506 // Instantiate an SSL certificate error alert dialog.
5507 DialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error, nestedScrollWebView.getWebViewFragmentId());
5509 // Show the SSL certificate error dialog.
5510 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
5515 // Check to see if this is the first page.
5516 if (pageNumber == 0) {
5517 // Set this nested scroll WebView as the current WebView.
5518 currentWebView = nestedScrollWebView;
5520 // Apply the app settings from the shared preferences.
5523 // Load the website if not waiting for Orbot to connect.
5524 if (!waitingForOrbot) {
5525 // Get the intent that started the app.
5526 Intent launchingIntent = getIntent();
5528 // Get the information from the intent.
5529 String launchingIntentAction = launchingIntent.getAction();
5530 Uri launchingIntentUriData = launchingIntent.getData();
5532 // If the intent action is a web search, perform the search.
5533 if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) {
5534 // Create an encoded URL string.
5535 String encodedUrlString;
5537 // Sanitize the search input and convert it to a search.
5539 encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
5540 } catch (UnsupportedEncodingException exception) {
5541 encodedUrlString = "";
5544 // Load the completed search URL.
5545 loadUrl(searchURL + encodedUrlString);
5546 } else if (launchingIntentUriData != null){ // Check to see if the intent contains a new URL.
5547 // Load the URL from the intent.
5548 loadUrl(launchingIntentUriData.toString());
5549 } else { // The is no URL in the intent.
5550 // Select the homepage based on the proxy through Orbot status.
5551 if (proxyThroughOrbot) {
5552 // Load the Tor homepage.
5553 loadUrl(sharedPreferences.getString("tor_homepage", getString(R.string.tor_homepage_default_value)));
5555 // Load the normal homepage.
5556 loadUrl(sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
5560 } else { // This is not the first tab.
5561 // Apply the domain settings.
5562 applyDomainSettings(nestedScrollWebView, url, false, false);
5565 nestedScrollWebView.loadUrl(url, customHeaders);
5567 // Set the focus and display the keyboard if the URL is blank.
5568 if (url.equals("")) {
5569 // Request focus for the URL text box.
5570 urlEditText.requestFocus();
5572 // Create a display keyboard handler.
5573 Handler displayKeyboardHandler = new Handler();
5575 // Create a display keyboard runnable.
5576 Runnable displayKeyboardRunnable = () -> {
5577 // Display the keyboard.
5578 inputMethodManager.showSoftInput(urlEditText, 0);
5581 // Display the keyboard after 100 milliseconds, which leaves enough time for the tab to transition.
5582 displayKeyboardHandler.postDelayed(displayKeyboardRunnable, 100);