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.dialogs.AdConsentDialog;
119 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
120 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
121 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
122 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
123 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
124 import com.stoutner.privacybrowser.dialogs.DownloadLocationPermissionDialog;
125 import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
126 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
127 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
128 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
129 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
130 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
131 import com.stoutner.privacybrowser.fragments.WebViewTabFragment;
132 import com.stoutner.privacybrowser.helpers.AdHelper;
133 import com.stoutner.privacybrowser.helpers.BlockListHelper;
134 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
135 import com.stoutner.privacybrowser.helpers.CheckPinnedMismatchHelper;
136 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
137 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
138 import com.stoutner.privacybrowser.views.NestedScrollWebView;
140 import java.io.ByteArrayInputStream;
141 import java.io.ByteArrayOutputStream;
143 import java.io.IOException;
144 import java.io.UnsupportedEncodingException;
145 import java.net.MalformedURLException;
147 import java.net.URLDecoder;
148 import java.net.URLEncoder;
149 import java.util.ArrayList;
150 import java.util.Date;
151 import java.util.HashMap;
152 import java.util.HashSet;
153 import java.util.List;
154 import java.util.Map;
155 import java.util.Set;
157 // AppCompatActivity from android.support.v7.app.AppCompatActivity must be used to have access to the SupportActionBar until the minimum API is >= 21.
158 public class MainWebViewActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener,
159 DownloadFileDialog.DownloadFileListener, DownloadImageDialog.DownloadImageListener, DownloadLocationPermissionDialog.DownloadLocationPermissionDialogListener, EditBookmarkDialog.EditBookmarkListener,
160 EditBookmarkFolderDialog.EditBookmarkFolderListener, NavigationView.OnNavigationItemSelectedListener, WebViewTabFragment.NewTabListener {
162 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`, `onResume()`, and `applyProxyThroughOrbot()`.
163 public static String orbotStatus;
165 // The WebView pager adapter is accessed from `HttpAuthenticationDialog`, `PinnedMismatchDialog`, and `SslCertificateErrorDialog`. It is also used in `onCreate()`, `onResume()`, and `addTab()`.
166 public static WebViewPagerAdapter webViewPagerAdapter;
168 // The load URL on restart variables are public static so they can be accessed from `BookmarksActivity`. They are used in `onRestart()`.
169 public static boolean loadUrlOnRestart;
170 public static String urlToLoadOnRestart;
172 // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onRestart()`.
173 public static boolean restartFromBookmarksActivity;
175 // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`,
176 // `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
177 public static String currentBookmarksFolder;
179 // The user agent constants are public static so they can be accessed from `SettingsFragment`, `DomainsActivity`, and `DomainSettingsFragment`.
180 public final static int UNRECOGNIZED_USER_AGENT = -1;
181 public final static int SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1;
182 public final static int SETTINGS_CUSTOM_USER_AGENT = 12;
183 public final static int DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0;
184 public final static int DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2;
185 public final static int DOMAINS_CUSTOM_USER_AGENT = 13;
189 // The current WebView is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
190 // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, `applyProxyThroughOrbot()`, and `applyDomainSettings()`.
191 private NestedScrollWebView currentWebView;
193 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
194 private final Map<String, String> customHeaders = new HashMap<>();
196 // The search URL is set in `applyProxyThroughOrbot()` and used in `onCreate()`, `onNewIntent()`, `loadURLFromTextBox()`, and `initializeWebView()`.
197 private String searchURL;
199 // The options menu is set in `onCreateOptionsMenu()` and used in `onOptionsItemSelected()`, `updatePrivacyIcons()`, and `initializeWebView()`.
200 private Menu optionsMenu;
202 // The blocklists are populated in `onCreate()` and accessed from `initializeWebView()`.
203 private ArrayList<List<String[]>> easyList;
204 private ArrayList<List<String[]>> easyPrivacy;
205 private ArrayList<List<String[]>> fanboysAnnoyanceList;
206 private ArrayList<List<String[]>> fanboysSocialList;
207 private ArrayList<List<String[]>> ultraPrivacy;
209 // `webViewDefaultUserAgent` is used in `onCreate()` and `onPrepareOptionsMenu()`.
210 private String webViewDefaultUserAgent;
212 // `proxyThroughOrbot` is used in `onRestart()`, `onOptionsItemSelected()`, `applyAppSettings()`, and `applyProxyThroughOrbot()`.
213 private boolean proxyThroughOrbot;
215 // The incognito mode is set in `applyAppSettings()` and used in `initializeWebView()`.
216 private boolean incognitoModeEnabled;
218 // The full screen browsing mode tracker is set it `applyAppSettings()` and used in `initializeWebView()`.
219 private boolean fullScreenBrowsingModeEnabled;
221 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
222 private boolean inFullScreenBrowsingMode;
224 // The app bar trackers are set in `applyAppSettings()` and used in `initializeWebView()`.
225 private boolean hideAppBar;
226 private boolean scrollAppBar;
228 // The loading new intent tracker is set in `onNewIntent()` and used in `setCurrentWebView()`.
229 private boolean loadingNewIntent;
231 // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
232 private boolean reapplyDomainSettingsOnRestart;
234 // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
235 private boolean reapplyAppSettingsOnRestart;
237 // `displayingFullScreenVideo` is used in `onCreate()` and `onResume()`.
238 private boolean displayingFullScreenVideo;
240 // `orbotStatusBroadcastReceiver` is used in `onCreate()` and `onDestroy()`.
241 private BroadcastReceiver orbotStatusBroadcastReceiver;
243 // `waitingForOrbot` is used in `onCreate()`, `onResume()`, and `applyProxyThroughOrbot()`.
244 private boolean waitingForOrbot;
246 // The action bar drawer toggle is initialized in `onCreate()` and used in `onResume()`.
247 private ActionBarDrawerToggle actionBarDrawerToggle;
249 // The color spans are used in `onCreate()` and `highlightUrlText()`.
250 private ForegroundColorSpan redColorSpan;
251 private ForegroundColorSpan initialGrayColorSpan;
252 private ForegroundColorSpan finalGrayColorSpan;
254 // The drawer header padding variables are used in `onCreate()` and `onConfigurationChanged()`.
255 private int drawerHeaderPaddingLeftAndRight;
256 private int drawerHeaderPaddingTop;
257 private int drawerHeaderPaddingBottom;
259 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onDestroy`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`,
260 // and `loadBookmarksFolder()`.
261 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
263 // `bookmarksCursor` is used in `onDestroy()`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
264 private Cursor bookmarksCursor;
266 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
267 private CursorAdapter bookmarksCursorAdapter;
269 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
270 private String oldFolderNameString;
272 // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
273 private ValueCallback<Uri[]> fileChooserCallback;
275 // The default progress view offsets are set in `onCreate()` and used in `initializeWebView()`.
276 private int defaultProgressViewStartOffset;
277 private int defaultProgressViewEndOffset;
279 // The swipe refresh layout top padding is used when exiting full screen browsing mode. It is used in an inner class in `initializeWebView()`.
280 private int swipeRefreshLayoutPaddingTop;
282 // The URL sanitizers are set in `applyAppSettings()` and used in `sanitizeUrl()`.
283 private boolean sanitizeGoogleAnalytics;
284 private boolean sanitizeFacebookClickIds;
285 private boolean sanitizeTwitterAmpRedirects;
287 // The download strings are used in `onCreate()`, `onRequestPermissionResult()` and `initializeWebView()`.
288 private String downloadUrl;
289 private String downloadContentDisposition;
290 private long downloadContentLength;
292 // `downloadImageUrl` is used in `onCreateContextMenu()` and `onRequestPermissionResult()`.
293 private String downloadImageUrl;
295 // The request codes are used in `onCreate()`, `onCreateContextMenu()`, `onCloseDownloadLocationPermissionDialog()`, `onRequestPermissionResult()`, and `initializeWebView()`.
296 private final int DOWNLOAD_FILE_REQUEST_CODE = 1;
297 private final int DOWNLOAD_IMAGE_REQUEST_CODE = 2;
300 // Remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
301 @SuppressLint("ClickableViewAccessibility")
302 protected void onCreate(Bundle savedInstanceState) {
303 // Get a handle for the shared preferences.
304 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
306 // Get the theme and screenshot preferences.
307 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
308 boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
310 // Disable screenshots if not allowed.
311 if (!allowScreenshots) {
312 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
315 // Set the activity theme.
317 setTheme(R.style.PrivacyBrowserDark);
319 setTheme(R.style.PrivacyBrowserLight);
322 // Run the default commands.
323 super.onCreate(savedInstanceState);
325 // Set the content view.
326 setContentView(R.layout.main_framelayout);
328 // Get a handle for the input method.
329 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
331 // Remove the lint warning below that the input method manager might be null.
332 assert inputMethodManager != null;
334 // Get a handle for the toolbar.
335 Toolbar toolbar = findViewById(R.id.toolbar);
337 // Set the action bar. `SupportActionBar` must be used until the minimum API is >= 21.
338 setSupportActionBar(toolbar);
340 // Get a handle for the action bar.
341 ActionBar actionBar = getSupportActionBar();
343 // This is needed to get rid of the Android Studio warning that the action bar might be null.
344 assert actionBar != null;
346 // Add the custom layout, which shows the URL text bar.
347 actionBar.setCustomView(R.layout.url_app_bar);
348 actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
350 // Initialize the foreground color spans for highlighting the URLs. We have to use the deprecated `getColor()` until API >= 23.
351 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
352 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
353 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
355 // Get handles for the URL views.
356 EditText urlEditText = findViewById(R.id.url_edittext);
358 // Remove the formatting from `urlTextBar` when the user is editing the text.
359 urlEditText.setOnFocusChangeListener((View v, boolean hasFocus) -> {
360 if (hasFocus) { // The user is editing the URL text box.
361 // Remove the highlighting.
362 urlEditText.getText().removeSpan(redColorSpan);
363 urlEditText.getText().removeSpan(initialGrayColorSpan);
364 urlEditText.getText().removeSpan(finalGrayColorSpan);
365 } else { // The user has stopped editing the URL text box.
366 // Move to the beginning of the string.
367 urlEditText.setSelection(0);
369 // Reapply the highlighting.
374 // Set the go button on the keyboard to load the URL in `urlTextBox`.
375 urlEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
376 // If the event is a key-down event on the `enter` button, load the URL.
377 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
378 // Load the URL into the mainWebView and consume the event.
379 loadUrlFromTextBox();
381 // If the enter key was pressed, consume the event.
384 // If any other key was pressed, do not consume the event.
389 // Initialize the Orbot status and the waiting for Orbot trackers.
390 orbotStatus = "unknown";
391 waitingForOrbot = false;
393 // Create an Orbot status `BroadcastReceiver`.
394 orbotStatusBroadcastReceiver = new BroadcastReceiver() {
396 public void onReceive(Context context, Intent intent) {
397 // Store the content of the status message in `orbotStatus`.
398 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
400 // If Privacy Browser is waiting on Orbot, load the website now that Orbot is connected.
401 if (orbotStatus.equals("ON") && waitingForOrbot) {
402 // Reset the waiting for Orbot status.
403 waitingForOrbot = false;
405 // Get the intent that started the app.
406 Intent launchingIntent = getIntent();
408 // Get the information from the intent.
409 String launchingIntentAction = launchingIntent.getAction();
410 Uri launchingIntentUriData = launchingIntent.getData();
412 // If the intent action is a web search, perform the search.
413 if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) {
414 // Create an encoded URL string.
415 String encodedUrlString;
417 // Sanitize the search input and convert it to a search.
419 encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
420 } catch (UnsupportedEncodingException exception) {
421 encodedUrlString = "";
424 // Load the completed search URL.
425 loadUrl(searchURL + encodedUrlString);
426 } else if (launchingIntentUriData != null){ // Check to see if the intent contains a new URL.
427 // Load the URL from the intent.
428 loadUrl(launchingIntentUriData.toString());
429 } else { // The is no URL in the intent.
430 // Select the homepage based on the proxy through Orbot status.
431 if (proxyThroughOrbot) {
432 // Load the Tor homepage.
433 loadUrl(sharedPreferences.getString("tor_homepage", getString(R.string.tor_homepage_default_value)));
435 // Load the normal homepage.
436 loadUrl(sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
443 // Register `orbotStatusBroadcastReceiver` on `this` context.
444 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
446 // Instantiate the blocklist helper.
447 BlockListHelper blockListHelper = new BlockListHelper();
449 // Parse the block lists.
450 easyList = blockListHelper.parseBlockList(getAssets(), "blocklists/easylist.txt");
451 easyPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/easyprivacy.txt");
452 fanboysAnnoyanceList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-annoyance.txt");
453 fanboysSocialList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-social.txt");
454 ultraPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/ultraprivacy.txt");
456 // Get handles for views that need to be modified.
457 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
458 NavigationView navigationView = findViewById(R.id.navigationview);
459 TabLayout tabLayout = findViewById(R.id.tablayout);
460 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
461 ViewPager webViewPager = findViewById(R.id.webviewpager);
462 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
463 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
464 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
465 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
466 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
468 // Listen for touches on the navigation menu.
469 navigationView.setNavigationItemSelectedListener(this);
471 // Get handles for the navigation menu and the back and forward menu items. The menu is zero-based.
472 Menu navigationMenu = navigationView.getMenu();
473 MenuItem navigationBackMenuItem = navigationMenu.getItem(2);
474 MenuItem navigationForwardMenuItem = navigationMenu.getItem(3);
475 MenuItem navigationHistoryMenuItem = navigationMenu.getItem(4);
476 MenuItem navigationRequestsMenuItem = navigationMenu.getItem(5);
478 // Initialize the web view pager adapter.
479 webViewPagerAdapter = new WebViewPagerAdapter(getSupportFragmentManager());
481 // Set the pager adapter on the web view pager.
482 webViewPager.setAdapter(webViewPagerAdapter);
484 // Store up to 100 tabs in memory.
485 webViewPager.setOffscreenPageLimit(100);
487 // Update the web view pager every time a tab is modified.
488 webViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
490 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
495 public void onPageSelected(int position) {
496 // Close the find on page bar if it is open.
497 closeFindOnPage(null);
499 // Set the current WebView.
500 setCurrentWebView(position);
502 // 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.
503 if (tabLayout.getSelectedTabPosition() != position) {
504 // Create a handler to select the tab.
505 Handler selectTabHandler = new Handler();
507 // Create a runnable select the new tab.
508 Runnable selectTabRunnable = () -> {
509 // Get a handle for the tab.
510 TabLayout.Tab tab = tabLayout.getTabAt(position);
512 // Assert that the tab is not null.
519 // Select the tab layout after 100 milliseconds, which leaves enough time for a new tab to be created.
520 selectTabHandler.postDelayed(selectTabRunnable, 100);
525 public void onPageScrollStateChanged(int state) {
530 // Display the View SSL Certificate dialog when the currently selected tab is reselected.
531 tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
533 public void onTabSelected(TabLayout.Tab tab) {
534 // Select the same page in the view pager.
535 webViewPager.setCurrentItem(tab.getPosition());
539 public void onTabUnselected(TabLayout.Tab tab) {
544 public void onTabReselected(TabLayout.Tab tab) {
545 // Instantiate the View SSL Certificate dialog.
546 DialogFragment viewSslCertificateDialogFragment = ViewSslCertificateDialog.displayDialog(currentWebView.getWebViewFragmentId());
548 // Display the View SSL Certificate dialog.
549 viewSslCertificateDialogFragment.show(getSupportFragmentManager(), getString(R.string.view_ssl_certificate));
553 // Add the first tab.
556 // 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.
557 // The deprecated `getResources().getDrawable()` must be used until the minimum API >= 21 and and `getResources().getColor()` must be used until the minimum API >= 23.
559 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
560 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
561 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
562 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
564 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
565 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
566 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
567 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
570 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
571 launchBookmarksActivityFab.setOnClickListener(v -> {
572 // Get a copy of the favorite icon bitmap.
573 Bitmap favoriteIconBitmap = currentWebView.getFavoriteOrDefaultIcon();
575 // Create a favorite icon byte array output stream.
576 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
578 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
579 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
581 // Convert the favorite icon byte array stream to a byte array.
582 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
584 // Create an intent to launch the bookmarks activity.
585 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
587 // Add the extra information to the intent.
588 bookmarksIntent.putExtra("current_url", currentWebView.getUrl());
589 bookmarksIntent.putExtra("current_title", currentWebView.getTitle());
590 bookmarksIntent.putExtra("current_folder", currentBookmarksFolder);
591 bookmarksIntent.putExtra("favorite_icon_byte_array", favoriteIconByteArray);
594 startActivity(bookmarksIntent);
597 // Set the create new bookmark folder FAB to display an alert dialog.
598 createBookmarkFolderFab.setOnClickListener(v -> {
599 // Create a create bookmark folder dialog.
600 DialogFragment createBookmarkFolderDialog = CreateBookmarkFolderDialog.createBookmarkFolder(currentWebView.getFavoriteOrDefaultIcon());
602 // Show the create bookmark folder dialog.
603 createBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.create_folder));
606 // Set the create new bookmark FAB to display an alert dialog.
607 createBookmarkFab.setOnClickListener(view -> {
608 // Instantiate the create bookmark dialog.
609 DialogFragment createBookmarkDialog = CreateBookmarkDialog.createBookmark(currentWebView.getUrl(), currentWebView.getTitle(), currentWebView.getFavoriteOrDefaultIcon());
611 // Display the create bookmark dialog.
612 createBookmarkDialog.show(getSupportFragmentManager(), getString(R.string.create_bookmark));
615 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
616 findOnPageEditText.addTextChangedListener(new TextWatcher() {
618 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
623 public void onTextChanged(CharSequence s, int start, int before, int count) {
628 public void afterTextChanged(Editable s) {
629 // 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.
630 if (currentWebView != null) {
631 currentWebView.findAllAsync(findOnPageEditText.getText().toString());
636 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
637 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
638 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
639 // Hide the soft keyboard.
640 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
642 // Consume the event.
644 } else { // A different key was pressed.
645 // Do not consume the event.
650 // Implement swipe to refresh.
651 swipeRefreshLayout.setOnRefreshListener(() -> currentWebView.reload());
653 // Store the default progress view offsets for use later in `initializeWebView()`.
654 defaultProgressViewStartOffset = swipeRefreshLayout.getProgressViewStartOffset();
655 defaultProgressViewEndOffset = swipeRefreshLayout.getProgressViewEndOffset();
657 // Set the swipe to refresh color according to the theme.
659 swipeRefreshLayout.setColorSchemeResources(R.color.blue_800);
660 swipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.gray_850);
662 swipeRefreshLayout.setColorSchemeResources(R.color.blue_500);
665 // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
666 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
667 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
669 // Initialize the bookmarks database helper. The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
670 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
672 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
673 currentBookmarksFolder = "";
675 // Load the home folder, which is `""` in the database.
676 loadBookmarksFolder();
678 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
679 // Convert the id from long to int to match the format of the bookmarks database.
680 int databaseID = (int) id;
682 // Get the bookmark cursor for this ID and move it to the first row.
683 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseID);
684 bookmarkCursor.moveToFirst();
686 // Act upon the bookmark according to the type.
687 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
688 // Store the new folder name in `currentBookmarksFolder`.
689 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
691 // Load the new folder.
692 loadBookmarksFolder();
693 } else { // The selected bookmark is not a folder.
694 // Load the bookmark URL.
695 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
697 // Close the bookmarks drawer.
698 drawerLayout.closeDrawer(GravityCompat.END);
701 // Close the `Cursor`.
702 bookmarkCursor.close();
705 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
706 // Convert the database ID from `long` to `int`.
707 int databaseId = (int) id;
709 // Find out if the selected bookmark is a folder.
710 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
713 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
714 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
716 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
717 DialogFragment editBookmarkFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId, currentWebView.getFavoriteOrDefaultIcon());
718 editBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.edit_folder));
720 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
721 DialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId, currentWebView.getFavoriteOrDefaultIcon());
722 editBookmarkDialog.show(getSupportFragmentManager(), getString(R.string.edit_bookmark));
725 // Consume the event.
729 // Get the status bar pixel size.
730 int statusBarResourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
731 int statusBarPixelSize = getResources().getDimensionPixelSize(statusBarResourceId);
733 // Get the resource density.
734 float screenDensity = getResources().getDisplayMetrics().density;
736 // Calculate the drawer header padding. This is used to move the text in the drawer headers below any cutouts.
737 drawerHeaderPaddingLeftAndRight = (int) (15 * screenDensity);
738 drawerHeaderPaddingTop = statusBarPixelSize + (int) (4 * screenDensity);
739 drawerHeaderPaddingBottom = (int) (8 * screenDensity);
741 // The drawer listener is used to update the navigation menu.`
742 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
744 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
748 public void onDrawerOpened(@NonNull View drawerView) {
752 public void onDrawerClosed(@NonNull View drawerView) {
756 public void onDrawerStateChanged(int newState) {
757 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // A drawer is opening or closing.
758 // Get handles for the drawer headers.
759 TextView navigationHeaderTextView = findViewById(R.id.navigationText);
760 TextView bookmarksHeaderTextView = findViewById(R.id.bookmarks_title_textview);
762 // 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.
763 if (navigationHeaderTextView != null) {
764 navigationHeaderTextView.setPadding(drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingTop, drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingBottom);
767 // 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.
768 if (bookmarksHeaderTextView != null) {
769 bookmarksHeaderTextView.setPadding(drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingTop, drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingBottom);
772 // Update the navigation menu items.
773 navigationBackMenuItem.setEnabled(currentWebView.canGoBack());
774 navigationForwardMenuItem.setEnabled(currentWebView.canGoForward());
775 navigationHistoryMenuItem.setEnabled((currentWebView.canGoBack() || currentWebView.canGoForward()));
776 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
778 // Hide the keyboard (if displayed).
779 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
781 // 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.
782 urlEditText.clearFocus();
783 currentWebView.clearFocus();
788 // Create the hamburger icon at the start of the AppBar.
789 actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
791 // 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).
792 customHeaders.put("X-Requested-With", "");
794 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
795 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
797 // Inflate a bare WebView to get the default user agent. It is not used to render content on the screen.
798 @SuppressLint("InflateParams") View webViewLayout = getLayoutInflater().inflate(R.layout.bare_webview, null, false);
800 // Get a handle for the WebView.
801 WebView bareWebView = webViewLayout.findViewById(R.id.bare_webview);
803 // Store the default user agent.
804 webViewDefaultUserAgent = bareWebView.getSettings().getUserAgentString();
806 // Destroy the bare WebView.
807 bareWebView.destroy();
811 protected void onNewIntent(Intent intent) {
812 // Get the information from the intent.
813 String intentAction = intent.getAction();
814 Uri intentUriData = intent.getData();
816 // Determine if this is a web search.
817 boolean isWebSearch = ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH));
819 // 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.
820 if (intentUriData != null || isWebSearch) {
821 // Get the shared preferences.
822 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
824 // Create a URL string.
827 // If the intent action is a web search, perform the search.
829 // Create an encoded URL string.
830 String encodedUrlString;
832 // Sanitize the search input and convert it to a search.
834 encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
835 } catch (UnsupportedEncodingException exception) {
836 encodedUrlString = "";
839 // Add the base search URL.
840 url = searchURL + encodedUrlString;
841 } else { // The intent should contain a URL.
842 // Set the intent data as the URL.
843 url = intentUriData.toString();
846 // Add a new tab if specified in the preferences.
847 if (sharedPreferences.getBoolean("open_intents_in_new_tab", true)) { // Load the URL in a new tab.
848 // Set the loading new intent flag.
849 loadingNewIntent = true;
853 } else { // Load the URL in the current tab.
858 // Get a handle for the drawer layout.
859 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
861 // Close the navigation drawer if it is open.
862 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
863 drawerLayout.closeDrawer(GravityCompat.START);
866 // Close the bookmarks drawer if it is open.
867 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
868 drawerLayout.closeDrawer(GravityCompat.END);
874 public void onRestart() {
875 // Run the default commands.
878 // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
879 if (proxyThroughOrbot) {
880 // Request Orbot to start. If Orbot is already running no hard will be caused by this request.
881 Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
883 // Send the intent to the Orbot package.
884 orbotIntent.setPackage("org.torproject.android");
887 sendBroadcast(orbotIntent);
890 // Apply the app settings if returning from the Settings activity.
891 if (reapplyAppSettingsOnRestart) {
892 // Reset the reapply app settings on restart tracker.
893 reapplyAppSettingsOnRestart = false;
895 // Apply the app settings.
899 // Apply the domain settings if returning from the settings or domains activity.
900 if (reapplyDomainSettingsOnRestart) {
901 // Reset the reapply domain settings on restart tracker.
902 reapplyDomainSettingsOnRestart = false;
904 // Reapply the domain settings for each tab.
905 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
906 // Get the WebView tab fragment.
907 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
909 // Get the fragment view.
910 View fragmentView = webViewTabFragment.getView();
912 // Only reload the WebViews if they exist.
913 if (fragmentView != null) {
914 // Get the nested scroll WebView from the tab fragment.
915 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
917 // Reset the current domain name so the domain settings will be reapplied.
918 nestedScrollWebView.resetCurrentDomainName();
920 // Reapply the domain settings if the URL is not null, which can happen if an empty tab is active when returning from settings.
921 if (nestedScrollWebView.getUrl() != null) {
922 applyDomainSettings(nestedScrollWebView, nestedScrollWebView.getUrl(), false, true);
928 // Load the URL on restart (used when loading a bookmark).
929 if (loadUrlOnRestart) {
930 // Load the specified URL.
931 loadUrl(urlToLoadOnRestart);
933 // Reset the load on restart tracker.
934 loadUrlOnRestart = false;
937 // Update the bookmarks drawer if returning from the Bookmarks activity.
938 if (restartFromBookmarksActivity) {
939 // Get a handle for the drawer layout.
940 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
942 // Close the bookmarks drawer.
943 drawerLayout.closeDrawer(GravityCompat.END);
945 // Reload the bookmarks drawer.
946 loadBookmarksFolder();
948 // Reset `restartFromBookmarksActivity`.
949 restartFromBookmarksActivity = false;
952 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
953 updatePrivacyIcons(true);
956 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
958 public void onResume() {
959 // Run the default commands.
962 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
963 // Get the WebView tab fragment.
964 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
966 // Get the fragment view.
967 View fragmentView = webViewTabFragment.getView();
969 // Only resume the WebViews if they exist (they won't when the app is first created).
970 if (fragmentView != null) {
971 // Get the nested scroll WebView from the tab fragment.
972 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
974 // Resume the nested scroll WebView JavaScript timers.
975 nestedScrollWebView.resumeTimers();
977 // Resume the nested scroll WebView.
978 nestedScrollWebView.onResume();
982 // Display a message to the user if waiting for Orbot.
983 if (waitingForOrbot && !orbotStatus.equals("ON")) {
984 // Disable the wide view port so that the waiting for Orbot text is displayed correctly.
985 currentWebView.getSettings().setUseWideViewPort(false);
987 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
988 currentWebView.loadData("<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>", "text/html", null);
991 if (displayingFullScreenVideo || inFullScreenBrowsingMode) {
992 // Get a handle for the root frame layouts.
993 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
995 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
996 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
998 /* Hide the system bars.
999 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1000 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
1001 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1002 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1004 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
1005 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1006 } else if (BuildConfig.FLAVOR.contentEquals("free")) { // Resume the adView for the free flavor.
1008 AdHelper.resumeAd(findViewById(R.id.adview));
1013 public void onPause() {
1014 // Run the default commands.
1017 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
1018 // Get the WebView tab fragment.
1019 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
1021 // Get the fragment view.
1022 View fragmentView = webViewTabFragment.getView();
1024 // Only pause the WebViews if they exist (they won't when the app is first created).
1025 if (fragmentView != null) {
1026 // Get the nested scroll WebView from the tab fragment.
1027 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
1029 // Pause the nested scroll WebView.
1030 nestedScrollWebView.onPause();
1032 // Pause the nested scroll WebView JavaScript timers.
1033 nestedScrollWebView.pauseTimers();
1037 // Pause the ad or it will continue to consume resources in the background on the free flavor.
1038 if (BuildConfig.FLAVOR.contentEquals("free")) {
1040 AdHelper.pauseAd(findViewById(R.id.adview));
1045 public void onDestroy() {
1046 // Unregister the Orbot status broadcast receiver.
1047 this.unregisterReceiver(orbotStatusBroadcastReceiver);
1049 // Close the bookmarks cursor and database.
1050 bookmarksCursor.close();
1051 bookmarksDatabaseHelper.close();
1053 // Run the default commands.
1058 public boolean onCreateOptionsMenu(Menu menu) {
1059 // Inflate the menu. This adds items to the action bar if it is present.
1060 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1062 // Store a handle for the options menu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons()`.
1065 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1066 updatePrivacyIcons(false);
1068 // Get handles for the menu items.
1069 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1070 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1071 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1072 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
1073 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
1074 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1075 MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
1077 // Only display third-party cookies if API >= 21
1078 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1080 // Only display the form data menu items if the API < 26.
1081 toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1082 clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1084 // Disable the clear form data menu item if the API >= 26 so that the status of the main Clear Data is calculated correctly.
1085 clearFormDataMenuItem.setEnabled(Build.VERSION.SDK_INT < 26);
1087 // Only show Ad Consent if this is the free flavor.
1088 adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
1090 // Get the shared preferences.
1091 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1093 // Get the dark theme and app bar preferences..
1094 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
1095 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
1097 // 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.
1098 if (displayAdditionalAppBarIcons) {
1099 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1100 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1101 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
1102 } else { //Do not display the additional icons.
1103 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1104 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1105 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1108 // Replace Refresh with Stop if a URL is already loading.
1109 if (currentWebView != null && currentWebView.getProgress() != 100) {
1111 refreshMenuItem.setTitle(R.string.stop);
1113 // If the icon is displayed in the AppBar, set it according to the theme.
1114 if (displayAdditionalAppBarIcons) {
1116 refreshMenuItem.setIcon(R.drawable.close_dark);
1118 refreshMenuItem.setIcon(R.drawable.close_light);
1127 public boolean onPrepareOptionsMenu(Menu menu) {
1128 // Get handles for the menu items.
1129 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
1130 MenuItem firstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1131 MenuItem thirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1132 MenuItem domStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1133 MenuItem saveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
1134 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
1135 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1136 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1137 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
1138 MenuItem blocklistsMenuItem = menu.findItem(R.id.blocklists);
1139 MenuItem easyListMenuItem = menu.findItem(R.id.easylist);
1140 MenuItem easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
1141 MenuItem fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
1142 MenuItem fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
1143 MenuItem ultraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
1144 MenuItem blockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
1145 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1146 MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
1147 MenuItem wideViewportMenuItem = menu.findItem(R.id.wide_viewport);
1148 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1149 MenuItem nightModeMenuItem = menu.findItem(R.id.night_mode);
1150 MenuItem proxyThroughOrbotMenuItem = menu.findItem(R.id.proxy_through_orbot);
1152 // Get a handle for the cookie manager.
1153 CookieManager cookieManager = CookieManager.getInstance();
1155 // Initialize the current user agent string and the font size.
1156 String currentUserAgent = getString(R.string.user_agent_privacy_browser);
1159 // 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.
1160 if (currentWebView != null) {
1161 // Set the add or edit domain text.
1162 if (currentWebView.getDomainSettingsApplied()) {
1163 addOrEditDomain.setTitle(R.string.edit_domain_settings);
1165 addOrEditDomain.setTitle(R.string.add_domain_settings);
1168 // Get the current user agent from the WebView.
1169 currentUserAgent = currentWebView.getSettings().getUserAgentString();
1171 // Get the current font size from the
1172 fontSize = currentWebView.getSettings().getTextZoom();
1174 // Set the status of the menu item checkboxes.
1175 domStorageMenuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1176 saveFormDataMenuItem.setChecked(currentWebView.getSettings().getSaveFormData()); // Form data can be removed once the minimum API >= 26.
1177 easyListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST));
1178 easyPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY));
1179 fanboysAnnoyanceListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1180 fanboysSocialBlockingListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1181 ultraPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY));
1182 blockAllThirdPartyRequestsMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1183 swipeToRefreshMenuItem.setChecked(currentWebView.getSwipeToRefresh());
1184 wideViewportMenuItem.setChecked(currentWebView.getSettings().getUseWideViewPort());
1185 displayImagesMenuItem.setChecked(currentWebView.getSettings().getLoadsImagesAutomatically());
1186 nightModeMenuItem.setChecked(currentWebView.getNightMode());
1188 // Initialize the display names for the blocklists with the number of blocked requests.
1189 blocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
1190 easyListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASY_LIST) + " - " + getString(R.string.easylist));
1191 easyPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASY_PRIVACY) + " - " + getString(R.string.easyprivacy));
1192 fanboysAnnoyanceListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " + getString(R.string.fanboys_annoyance_list));
1193 fanboysSocialBlockingListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " + getString(R.string.fanboys_social_blocking_list));
1194 ultraPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRA_PRIVACY) + " - " + getString(R.string.ultraprivacy));
1195 blockAllThirdPartyRequestsMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " + getString(R.string.block_all_third_party_requests));
1197 // Only modify third-party cookies if the API >= 21.
1198 if (Build.VERSION.SDK_INT >= 21) {
1199 // Set the status of the third-party cookies checkbox.
1200 thirdPartyCookiesMenuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
1202 // Enable third-party cookies if first-party cookies are enabled.
1203 thirdPartyCookiesMenuItem.setEnabled(cookieManager.acceptCookie());
1206 // Enable DOM Storage if JavaScript is enabled.
1207 domStorageMenuItem.setEnabled(currentWebView.getSettings().getJavaScriptEnabled());
1210 // Set the status of the menu item checkboxes.
1211 firstPartyCookiesMenuItem.setChecked(cookieManager.acceptCookie());
1212 proxyThroughOrbotMenuItem.setChecked(proxyThroughOrbot);
1214 // Enable Clear Cookies if there are any.
1215 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1217 // 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`.
1218 String privateDataDirectoryString = getApplicationInfo().dataDir;
1220 // Get a count of the number of files in the Local Storage directory.
1221 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1222 int localStorageDirectoryNumberOfFiles = 0;
1223 if (localStorageDirectory.exists()) {
1224 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1227 // Get a count of the number of files in the IndexedDB directory.
1228 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1229 int indexedDBDirectoryNumberOfFiles = 0;
1230 if (indexedDBDirectory.exists()) {
1231 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1234 // Enable Clear DOM Storage if there is any.
1235 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1237 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
1238 if (Build.VERSION.SDK_INT < 26) {
1239 // Get the WebView database.
1240 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1242 // Enable the clear form data menu item if there is anything to clear.
1243 clearFormDataMenuItem.setEnabled(webViewDatabase.hasFormData());
1246 // Enable Clear Data if any of the submenu items are enabled.
1247 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
1249 // Disable Fanboy's Social Blocking List menu item if Fanboy's Annoyance List is checked.
1250 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListMenuItem.isChecked());
1252 // Select the current user agent menu item. A switch statement cannot be used because the user agents are not compile time constants.
1253 if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) { // Privacy Browser.
1254 menu.findItem(R.id.user_agent_privacy_browser).setChecked(true);
1255 } else if (currentUserAgent.equals(webViewDefaultUserAgent)) { // WebView Default.
1256 menu.findItem(R.id.user_agent_webview_default).setChecked(true);
1257 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) { // Firefox on Android.
1258 menu.findItem(R.id.user_agent_firefox_on_android).setChecked(true);
1259 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) { // Chrome on Android.
1260 menu.findItem(R.id.user_agent_chrome_on_android).setChecked(true);
1261 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) { // Safari on iOS.
1262 menu.findItem(R.id.user_agent_safari_on_ios).setChecked(true);
1263 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) { // Firefox on Linux.
1264 menu.findItem(R.id.user_agent_firefox_on_linux).setChecked(true);
1265 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) { // Chromium on Linux.
1266 menu.findItem(R.id.user_agent_chromium_on_linux).setChecked(true);
1267 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) { // Firefox on Windows.
1268 menu.findItem(R.id.user_agent_firefox_on_windows).setChecked(true);
1269 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) { // Chrome on Windows.
1270 menu.findItem(R.id.user_agent_chrome_on_windows).setChecked(true);
1271 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) { // Edge on Windows.
1272 menu.findItem(R.id.user_agent_edge_on_windows).setChecked(true);
1273 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) { // Internet Explorer on Windows.
1274 menu.findItem(R.id.user_agent_internet_explorer_on_windows).setChecked(true);
1275 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) { // Safari on macOS.
1276 menu.findItem(R.id.user_agent_safari_on_macos).setChecked(true);
1277 } else { // Custom user agent.
1278 menu.findItem(R.id.user_agent_custom).setChecked(true);
1281 // Instantiate the font size title and the selected font size menu item.
1282 String fontSizeTitle;
1283 MenuItem selectedFontSizeMenuItem;
1285 // Prepare the font size title and current size menu item.
1288 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
1289 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1293 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
1294 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1298 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
1299 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1303 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1304 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1308 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
1309 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1313 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
1314 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1318 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
1319 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1323 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
1324 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1328 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1329 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1333 // Set the font size title and select the current size menu item.
1334 fontSizeMenuItem.setTitle(fontSizeTitle);
1335 selectedFontSizeMenuItem.setChecked(true);
1337 // Run all the other default commands.
1338 super.onPrepareOptionsMenu(menu);
1340 // Display the menu.
1345 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1346 @SuppressLint("SetJavaScriptEnabled")
1347 public boolean onOptionsItemSelected(MenuItem menuItem) {
1348 // Reenter full screen browsing mode if it was interrupted by the options menu. <https://redmine.stoutner.com/issues/389>
1349 if (inFullScreenBrowsingMode) {
1350 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
1351 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1353 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
1355 /* Hide the system bars.
1356 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1357 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
1358 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1359 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1361 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
1362 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1365 // Get the selected menu item ID.
1366 int menuItemId = menuItem.getItemId();
1368 // Get a handle for the shared preferences.
1369 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1371 // Get a handle for the cookie manager.
1372 CookieManager cookieManager = CookieManager.getInstance();
1374 // Run the commands that correlate to the selected menu item.
1375 switch (menuItemId) {
1376 case R.id.toggle_javascript:
1377 // Toggle the JavaScript status.
1378 currentWebView.getSettings().setJavaScriptEnabled(!currentWebView.getSettings().getJavaScriptEnabled());
1380 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1381 updatePrivacyIcons(true);
1383 // Display a `Snackbar`.
1384 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScrip is enabled.
1385 Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1386 } else if (cookieManager.acceptCookie()) { // JavaScript is disabled, but first-party cookies are enabled.
1387 Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1388 } else { // Privacy mode.
1389 Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1392 // Reload the current WebView.
1393 currentWebView.reload();
1396 case R.id.add_or_edit_domain:
1397 if (currentWebView.getDomainSettingsApplied()) { // Edit the current domain settings.
1398 // Reapply the domain settings on returning to `MainWebViewActivity`.
1399 reapplyDomainSettingsOnRestart = true;
1401 // Create an intent to launch the domains activity.
1402 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1404 // Add the extra information to the intent.
1405 domainsIntent.putExtra("load_domain", currentWebView.getDomainSettingsDatabaseId());
1406 domainsIntent.putExtra("close_on_back", true);
1407 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1409 // Get the current certificate.
1410 SslCertificate sslCertificate = currentWebView.getCertificate();
1412 // Check to see if the SSL certificate is populated.
1413 if (sslCertificate != null) {
1414 // Extract the certificate to strings.
1415 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1416 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1417 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1418 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1419 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1420 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1421 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1422 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1424 // Add the certificate to the intent.
1425 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1426 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1427 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1428 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1429 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1430 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1431 domainsIntent.putExtra("ssl_start_date", startDateLong);
1432 domainsIntent.putExtra("ssl_end_date", endDateLong);
1435 // Check to see if the current IP addresses have been received.
1436 if (currentWebView.hasCurrentIpAddresses()) {
1437 // Add the current IP addresses to the intent.
1438 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1442 startActivity(domainsIntent);
1443 } else { // Add a new domain.
1444 // Apply the new domain settings on returning to `MainWebViewActivity`.
1445 reapplyDomainSettingsOnRestart = true;
1447 // Get the current domain
1448 Uri currentUri = Uri.parse(currentWebView.getUrl());
1449 String currentDomain = currentUri.getHost();
1451 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1452 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1454 // Create the domain and store the database ID.
1455 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1457 // Create an intent to launch the domains activity.
1458 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1460 // Add the extra information to the intent.
1461 domainsIntent.putExtra("load_domain", newDomainDatabaseId);
1462 domainsIntent.putExtra("close_on_back", true);
1463 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1465 // Get the current certificate.
1466 SslCertificate sslCertificate = currentWebView.getCertificate();
1468 // Check to see if the SSL certificate is populated.
1469 if (sslCertificate != null) {
1470 // Extract the certificate to strings.
1471 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1472 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1473 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1474 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1475 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1476 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1477 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1478 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1480 // Add the certificate to the intent.
1481 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1482 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1483 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1484 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1485 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1486 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1487 domainsIntent.putExtra("ssl_start_date", startDateLong);
1488 domainsIntent.putExtra("ssl_end_date", endDateLong);
1491 // Check to see if the current IP addresses have been received.
1492 if (currentWebView.hasCurrentIpAddresses()) {
1493 // Add the current IP addresses to the intent.
1494 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1498 startActivity(domainsIntent);
1502 case R.id.toggle_first_party_cookies:
1503 // Switch the first-party cookie status.
1504 cookieManager.setAcceptCookie(!cookieManager.acceptCookie());
1506 // Store the first-party cookie status.
1507 currentWebView.setAcceptFirstPartyCookies(cookieManager.acceptCookie());
1509 // Update the menu checkbox.
1510 menuItem.setChecked(cookieManager.acceptCookie());
1512 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1513 updatePrivacyIcons(true);
1515 // Display a snackbar.
1516 if (cookieManager.acceptCookie()) { // First-party cookies are enabled.
1517 Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1518 } else if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is still enabled.
1519 Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1520 } else { // Privacy mode.
1521 Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1524 // Reload the current WebView.
1525 currentWebView.reload();
1528 case R.id.toggle_third_party_cookies:
1529 if (Build.VERSION.SDK_INT >= 21) {
1530 // Switch the status of thirdPartyCookiesEnabled.
1531 cookieManager.setAcceptThirdPartyCookies(currentWebView, !cookieManager.acceptThirdPartyCookies(currentWebView));
1533 // Update the menu checkbox.
1534 menuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
1536 // Display a snackbar.
1537 if (cookieManager.acceptThirdPartyCookies(currentWebView)) {
1538 Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1540 Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1543 // Reload the current WebView.
1544 currentWebView.reload();
1545 } // Else do nothing because SDK < 21.
1548 case R.id.toggle_dom_storage:
1549 // Toggle the status of domStorageEnabled.
1550 currentWebView.getSettings().setDomStorageEnabled(!currentWebView.getSettings().getDomStorageEnabled());
1552 // Update the menu checkbox.
1553 menuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1555 // Update the privacy icon. `true` refreshes the app bar icons.
1556 updatePrivacyIcons(true);
1558 // Display a snackbar.
1559 if (currentWebView.getSettings().getDomStorageEnabled()) {
1560 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1562 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1565 // Reload the current WebView.
1566 currentWebView.reload();
1569 // Form data can be removed once the minimum API >= 26.
1570 case R.id.toggle_save_form_data:
1571 // Switch the status of saveFormDataEnabled.
1572 currentWebView.getSettings().setSaveFormData(!currentWebView.getSettings().getSaveFormData());
1574 // Update the menu checkbox.
1575 menuItem.setChecked(currentWebView.getSettings().getSaveFormData());
1577 // Display a snackbar.
1578 if (currentWebView.getSettings().getSaveFormData()) {
1579 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1581 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1584 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1585 updatePrivacyIcons(true);
1587 // Reload the current WebView.
1588 currentWebView.reload();
1591 case R.id.clear_cookies:
1592 Snackbar.make(findViewById(R.id.webviewpager), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1593 .setAction(R.string.undo, v -> {
1594 // Do nothing because everything will be handled by `onDismissed()` below.
1596 .addCallback(new Snackbar.Callback() {
1597 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1599 public void onDismissed(Snackbar snackbar, int event) {
1600 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1601 // Delete the cookies, which command varies by SDK.
1602 if (Build.VERSION.SDK_INT < 21) {
1603 cookieManager.removeAllCookie();
1605 cookieManager.removeAllCookies(null);
1613 case R.id.clear_dom_storage:
1614 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1615 .setAction(R.string.undo, v -> {
1616 // Do nothing because everything will be handled by `onDismissed()` below.
1618 .addCallback(new Snackbar.Callback() {
1619 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1621 public void onDismissed(Snackbar snackbar, int event) {
1622 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1623 // Delete the DOM Storage.
1624 WebStorage webStorage = WebStorage.getInstance();
1625 webStorage.deleteAllData();
1627 // Initialize a handler to manually delete the DOM storage files and directories.
1628 Handler deleteDomStorageHandler = new Handler();
1630 // Setup a runnable to manually delete the DOM storage files and directories.
1631 Runnable deleteDomStorageRunnable = () -> {
1633 // Get a handle for the runtime.
1634 Runtime runtime = Runtime.getRuntime();
1636 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
1637 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
1638 String privateDataDirectoryString = getApplicationInfo().dataDir;
1640 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1641 Process deleteLocalStorageProcess = runtime.exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1643 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1644 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1645 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1646 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1647 Process deleteDatabasesProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1649 // Wait for the processes to finish.
1650 deleteLocalStorageProcess.waitFor();
1651 deleteIndexProcess.waitFor();
1652 deleteQuotaManagerProcess.waitFor();
1653 deleteQuotaManagerJournalProcess.waitFor();
1654 deleteDatabasesProcess.waitFor();
1655 } catch (Exception exception) {
1656 // Do nothing if an error is thrown.
1660 // Manually delete the DOM storage files after 200 milliseconds.
1661 deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200);
1668 // Form data can be remove once the minimum API >= 26.
1669 case R.id.clear_form_data:
1670 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1671 .setAction(R.string.undo, v -> {
1672 // Do nothing because everything will be handled by `onDismissed()` below.
1674 .addCallback(new Snackbar.Callback() {
1675 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1677 public void onDismissed(Snackbar snackbar, int event) {
1678 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1679 // Delete the form data.
1680 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1681 mainWebViewDatabase.clearFormData();
1689 // Toggle the EasyList status.
1690 currentWebView.enableBlocklist(NestedScrollWebView.EASY_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST));
1692 // Update the menu checkbox.
1693 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST));
1695 // Reload the current WebView.
1696 currentWebView.reload();
1699 case R.id.easyprivacy:
1700 // Toggle the EasyPrivacy status.
1701 currentWebView.enableBlocklist(NestedScrollWebView.EASY_PRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY));
1703 // Update the menu checkbox.
1704 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY));
1706 // Reload the current WebView.
1707 currentWebView.reload();
1710 case R.id.fanboys_annoyance_list:
1711 // Toggle Fanboy's Annoyance List status.
1712 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1714 // Update the menu checkbox.
1715 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1717 // Update the staus of Fanboy's Social Blocking List.
1718 MenuItem fanboysSocialBlockingListMenuItem = optionsMenu.findItem(R.id.fanboys_social_blocking_list);
1719 fanboysSocialBlockingListMenuItem.setEnabled(!currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1721 // Reload the current WebView.
1722 currentWebView.reload();
1725 case R.id.fanboys_social_blocking_list:
1726 // Toggle Fanboy's Social Blocking List status.
1727 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1729 // Update the menu checkbox.
1730 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1732 // Reload the current WebView.
1733 currentWebView.reload();
1736 case R.id.ultraprivacy:
1737 // Toggle the UltraPrivacy status.
1738 currentWebView.enableBlocklist(NestedScrollWebView.ULTRA_PRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY));
1740 // Update the menu checkbox.
1741 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY));
1743 // Reload the current WebView.
1744 currentWebView.reload();
1747 case R.id.block_all_third_party_requests:
1748 //Toggle the third-party requests blocker status.
1749 currentWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, !currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1751 // Update the menu checkbox.
1752 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1754 // Reload the current WebView.
1755 currentWebView.reload();
1758 case R.id.user_agent_privacy_browser:
1759 // Update the user agent.
1760 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
1762 // Reload the current WebView.
1763 currentWebView.reload();
1766 case R.id.user_agent_webview_default:
1767 // Update the user agent.
1768 currentWebView.getSettings().setUserAgentString("");
1770 // Reload the current WebView.
1771 currentWebView.reload();
1774 case R.id.user_agent_firefox_on_android:
1775 // Update the user agent.
1776 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
1778 // Reload the current WebView.
1779 currentWebView.reload();
1782 case R.id.user_agent_chrome_on_android:
1783 // Update the user agent.
1784 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
1786 // Reload the current WebView.
1787 currentWebView.reload();
1790 case R.id.user_agent_safari_on_ios:
1791 // Update the user agent.
1792 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
1794 // Reload the current WebView.
1795 currentWebView.reload();
1798 case R.id.user_agent_firefox_on_linux:
1799 // Update the user agent.
1800 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
1802 // Reload the current WebView.
1803 currentWebView.reload();
1806 case R.id.user_agent_chromium_on_linux:
1807 // Update the user agent.
1808 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
1810 // Reload the current WebView.
1811 currentWebView.reload();
1814 case R.id.user_agent_firefox_on_windows:
1815 // Update the user agent.
1816 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
1818 // Reload the current WebView.
1819 currentWebView.reload();
1822 case R.id.user_agent_chrome_on_windows:
1823 // Update the user agent.
1824 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
1826 // Reload the current WebView.
1827 currentWebView.reload();
1830 case R.id.user_agent_edge_on_windows:
1831 // Update the user agent.
1832 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
1834 // Reload the current WebView.
1835 currentWebView.reload();
1838 case R.id.user_agent_internet_explorer_on_windows:
1839 // Update the user agent.
1840 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
1842 // Reload the current WebView.
1843 currentWebView.reload();
1846 case R.id.user_agent_safari_on_macos:
1847 // Update the user agent.
1848 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
1850 // Reload the current WebView.
1851 currentWebView.reload();
1854 case R.id.user_agent_custom:
1855 // Update the user agent.
1856 currentWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
1858 // Reload the current WebView.
1859 currentWebView.reload();
1862 case R.id.font_size_twenty_five_percent:
1863 currentWebView.getSettings().setTextZoom(25);
1866 case R.id.font_size_fifty_percent:
1867 currentWebView.getSettings().setTextZoom(50);
1870 case R.id.font_size_seventy_five_percent:
1871 currentWebView.getSettings().setTextZoom(75);
1874 case R.id.font_size_one_hundred_percent:
1875 currentWebView.getSettings().setTextZoom(100);
1878 case R.id.font_size_one_hundred_twenty_five_percent:
1879 currentWebView.getSettings().setTextZoom(125);
1882 case R.id.font_size_one_hundred_fifty_percent:
1883 currentWebView.getSettings().setTextZoom(150);
1886 case R.id.font_size_one_hundred_seventy_five_percent:
1887 currentWebView.getSettings().setTextZoom(175);
1890 case R.id.font_size_two_hundred_percent:
1891 currentWebView.getSettings().setTextZoom(200);
1894 case R.id.swipe_to_refresh:
1895 // Toggle the stored status of swipe to refresh.
1896 currentWebView.setSwipeToRefresh(!currentWebView.getSwipeToRefresh());
1898 // Get a handle for the swipe refresh layout.
1899 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
1901 // Update the swipe refresh layout.
1902 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
1903 if (Build.VERSION.SDK_INT >= 23) { // For API >= 23, the status of the scroll refresh listener is continuously updated by the on scroll change listener.
1904 // Only enable the swipe refresh layout if the WebView is scrolled to the top.
1905 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
1906 } else { // For API < 23, the swipe refresh layout is always enabled.
1907 // Enable the swipe refresh layout.
1908 swipeRefreshLayout.setEnabled(true);
1910 } else { // Swipe to refresh is disabled.
1911 // Disable the swipe refresh layout.
1912 swipeRefreshLayout.setEnabled(false);
1916 case R.id.wide_viewport:
1917 // Toggle the viewport.
1918 currentWebView.getSettings().setUseWideViewPort(!currentWebView.getSettings().getUseWideViewPort());
1921 case R.id.display_images:
1922 if (currentWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1923 // Disable loading of images.
1924 currentWebView.getSettings().setLoadsImagesAutomatically(false);
1926 // Reload the website to remove existing images.
1927 currentWebView.reload();
1928 } else { // Images are not currently loaded automatically.
1929 // Enable loading of images. Missing images will be loaded without the need for a reload.
1930 currentWebView.getSettings().setLoadsImagesAutomatically(true);
1934 case R.id.night_mode:
1935 // Toggle night mode.
1936 currentWebView.setNightMode(!currentWebView.getNightMode());
1938 // Enable or disable JavaScript according to night mode, the global preference, and any domain settings.
1939 if (currentWebView.getNightMode()) { // Night mode is enabled, which requires JavaScript.
1940 // Enable JavaScript.
1941 currentWebView.getSettings().setJavaScriptEnabled(true);
1942 } else if (currentWebView.getDomainSettingsApplied()) { // Night mode is disabled and domain settings are applied. Set JavaScript according to the domain settings.
1943 // Apply the JavaScript preference that was stored the last time domain settings were loaded.
1944 currentWebView.getSettings().setJavaScriptEnabled(currentWebView.getDomainSettingsJavaScriptEnabled());
1945 } else { // Night mode is disabled and domain settings are not applied. Set JavaScript according to the global preference.
1946 // Apply the JavaScript preference.
1947 currentWebView.getSettings().setJavaScriptEnabled(sharedPreferences.getBoolean("javascript", false));
1950 // Update the privacy icons.
1951 updatePrivacyIcons(false);
1953 // Reload the website.
1954 currentWebView.reload();
1957 case R.id.find_on_page:
1958 // Get a handle for the views.
1959 Toolbar toolbar = findViewById(R.id.toolbar);
1960 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
1961 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
1963 // Set the minimum height of the find on page linear layout to match the toolbar.
1964 findOnPageLinearLayout.setMinimumHeight(toolbar.getHeight());
1966 // Hide the toolbar.
1967 toolbar.setVisibility(View.GONE);
1969 // Show the find on page linear layout.
1970 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1972 // Display the keyboard. The app must wait 200 ms before running the command to work around a bug in Android.
1973 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1974 findOnPageEditText.postDelayed(() -> {
1975 // Set the focus on `findOnPageEditText`.
1976 findOnPageEditText.requestFocus();
1978 // Get a handle for the input method manager.
1979 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1981 // Remove the lint warning below that the input method manager might be null.
1982 assert inputMethodManager != null;
1984 // Display the keyboard. `0` sets no input flags.
1985 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1990 // Get a print manager instance.
1991 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1993 // Remove the lint error below that print manager might be null.
1994 assert printManager != null;
1996 // Create a print document adapter from the current WebView.
1997 PrintDocumentAdapter printDocumentAdapter = currentWebView.createPrintDocumentAdapter();
1999 // Print the document.
2000 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
2003 case R.id.add_to_homescreen:
2004 // Instantiate the create home screen shortcut dialog.
2005 DialogFragment createHomeScreenShortcutDialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView.getTitle(), currentWebView.getUrl(),
2006 currentWebView.getFavoriteOrDefaultIcon());
2008 // Show the create home screen shortcut dialog.
2009 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2012 case R.id.view_source:
2013 // Create an intent to launch the view source activity.
2014 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
2016 // Add the variables to the intent.
2017 viewSourceIntent.putExtra("user_agent", currentWebView.getSettings().getUserAgentString());
2018 viewSourceIntent.putExtra("current_url", currentWebView.getUrl());
2021 startActivity(viewSourceIntent);
2024 case R.id.share_url:
2025 // Setup the share string.
2026 String shareString = currentWebView.getTitle() + " – " + currentWebView.getUrl();
2028 // Create the share intent.
2029 Intent shareIntent = new Intent(Intent.ACTION_SEND);
2030 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
2031 shareIntent.setType("text/plain");
2034 startActivity(Intent.createChooser(shareIntent, getString(R.string.share_url)));
2037 case R.id.open_with_app:
2038 openWithApp(currentWebView.getUrl());
2041 case R.id.open_with_browser:
2042 openWithBrowser(currentWebView.getUrl());
2045 case R.id.proxy_through_orbot:
2046 // Toggle the proxy through Orbot variable.
2047 proxyThroughOrbot = !proxyThroughOrbot;
2049 // Apply the proxy through Orbot settings.
2050 applyProxyThroughOrbot(true);
2054 if (menuItem.getTitle().equals(getString(R.string.refresh))) { // The refresh button was pushed.
2055 // Reload the current WebView.
2056 currentWebView.reload();
2057 } else { // The stop button was pushed.
2058 // Stop the loading of the WebView.
2059 currentWebView.stopLoading();
2063 case R.id.ad_consent:
2064 // Display the ad consent dialog.
2065 DialogFragment adConsentDialogFragment = new AdConsentDialog();
2066 adConsentDialogFragment.show(getSupportFragmentManager(), getString(R.string.ad_consent));
2070 // Don't consume the event.
2071 return super.onOptionsItemSelected(menuItem);
2075 // removeAllCookies is deprecated, but it is required for API < 21.
2077 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2078 // Get the menu item ID.
2079 int menuItemId = menuItem.getItemId();
2081 // Get a handle for the shared preferences.
2082 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2084 // Run the commands that correspond to the selected menu item.
2085 switch (menuItemId) {
2086 case R.id.clear_and_exit:
2087 // Clear and exit Privacy Browser.
2092 // Select the homepage based on the proxy through Orbot status.
2093 if (proxyThroughOrbot) {
2094 // Load the Tor homepage.
2095 loadUrl(sharedPreferences.getString("tor_homepage", getString(R.string.tor_homepage_default_value)));
2097 // Load the normal homepage.
2098 loadUrl(sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
2103 if (currentWebView.canGoBack()) {
2104 // Reset the current domain name so that navigation works if third-party requests are blocked.
2105 currentWebView.resetCurrentDomainName();
2107 // Set navigating history so that the domain settings are applied when the new URL is loaded.
2108 currentWebView.setNavigatingHistory(true);
2110 // Load the previous website in the history.
2111 currentWebView.goBack();
2116 if (currentWebView.canGoForward()) {
2117 // Reset the current domain name so that navigation works if third-party requests are blocked.
2118 currentWebView.resetCurrentDomainName();
2120 // Set navigating history so that the domain settings are applied when the new URL is loaded.
2121 currentWebView.setNavigatingHistory(true);
2123 // Load the next website in the history.
2124 currentWebView.goForward();
2129 // Instantiate the URL history dialog.
2130 DialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(currentWebView.getWebViewFragmentId());
2132 // Show the URL history dialog.
2133 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2137 // Populate the resource requests.
2138 RequestsActivity.resourceRequests = currentWebView.getResourceRequests();
2140 // Create an intent to launch the Requests activity.
2141 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2143 // Add the block third-party requests status to the intent.
2144 requestsIntent.putExtra("block_all_third_party_requests", currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
2147 startActivity(requestsIntent);
2150 case R.id.downloads:
2151 // Launch the system Download Manager.
2152 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2154 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2155 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2157 startActivity(downloadManagerIntent);
2161 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2162 reapplyDomainSettingsOnRestart = true;
2164 // Launch the domains activity.
2165 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2167 // Add the extra information to the intent.
2168 domainsIntent.putExtra("current_url", currentWebView.getUrl());
2170 // Get the current certificate.
2171 SslCertificate sslCertificate = currentWebView.getCertificate();
2173 // Check to see if the SSL certificate is populated.
2174 if (sslCertificate != null) {
2175 // Extract the certificate to strings.
2176 String issuedToCName = sslCertificate.getIssuedTo().getCName();
2177 String issuedToOName = sslCertificate.getIssuedTo().getOName();
2178 String issuedToUName = sslCertificate.getIssuedTo().getUName();
2179 String issuedByCName = sslCertificate.getIssuedBy().getCName();
2180 String issuedByOName = sslCertificate.getIssuedBy().getOName();
2181 String issuedByUName = sslCertificate.getIssuedBy().getUName();
2182 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
2183 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
2185 // Add the certificate to the intent.
2186 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
2187 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
2188 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
2189 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
2190 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
2191 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
2192 domainsIntent.putExtra("ssl_start_date", startDateLong);
2193 domainsIntent.putExtra("ssl_end_date", endDateLong);
2196 // Check to see if the current IP addresses have been received.
2197 if (currentWebView.hasCurrentIpAddresses()) {
2198 // Add the current IP addresses to the intent.
2199 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
2203 startActivity(domainsIntent);
2207 // Set the flag to reapply app settings on restart when returning from Settings.
2208 reapplyAppSettingsOnRestart = true;
2210 // Set the flag to reapply the domain settings on restart when returning from Settings.
2211 reapplyDomainSettingsOnRestart = true;
2213 // Launch the settings activity.
2214 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2215 startActivity(settingsIntent);
2218 case R.id.import_export:
2219 // Launch the import/export activity.
2220 Intent importExportIntent = new Intent (this, ImportExportActivity.class);
2221 startActivity(importExportIntent);
2225 // Launch the logcat activity.
2226 Intent logcatIntent = new Intent(this, LogcatActivity.class);
2227 startActivity(logcatIntent);
2231 // Launch `GuideActivity`.
2232 Intent guideIntent = new Intent(this, GuideActivity.class);
2233 startActivity(guideIntent);
2237 // Create an intent to launch the about activity.
2238 Intent aboutIntent = new Intent(this, AboutActivity.class);
2240 // Create a string array for the blocklist versions.
2241 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],
2242 ultraPrivacy.get(0).get(0)[0]};
2244 // Add the blocklist versions to the intent.
2245 aboutIntent.putExtra("blocklist_versions", blocklistVersions);
2248 startActivity(aboutIntent);
2252 // Get a handle for the drawer layout.
2253 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
2255 // Close the navigation drawer.
2256 drawerLayout.closeDrawer(GravityCompat.START);
2261 public void onPostCreate(Bundle savedInstanceState) {
2262 // Run the default commands.
2263 super.onPostCreate(savedInstanceState);
2265 // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished. This creates the navigation drawer icon.
2266 actionBarDrawerToggle.syncState();
2270 public void onConfigurationChanged(Configuration newConfig) {
2271 // Run the default commands.
2272 super.onConfigurationChanged(newConfig);
2274 // Get the status bar pixel size.
2275 int statusBarResourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
2276 int statusBarPixelSize = getResources().getDimensionPixelSize(statusBarResourceId);
2278 // Get the resource density.
2279 float screenDensity = getResources().getDisplayMetrics().density;
2281 // Recalculate the drawer header padding.
2282 drawerHeaderPaddingLeftAndRight = (int) (15 * screenDensity);
2283 drawerHeaderPaddingTop = statusBarPixelSize + (int) (4 * screenDensity);
2284 drawerHeaderPaddingBottom = (int) (8 * screenDensity);
2286 // Reload the ad for the free flavor if not in full screen mode.
2287 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2288 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2289 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
2292 // `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:
2293 // https://code.google.com/p/android/issues/detail?id=20493#c8
2294 // ActivityCompat.invalidateOptionsMenu(this);
2298 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2299 // Store the hit test result.
2300 final WebView.HitTestResult hitTestResult = currentWebView.getHitTestResult();
2302 // Create the URL strings.
2303 final String imageUrl;
2304 final String linkUrl;
2306 // Get handles for the system managers.
2307 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2308 FragmentManager fragmentManager = getSupportFragmentManager();
2309 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2311 // Remove the lint errors below that the clipboard manager might be null.
2312 assert clipboardManager != null;
2314 // Process the link according to the type.
2315 switch (hitTestResult.getType()) {
2316 // `SRC_ANCHOR_TYPE` is a link.
2317 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2318 // Get the target URL.
2319 linkUrl = hitTestResult.getExtra();
2321 // Set the target URL as the title of the `ContextMenu`.
2322 menu.setHeaderTitle(linkUrl);
2324 // Add an Open in New Tab entry.
2325 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2326 // Load the link URL in a new tab.
2331 // Add an Open with App entry.
2332 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2333 openWithApp(linkUrl);
2337 // Add an Open with Browser entry.
2338 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2339 openWithBrowser(linkUrl);
2343 // Add a Copy URL entry.
2344 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2345 // Save the link URL in a `ClipData`.
2346 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2348 // Set the `ClipData` as the clipboard's primary clip.
2349 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2353 // Add a Download URL entry.
2354 menu.add(R.string.download_url).setOnMenuItemClickListener((MenuItem item) -> {
2355 // Check if the download should be processed by an external app.
2356 if (sharedPreferences.getBoolean("download_with_external_app", false)) { // Download with an external app.
2357 openUrlWithExternalApp(linkUrl);
2358 } else { // Download with Android's download manager.
2359 // Check to see if the storage permission has already been granted.
2360 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission needs to be requested.
2361 // Store the variables for future use by `onRequestPermissionsResult()`.
2362 downloadUrl = linkUrl;
2363 downloadContentDisposition = "none";
2364 downloadContentLength = -1;
2366 // Show a dialog if the user has previously denied the permission.
2367 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2368 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
2369 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
2371 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
2372 downloadLocationPermissionDialogFragment.show(fragmentManager, getString(R.string.download_location));
2373 } else { // Show the permission request directly.
2374 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
2375 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2377 } else { // The storage permission has already been granted.
2378 // Get a handle for the download file alert dialog.
2379 DialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(linkUrl, "none", -1);
2381 // Show the download file alert dialog.
2382 downloadFileDialogFragment.show(fragmentManager, getString(R.string.download));
2388 // Add a Cancel entry, which by default closes the context menu.
2389 menu.add(R.string.cancel);
2392 case WebView.HitTestResult.EMAIL_TYPE:
2393 // Get the target URL.
2394 linkUrl = hitTestResult.getExtra();
2396 // Set the target URL as the title of the `ContextMenu`.
2397 menu.setHeaderTitle(linkUrl);
2399 // Add a Write Email entry.
2400 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2401 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2402 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2404 // Parse the url and set it as the data for the `Intent`.
2405 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2407 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2408 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2411 startActivity(emailIntent);
2415 // Add a Copy Email Address entry.
2416 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2417 // Save the email address in a `ClipData`.
2418 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2420 // Set the `ClipData` as the clipboard's primary clip.
2421 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2425 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2426 menu.add(R.string.cancel);
2429 // `IMAGE_TYPE` is an image. `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link. Privacy Browser processes them the same.
2430 case WebView.HitTestResult.IMAGE_TYPE:
2431 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2432 // Get the image URL.
2433 imageUrl = hitTestResult.getExtra();
2435 // Set the image URL as the title of the context menu.
2436 menu.setHeaderTitle(imageUrl);
2438 // Add an Open in New Tab entry.
2439 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2440 // Load the image URL in a new tab.
2441 addNewTab(imageUrl);
2445 // Add a View Image entry.
2446 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2451 // Add a `Download Image` entry.
2452 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2453 // Check if the download should be processed by an external app.
2454 if (sharedPreferences.getBoolean("download_with_external_app", false)) { // Download with an external app.
2455 openUrlWithExternalApp(imageUrl);
2456 } else { // Download with Android's download manager.
2457 // Check to see if the storage permission has already been granted.
2458 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission needs to be requested.
2459 // Store the image URL for use by `onRequestPermissionResult()`.
2460 downloadImageUrl = imageUrl;
2462 // Show a dialog if the user has previously denied the permission.
2463 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2464 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2465 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2467 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
2468 downloadLocationPermissionDialogFragment.show(fragmentManager, getString(R.string.download_location));
2469 } else { // Show the permission request directly.
2470 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
2471 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2473 } else { // The storage permission has already been granted.
2474 // Get a handle for the download image alert dialog.
2475 DialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2477 // Show the download image alert dialog.
2478 downloadImageDialogFragment.show(fragmentManager, getString(R.string.download));
2484 // Add a `Copy URL` entry.
2485 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2486 // Save the image URL in a `ClipData`.
2487 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2489 // Set the `ClipData` as the clipboard's primary clip.
2490 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2494 // Add an Open with App entry.
2495 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2496 openWithApp(imageUrl);
2500 // Add an Open with Browser entry.
2501 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2502 openWithBrowser(imageUrl);
2506 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2507 menu.add(R.string.cancel);
2513 public void onCreateBookmark(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2514 // Get a handle for the bookmarks list view.
2515 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2517 // Get the views from the dialog fragment.
2518 EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
2519 EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
2521 // Extract the strings from the edit texts.
2522 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2523 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2525 // Create a favorite icon byte array output stream.
2526 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2528 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2529 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2531 // Convert the favorite icon byte array stream to a byte array.
2532 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2534 // Display the new bookmark below the current items in the (0 indexed) list.
2535 int newBookmarkDisplayOrder = bookmarksListView.getCount();
2537 // Create the bookmark.
2538 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2540 // Update the bookmarks cursor with the current contents of this folder.
2541 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2543 // Update the list view.
2544 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2546 // Scroll to the new bookmark.
2547 bookmarksListView.setSelection(newBookmarkDisplayOrder);
2551 public void onCreateBookmarkFolder(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2552 // Get a handle for the bookmarks list view.
2553 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2555 // Get handles for the views in the dialog fragment.
2556 EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
2557 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
2558 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
2560 // Get new folder name string.
2561 String folderNameString = createFolderNameEditText.getText().toString();
2563 // Create a folder icon bitmap.
2564 Bitmap folderIconBitmap;
2566 // Set the folder icon bitmap according to the dialog.
2567 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
2568 // Get the default folder icon drawable.
2569 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2571 // Convert the folder icon drawable to a bitmap drawable.
2572 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2574 // Convert the folder icon bitmap drawable to a bitmap.
2575 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2576 } else { // Use the WebView favorite icon.
2577 // Copy the favorite icon bitmap to the folder icon bitmap.
2578 folderIconBitmap = favoriteIconBitmap;
2581 // Create a folder icon byte array output stream.
2582 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2584 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2585 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2587 // Convert the folder icon byte array stream to a byte array.
2588 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2590 // Move all the bookmarks down one in the display order.
2591 for (int i = 0; i < bookmarksListView.getCount(); i++) {
2592 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2593 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2596 // Create the folder, which will be placed at the top of the `ListView`.
2597 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2599 // Update the bookmarks cursor with the current contents of this folder.
2600 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2602 // Update the `ListView`.
2603 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2605 // Scroll to the new folder.
2606 bookmarksListView.setSelection(0);
2610 public void onSaveBookmark(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, Bitmap favoriteIconBitmap) {
2611 // Get handles for the views from `dialogFragment`.
2612 EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
2613 EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
2614 RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
2616 // Store the bookmark strings.
2617 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
2618 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
2620 // Update the bookmark.
2621 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
2622 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
2623 } else { // Update the bookmark using the `WebView` favorite icon.
2624 // Create a favorite icon byte array output stream.
2625 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2627 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2628 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
2630 // Convert the favorite icon byte array stream to a byte array.
2631 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
2633 // Update the bookmark and the favorite icon.
2634 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
2637 // Update the bookmarks cursor with the current contents of this folder.
2638 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2640 // Update the list view.
2641 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2645 public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId, Bitmap favoriteIconBitmap) {
2646 // Get handles for the views from `dialogFragment`.
2647 EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
2648 RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
2649 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
2650 ImageView defaultFolderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
2652 // Get the new folder name.
2653 String newFolderNameString = editFolderNameEditText.getText().toString();
2655 // Check if the favorite icon has changed.
2656 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
2657 // Update the name in the database.
2658 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2659 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
2660 // Create the new folder icon Bitmap.
2661 Bitmap folderIconBitmap;
2663 // Populate the new folder icon bitmap.
2664 if (defaultFolderIconRadioButton.isChecked()) {
2665 // Get the default folder icon drawable.
2666 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2668 // Convert the folder icon drawable to a bitmap drawable.
2669 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2671 // Convert the folder icon bitmap drawable to a bitmap.
2672 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2673 } else { // Use the `WebView` favorite icon.
2674 // Copy the favorite icon bitmap to the folder icon bitmap.
2675 folderIconBitmap = favoriteIconBitmap;
2678 // Create a folder icon byte array output stream.
2679 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2681 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2682 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2684 // Convert the folder icon byte array stream to a byte array.
2685 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2687 // Update the folder icon in the database.
2688 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, newFolderIconByteArray);
2689 } else { // The folder icon and the name have changed.
2690 // Get the new folder icon `Bitmap`.
2691 Bitmap folderIconBitmap;
2692 if (defaultFolderIconRadioButton.isChecked()) {
2693 // Get the default folder icon drawable.
2694 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2696 // Convert the folder icon drawable to a bitmap drawable.
2697 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2699 // Convert the folder icon bitmap drawable to a bitmap.
2700 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2701 } else { // Use the `WebView` favorite icon.
2702 // Copy the favorite icon bitmap to the folder icon bitmap.
2703 folderIconBitmap = favoriteIconBitmap;
2706 // Create a folder icon byte array output stream.
2707 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2709 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2710 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2712 // Convert the folder icon byte array stream to a byte array.
2713 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2715 // Update the folder name and icon in the database.
2716 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, newFolderIconByteArray);
2719 // Update the bookmarks cursor with the current contents of this folder.
2720 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2722 // Update the `ListView`.
2723 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2727 public void onCloseDownloadLocationPermissionDialog(int downloadType) {
2728 switch (downloadType) {
2729 case DownloadLocationPermissionDialog.DOWNLOAD_FILE:
2730 // Request the WRITE_EXTERNAL_STORAGE permission with a file request code.
2731 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2734 case DownloadLocationPermissionDialog.DOWNLOAD_IMAGE:
2735 // Request the WRITE_EXTERNAL_STORAGE permission with an image request code.
2736 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2742 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
2743 // Get a handle for the fragment manager.
2744 FragmentManager fragmentManager = getSupportFragmentManager();
2746 switch (requestCode) {
2747 case DOWNLOAD_FILE_REQUEST_CODE:
2748 // Show the download file alert dialog. When the dialog closes, the correct command will be used based on the permission status.
2749 DialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(downloadUrl, downloadContentDisposition, downloadContentLength);
2751 // On API 23, displaying the fragment must be delayed or the app will crash.
2752 if (Build.VERSION.SDK_INT == 23) {
2753 new Handler().postDelayed(() -> downloadFileDialogFragment.show(fragmentManager, getString(R.string.download)), 500);
2755 downloadFileDialogFragment.show(fragmentManager, getString(R.string.download));
2758 // Reset the download variables.
2760 downloadContentDisposition = "";
2761 downloadContentLength = 0;
2764 case DOWNLOAD_IMAGE_REQUEST_CODE:
2765 // Show the download image alert dialog. When the dialog closes, the correct command will be used based on the permission status.
2766 DialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(downloadImageUrl);
2768 // On API 23, displaying the fragment must be delayed or the app will crash.
2769 if (Build.VERSION.SDK_INT == 23) {
2770 new Handler().postDelayed(() -> downloadImageDialogFragment.show(fragmentManager, getString(R.string.download)), 500);
2772 downloadImageDialogFragment.show(fragmentManager, getString(R.string.download));
2775 // Reset the image URL variable.
2776 downloadImageUrl = "";
2782 public void onDownloadImage(DialogFragment dialogFragment, String imageUrl) {
2783 // Download the image if it has an HTTP or HTTPS URI.
2784 if (imageUrl.startsWith("http")) {
2785 // Get a handle for the system `DOWNLOAD_SERVICE`.
2786 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2788 // Parse `imageUrl`.
2789 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
2791 // Get a handle for the cookie manager.
2792 CookieManager cookieManager = CookieManager.getInstance();
2794 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
2795 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2796 if (cookieManager.acceptCookie()) {
2797 // Get the cookies for `imageUrl`.
2798 String cookies = cookieManager.getCookie(imageUrl);
2800 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2801 downloadRequest.addRequestHeader("Cookie", cookies);
2804 // Get the file name from the dialog fragment.
2805 EditText downloadImageNameEditText = dialogFragment.getDialog().findViewById(R.id.download_image_name);
2806 String imageName = downloadImageNameEditText.getText().toString();
2808 // Specify the download location.
2809 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
2810 // Download to the public download directory.
2811 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, imageName);
2812 } else { // External write permission denied.
2813 // Download to the app's external download directory.
2814 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, imageName);
2817 // Allow `MediaScanner` to index the download if it is a media file.
2818 downloadRequest.allowScanningByMediaScanner();
2820 // Add the URL as the description for the download.
2821 downloadRequest.setDescription(imageUrl);
2823 // Show the download notification after the download is completed.
2824 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2826 // Remove the lint warning below that `downloadManager` might be `null`.
2827 assert downloadManager != null;
2829 // Initiate the download.
2830 downloadManager.enqueue(downloadRequest);
2831 } else { // The image is not an HTTP or HTTPS URI.
2832 Snackbar.make(currentWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
2837 public void onDownloadFile(DialogFragment dialogFragment, String downloadUrl) {
2838 // Download the file if it has an HTTP or HTTPS URI.
2839 if (downloadUrl.startsWith("http")) {
2840 // Get a handle for the system `DOWNLOAD_SERVICE`.
2841 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2843 // Parse `downloadUrl`.
2844 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
2846 // Get a handle for the cookie manager.
2847 CookieManager cookieManager = CookieManager.getInstance();
2849 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
2850 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2851 if (cookieManager.acceptCookie()) {
2852 // Get the cookies for `downloadUrl`.
2853 String cookies = cookieManager.getCookie(downloadUrl);
2855 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2856 downloadRequest.addRequestHeader("Cookie", cookies);
2859 // Get the file name from the dialog fragment.
2860 EditText downloadFileNameEditText = dialogFragment.getDialog().findViewById(R.id.download_file_name);
2861 String fileName = downloadFileNameEditText.getText().toString();
2863 // Specify the download location.
2864 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
2865 // Download to the public download directory.
2866 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
2867 } else { // External write permission denied.
2868 // Download to the app's external download directory.
2869 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, fileName);
2872 // Allow `MediaScanner` to index the download if it is a media file.
2873 downloadRequest.allowScanningByMediaScanner();
2875 // Add the URL as the description for the download.
2876 downloadRequest.setDescription(downloadUrl);
2878 // Show the download notification after the download is completed.
2879 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2881 // Remove the lint warning below that `downloadManager` might be `null`.
2882 assert downloadManager != null;
2884 // Initiate the download.
2885 downloadManager.enqueue(downloadRequest);
2886 } else { // The download is not an HTTP or HTTPS URI.
2887 Snackbar.make(currentWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
2891 // Override `onBackPressed` to handle the navigation drawer and and the WebView.
2893 public void onBackPressed() {
2894 // Get a handle for the drawer layout and the tab layout.
2895 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
2896 TabLayout tabLayout = findViewById(R.id.tablayout);
2898 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
2899 // Close the navigation drawer.
2900 drawerLayout.closeDrawer(GravityCompat.START);
2901 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
2902 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
2903 // close the bookmarks drawer.
2904 drawerLayout.closeDrawer(GravityCompat.END);
2905 } else { // A subfolder is displayed.
2906 // Place the former parent folder in `currentFolder`.
2907 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolderName(currentBookmarksFolder);
2909 // Load the new folder.
2910 loadBookmarksFolder();
2912 } else if (currentWebView.canGoBack()) { // There is at least one item in the current WebView history.
2913 // Reset the current domain name so that navigation works if third-party requests are blocked.
2914 currentWebView.resetCurrentDomainName();
2916 // Set navigating history so that the domain settings are applied when the new URL is loaded.
2917 currentWebView.setNavigatingHistory(true);
2920 currentWebView.goBack();
2921 } else if (tabLayout.getTabCount() > 1) { // There are at least two tabs.
2922 // Close the current tab.
2924 } else { // There isn't anything to do in Privacy Browser.
2925 // Run the default commands.
2926 super.onBackPressed();
2928 // Manually kill Privacy Browser. Otherwise, it is glitchy when restarted.
2933 // 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.
2935 public void onActivityResult(int requestCode, int resultCode, Intent data) {
2936 // File uploads only work on API >= 21.
2937 if (Build.VERSION.SDK_INT >= 21) {
2938 // Pass the file to the WebView.
2939 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
2943 private void loadUrlFromTextBox() {
2944 // Get a handle for the URL edit text.
2945 EditText urlEditText = findViewById(R.id.url_edittext);
2947 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
2948 String unformattedUrlString = urlEditText.getText().toString().trim();
2950 // Initialize the formatted URL string.
2953 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
2954 if (unformattedUrlString.startsWith("content://")) { // This is a Content URL.
2955 // Load the entire content URL.
2956 url = unformattedUrlString;
2957 } else if (Patterns.WEB_URL.matcher(unformattedUrlString).matches() || unformattedUrlString.startsWith("http://") || unformattedUrlString.startsWith("https://") ||
2958 unformattedUrlString.startsWith("file://")) { // This is a standard URL.
2959 // Add `https://` at the beginning if there is no protocol. Otherwise the app will segfault.
2960 if (!unformattedUrlString.startsWith("http") && !unformattedUrlString.startsWith("file://") && !unformattedUrlString.startsWith("content://")) {
2961 unformattedUrlString = "https://" + unformattedUrlString;
2964 // Initialize `unformattedUrl`.
2965 URL unformattedUrl = null;
2967 // 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.
2969 unformattedUrl = new URL(unformattedUrlString);
2970 } catch (MalformedURLException e) {
2971 e.printStackTrace();
2974 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2975 String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2976 String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2977 String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2978 String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2979 String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2982 Uri.Builder uri = new Uri.Builder();
2983 uri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2985 // Decode the URI as a UTF-8 string in.
2987 url = URLDecoder.decode(uri.build().toString(), "UTF-8");
2988 } catch (UnsupportedEncodingException exception) {
2989 // Do nothing. The formatted URL string will remain blank.
2991 } else if (!unformattedUrlString.isEmpty()){ // This is not a URL, but rather a search string.
2992 // Create an encoded URL String.
2993 String encodedUrlString;
2995 // Sanitize the search input.
2997 encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2998 } catch (UnsupportedEncodingException exception) {
2999 encodedUrlString = "";
3002 // Add the base search URL.
3003 url = searchURL + encodedUrlString;
3006 // 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.
3007 urlEditText.clearFocus();
3013 private void loadUrl(String url) {
3014 // Sanitize the URL.
3015 url = sanitizeUrl(url);
3017 // Apply the domain settings.
3018 applyDomainSettings(currentWebView, url, true, false);
3021 currentWebView.loadUrl(url, customHeaders);
3024 public void findPreviousOnPage(View view) {
3025 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
3026 currentWebView.findNext(false);
3029 public void findNextOnPage(View view) {
3030 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
3031 currentWebView.findNext(true);
3034 public void closeFindOnPage(View view) {
3035 // Get a handle for the views.
3036 Toolbar toolbar = findViewById(R.id.toolbar);
3037 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
3038 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
3040 // Delete the contents of `find_on_page_edittext`.
3041 findOnPageEditText.setText(null);
3043 // Clear the highlighted phrases if the WebView is not null.
3044 if (currentWebView != null) {
3045 currentWebView.clearMatches();
3048 // Hide the find on page linear layout.
3049 findOnPageLinearLayout.setVisibility(View.GONE);
3051 // Show the toolbar.
3052 toolbar.setVisibility(View.VISIBLE);
3054 // Get a handle for the input method manager.
3055 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
3057 // Remove the lint warning below that the input method manager might be null.
3058 assert inputMethodManager != null;
3060 // Hide the keyboard.
3061 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
3064 private void applyAppSettings() {
3065 // Get a handle for the shared preferences.
3066 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3068 // Store the values from the shared preferences in variables.
3069 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3070 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
3071 sanitizeGoogleAnalytics = sharedPreferences.getBoolean("google_analytics", true);
3072 sanitizeFacebookClickIds = sharedPreferences.getBoolean("facebook_click_ids", true);
3073 sanitizeTwitterAmpRedirects = sharedPreferences.getBoolean("twitter_amp_redirects", true);
3074 proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
3075 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3076 hideAppBar = sharedPreferences.getBoolean("hide_app_bar", true);
3077 scrollAppBar = sharedPreferences.getBoolean("scroll_app_bar", true);
3079 // Get handles for the views that need to be modified.
3080 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
3081 AppBarLayout appBarLayout = findViewById(R.id.appbar_layout);
3082 ActionBar actionBar = getSupportActionBar();
3083 Toolbar toolbar = findViewById(R.id.toolbar);
3084 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
3085 LinearLayout tabsLinearLayout = findViewById(R.id.tabs_linearlayout);
3086 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
3088 // Remove the incorrect lint warning below that the action bar might be null.
3089 assert actionBar != null;
3091 // Apply the proxy through Orbot settings.
3092 applyProxyThroughOrbot(false);
3094 // Set Do Not Track status.
3095 if (doNotTrackEnabled) {
3096 customHeaders.put("DNT", "1");
3098 customHeaders.remove("DNT");
3101 // Get the current layout parameters. Using coordinator layout parameters allows the `setBehavior()` command and using app bar layout parameters allows the `setScrollFlags()` command.
3102 CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
3103 AppBarLayout.LayoutParams toolbarLayoutParams = (AppBarLayout.LayoutParams) toolbar.getLayoutParams();
3104 AppBarLayout.LayoutParams findOnPageLayoutParams = (AppBarLayout.LayoutParams) findOnPageLinearLayout.getLayoutParams();
3105 AppBarLayout.LayoutParams tabsLayoutParams = (AppBarLayout.LayoutParams) tabsLinearLayout.getLayoutParams();
3107 // Add the scrolling behavior to the layout parameters.
3109 // Enable scrolling of the app bar.
3110 swipeRefreshLayoutParams.setBehavior(new AppBarLayout.ScrollingViewBehavior());
3111 toolbarLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3112 findOnPageLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3113 tabsLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3115 // Disable scrolling of the app bar.
3116 swipeRefreshLayoutParams.setBehavior(null);
3117 toolbarLayoutParams.setScrollFlags(0);
3118 findOnPageLayoutParams.setScrollFlags(0);
3119 tabsLayoutParams.setScrollFlags(0);
3121 // Expand the app bar if it is currently collapsed.
3122 appBarLayout.setExpanded(true);
3125 // Apply the modified layout parameters.
3126 swipeRefreshLayout.setLayoutParams(swipeRefreshLayoutParams);
3127 toolbar.setLayoutParams(toolbarLayoutParams);
3128 findOnPageLinearLayout.setLayoutParams(findOnPageLayoutParams);
3129 tabsLinearLayout.setLayoutParams(tabsLayoutParams);
3131 // Set the app bar scrolling for each WebView.
3132 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3133 // Get the WebView tab fragment.
3134 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3136 // Get the fragment view.
3137 View fragmentView = webViewTabFragment.getView();
3139 // Only modify the WebViews if they exist.
3140 if (fragmentView != null) {
3141 // Get the nested scroll WebView from the tab fragment.
3142 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3144 // Set the app bar scrolling.
3145 nestedScrollWebView.setNestedScrollingEnabled(scrollAppBar);
3149 // Update the full screen browsing mode settings.
3150 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
3151 // Update the visibility of the app bar, which might have changed in the settings.
3153 // Hide the tab linear layout.
3154 tabsLinearLayout.setVisibility(View.GONE);
3156 // Hide the action bar.
3159 // Show the tab linear layout.
3160 tabsLinearLayout.setVisibility(View.VISIBLE);
3162 // Show the action bar.
3166 // Hide the banner ad in the free flavor.
3167 if (BuildConfig.FLAVOR.contentEquals("free")) {
3168 AdHelper.hideAd(findViewById(R.id.adview));
3171 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
3172 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3174 /* Hide the system bars.
3175 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3176 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
3177 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3178 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3180 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
3181 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3182 } else { // Privacy Browser is not in full screen browsing mode.
3183 // 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.
3184 inFullScreenBrowsingMode = false;
3186 // Show the tab linear layout.
3187 tabsLinearLayout.setVisibility(View.VISIBLE);
3189 // Show the action bar.
3192 // Show the banner ad in the free flavor.
3193 if (BuildConfig.FLAVOR.contentEquals("free")) {
3194 // Initialize the ads. If this isn't the first run, `loadAd()` will be automatically called instead.
3195 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getSupportFragmentManager(), getString(R.string.google_app_id), getString(R.string.ad_unit_id));
3198 // Remove the `SYSTEM_UI` flags from the root frame layout.
3199 rootFrameLayout.setSystemUiVisibility(0);
3201 // Add the translucent status flag.
3202 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3207 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
3208 @SuppressLint("SetJavaScriptEnabled")
3209 private boolean applyDomainSettings(NestedScrollWebView nestedScrollWebView, String url, boolean resetTab, boolean reloadWebsite) {
3210 // Store a copy of the current user agent to track changes for the return boolean.
3211 String initialUserAgent = nestedScrollWebView.getSettings().getUserAgentString();
3213 // Parse the URL into a URI.
3214 Uri uri = Uri.parse(url);
3216 // Extract the domain from `uri`.
3217 String newHostName = uri.getHost();
3219 // Strings don't like to be null.
3220 if (newHostName == null) {
3224 // 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.
3225 if (!nestedScrollWebView.getCurrentDomainName().equals(newHostName) || newHostName.equals("")) {
3226 // Set the new host name as the current domain name.
3227 nestedScrollWebView.setCurrentDomainName(newHostName);
3229 // Reset the ignoring of pinned domain information.
3230 nestedScrollWebView.setIgnorePinnedDomainInformation(false);
3232 // Clear any pinned SSL certificate or IP addresses.
3233 nestedScrollWebView.clearPinnedSslCertificate();
3234 nestedScrollWebView.clearPinnedIpAddresses();
3236 // Reset the favorite icon if specified.
3238 // Initialize the favorite icon.
3239 nestedScrollWebView.initializeFavoriteIcon();
3241 // Get the current page position.
3242 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
3244 // Get a handle for the tab layout.
3245 TabLayout tabLayout = findViewById(R.id.tablayout);
3247 // Get the corresponding tab.
3248 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
3250 // Update the tab if it isn't null, which sometimes happens when restarting from the background.
3252 // Get the tab custom view.
3253 View tabCustomView = tab.getCustomView();
3255 // Remove the warning below that the tab custom view might be null.
3256 assert tabCustomView != null;
3258 // Get the tab views.
3259 ImageView tabFavoriteIconImageView = tabCustomView.findViewById(R.id.favorite_icon_imageview);
3260 TextView tabTitleTextView = tabCustomView.findViewById(R.id.title_textview);
3262 // Set the default favorite icon as the favorite icon for this tab.
3263 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(nestedScrollWebView.getFavoriteOrDefaultIcon(), 64, 64, true));
3265 // Set the loading title text.
3266 tabTitleTextView.setText(R.string.loading);
3270 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3271 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3273 // Get a full cursor from `domainsDatabaseHelper`.
3274 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3276 // Initialize `domainSettingsSet`.
3277 Set<String> domainSettingsSet = new HashSet<>();
3279 // Get the domain name column index.
3280 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3282 // Populate `domainSettingsSet`.
3283 for (int i = 0; i < domainNameCursor.getCount(); i++) {
3284 // Move `domainsCursor` to the current row.
3285 domainNameCursor.moveToPosition(i);
3287 // Store the domain name in `domainSettingsSet`.
3288 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3291 // Close `domainNameCursor.
3292 domainNameCursor.close();
3294 // Initialize the domain name in database variable.
3295 String domainNameInDatabase = null;
3297 // Check the hostname against the domain settings set.
3298 if (domainSettingsSet.contains(newHostName)) { // The hostname is contained in the domain settings set.
3299 // Record the domain name in the database.
3300 domainNameInDatabase = newHostName;
3302 // Set the domain settings applied tracker to true.
3303 nestedScrollWebView.setDomainSettingsApplied(true);
3304 } else { // The hostname is not contained in the domain settings set.
3305 // Set the domain settings applied tracker to false.
3306 nestedScrollWebView.setDomainSettingsApplied(false);
3309 // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3310 while (!nestedScrollWebView.getDomainSettingsApplied() && newHostName.contains(".")) { // Stop checking if domain settings are already applied or there are no more `.` in the host name.
3311 if (domainSettingsSet.contains("*." + newHostName)) { // Check the host name prepended by `*.`.
3312 // Set the domain settings applied tracker to true.
3313 nestedScrollWebView.setDomainSettingsApplied(true);
3315 // Store the applied domain names as it appears in the database.
3316 domainNameInDatabase = "*." + newHostName;
3319 // Strip out the lowest subdomain of of the host name.
3320 newHostName = newHostName.substring(newHostName.indexOf(".") + 1);
3324 // Get a handle for the shared preferences.
3325 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3327 // Store the general preference information.
3328 String defaultFontSizeString = sharedPreferences.getString("font_size", getString(R.string.font_size_default_value));
3329 String defaultUserAgentName = sharedPreferences.getString("user_agent", getString(R.string.user_agent_default_value));
3330 boolean defaultSwipeToRefresh = sharedPreferences.getBoolean("swipe_to_refresh", true);
3331 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
3332 boolean wideViewport = sharedPreferences.getBoolean("wide_viewport", true);
3333 boolean displayWebpageImages = sharedPreferences.getBoolean("display_webpage_images", true);
3335 // Get a handle for the cookie manager.
3336 CookieManager cookieManager = CookieManager.getInstance();
3338 // Get handles for the views.
3339 RelativeLayout urlRelativeLayout = findViewById(R.id.url_relativelayout);
3340 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
3342 // Initialize the user agent array adapter and string array.
3343 ArrayAdapter<CharSequence> userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item);
3344 String[] userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
3346 if (nestedScrollWebView.getDomainSettingsApplied()) { // The url has custom domain settings.
3347 // Get a cursor for the current host and move it to the first position.
3348 Cursor currentDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3349 currentDomainSettingsCursor.moveToFirst();
3351 // Get the settings from the cursor.
3352 nestedScrollWebView.setDomainSettingsDatabaseId(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3353 nestedScrollWebView.setDomainSettingsJavaScriptEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3354 nestedScrollWebView.setAcceptFirstPartyCookies(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3355 boolean domainThirdPartyCookiesEnabled = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3356 nestedScrollWebView.getSettings().setDomStorageEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3357 // Form data can be removed once the minimum API >= 26.
3358 boolean saveFormData = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3359 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASY_LIST,
3360 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3361 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASY_PRIVACY,
3362 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3363 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST,
3364 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3365 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST,
3366 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3367 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRA_PRIVACY,
3368 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_ULTRAPRIVACY)) == 1);
3369 nestedScrollWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS,
3370 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
3371 String userAgentName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3372 int fontSize = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3373 int swipeToRefreshInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
3374 int nightModeInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
3375 int wideViewportInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.WIDE_VIEWPORT));
3376 int displayWebpageImagesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3377 boolean pinnedSslCertificate = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3378 String pinnedSslIssuedToCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3379 String pinnedSslIssuedToOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3380 String pinnedSslIssuedToUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3381 String pinnedSslIssuedByCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3382 String pinnedSslIssuedByOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3383 String pinnedSslIssuedByUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3384 boolean pinnedIpAddresses = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_IP_ADDRESSES)) == 1);
3385 String pinnedHostIpAddresses = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.IP_ADDRESSES));
3387 // Create the pinned SSL date variables.
3388 Date pinnedSslStartDate;
3389 Date pinnedSslEndDate;
3391 // 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.
3392 if (currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
3393 pinnedSslStartDate = null;
3395 pinnedSslStartDate = new Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
3398 // 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.
3399 if (currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
3400 pinnedSslEndDate = null;
3402 pinnedSslEndDate = new Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
3405 // If there is a pinned SSL certificate, store it in the WebView.
3406 if (pinnedSslCertificate) {
3407 nestedScrollWebView.setPinnedSslCertificate(pinnedSslIssuedToCName, pinnedSslIssuedToOName, pinnedSslIssuedToUName, pinnedSslIssuedByCName, pinnedSslIssuedByOName, pinnedSslIssuedByUName,
3408 pinnedSslStartDate, pinnedSslEndDate);
3411 // If there is a pinned IP address, store it in the WebView.
3412 if (pinnedIpAddresses) {
3413 nestedScrollWebView.setPinnedIpAddresses(pinnedHostIpAddresses);
3416 // Set night mode according to the night mode int.
3417 switch (nightModeInt) {
3418 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
3419 // Set night mode according to the current default.
3420 nestedScrollWebView.setNightMode(sharedPreferences.getBoolean("night_mode", false));
3423 case DomainsDatabaseHelper.ENABLED:
3424 // Enable night mode.
3425 nestedScrollWebView.setNightMode(true);
3428 case DomainsDatabaseHelper.DISABLED:
3429 // Disable night mode.
3430 nestedScrollWebView.setNightMode(false);
3434 // Enable JavaScript if night mode is enabled.
3435 if (nestedScrollWebView.getNightMode()) {
3436 // Enable JavaScript.
3437 nestedScrollWebView.getSettings().setJavaScriptEnabled(true);
3439 // Set JavaScript according to the domain settings.
3440 nestedScrollWebView.getSettings().setJavaScriptEnabled(nestedScrollWebView.getDomainSettingsJavaScriptEnabled());
3443 // Close the current host domain settings cursor.
3444 currentDomainSettingsCursor.close();
3446 // Apply the domain settings.
3447 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptFirstPartyCookies());
3449 // Set third-party cookies status if API >= 21.
3450 if (Build.VERSION.SDK_INT >= 21) {
3451 cookieManager.setAcceptThirdPartyCookies(nestedScrollWebView, domainThirdPartyCookiesEnabled);
3454 // Apply the form data setting if the API < 26.
3455 if (Build.VERSION.SDK_INT < 26) {
3456 nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
3459 // Apply the font size.
3460 if (fontSize == 0) { // Apply the default font size.
3461 nestedScrollWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3462 } else { // Apply the specified font size.
3463 nestedScrollWebView.getSettings().setTextZoom(fontSize);
3466 // Set the user agent.
3467 if (userAgentName.equals(getString(R.string.system_default_user_agent))) { // Use the system default user agent.
3468 // Get the array position of the default user agent name.
3469 int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3471 // Set the user agent according to the system default.
3472 switch (defaultUserAgentArrayPosition) {
3473 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
3474 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3475 nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
3478 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3479 // Set the user agent to `""`, which uses the default value.
3480 nestedScrollWebView.getSettings().setUserAgentString("");
3483 case SETTINGS_CUSTOM_USER_AGENT:
3484 // Set the default custom user agent.
3485 nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
3489 // Get the user agent string from the user agent data array
3490 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
3492 } else { // Set the user agent according to the stored name.
3493 // Get the array position of the user agent name.
3494 int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
3496 switch (userAgentArrayPosition) {
3497 case UNRECOGNIZED_USER_AGENT: // The user agent name contains a custom user agent.
3498 nestedScrollWebView.getSettings().setUserAgentString(userAgentName);
3501 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3502 // Set the user agent to `""`, which uses the default value.
3503 nestedScrollWebView.getSettings().setUserAgentString("");
3507 // Get the user agent string from the user agent data array.
3508 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3512 // Set swipe to refresh.
3513 switch (swipeToRefreshInt) {
3514 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
3515 // Store the swipe to refresh status in the nested scroll WebView.
3516 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
3518 // 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.
3519 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
3522 case DomainsDatabaseHelper.ENABLED:
3523 // Store the swipe to refresh status in the nested scroll WebView.
3524 nestedScrollWebView.setSwipeToRefresh(true);
3526 // Enable swipe to refresh. This can be removed once the minimum API >= 23 because it is continuously set by an on scroll change listener.
3527 swipeRefreshLayout.setEnabled(true);
3530 case DomainsDatabaseHelper.DISABLED:
3531 // Store the swipe to refresh status in the nested scroll WebView.
3532 nestedScrollWebView.setSwipeToRefresh(false);
3534 // Disable swipe to refresh. This can be removed once the minimum API >= 23 because it is continuously set by an on scroll change listener.
3535 swipeRefreshLayout.setEnabled(false);
3538 // Set the viewport.
3539 switch (wideViewportInt) {
3540 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
3541 nestedScrollWebView.getSettings().setUseWideViewPort(wideViewport);
3544 case DomainsDatabaseHelper.ENABLED:
3545 nestedScrollWebView.getSettings().setUseWideViewPort(true);
3548 case DomainsDatabaseHelper.DISABLED:
3549 nestedScrollWebView.getSettings().setUseWideViewPort(false);
3553 // Set the loading of webpage images.
3554 switch (displayWebpageImagesInt) {
3555 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
3556 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
3559 case DomainsDatabaseHelper.ENABLED:
3560 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(true);
3563 case DomainsDatabaseHelper.DISABLED:
3564 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(false);
3568 // 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.
3570 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
3572 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
3574 } else { // The new URL does not have custom domain settings. Load the defaults.
3575 // Store the values from the shared preferences.
3576 boolean defaultJavaScriptEnabled = sharedPreferences.getBoolean("javascript", false);
3577 nestedScrollWebView.setAcceptFirstPartyCookies(sharedPreferences.getBoolean("first_party_cookies", false));
3578 boolean defaultThirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies", false);
3579 nestedScrollWebView.getSettings().setDomStorageEnabled(sharedPreferences.getBoolean("dom_storage", false));
3580 boolean saveFormData = sharedPreferences.getBoolean("save_form_data", false); // Form data can be removed once the minimum API >= 26.
3581 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASY_LIST, sharedPreferences.getBoolean("easylist", true));
3582 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASY_PRIVACY, sharedPreferences.getBoolean("easyprivacy", true));
3583 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, sharedPreferences.getBoolean("fanboys_annoyance_list", true));
3584 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, sharedPreferences.getBoolean("fanboys_social_blocking_list", true));
3585 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRA_PRIVACY, sharedPreferences.getBoolean("ultraprivacy", true));
3586 nestedScrollWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, sharedPreferences.getBoolean("block_all_third_party_requests", false));
3587 nestedScrollWebView.setNightMode(sharedPreferences.getBoolean("night_mode", false));
3589 // Enable JavaScript if night mode is enabled.
3590 if (nestedScrollWebView.getNightMode()) {
3591 // Enable JavaScript.
3592 nestedScrollWebView.getSettings().setJavaScriptEnabled(true);
3594 // Set JavaScript according to the domain settings.
3595 nestedScrollWebView.getSettings().setJavaScriptEnabled(defaultJavaScriptEnabled);
3598 // Apply the default settings.
3599 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptFirstPartyCookies());
3600 nestedScrollWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3602 // Apply the form data setting if the API < 26.
3603 if (Build.VERSION.SDK_INT < 26) {
3604 nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
3607 // Store the swipe to refresh status in the nested scroll WebView.
3608 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
3610 // Apply swipe to refresh according to the default.
3611 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
3613 // Reset the pinned variables.
3614 nestedScrollWebView.setDomainSettingsDatabaseId(-1);
3616 // Set third-party cookies status if API >= 21.
3617 if (Build.VERSION.SDK_INT >= 21) {
3618 cookieManager.setAcceptThirdPartyCookies(nestedScrollWebView, defaultThirdPartyCookiesEnabled);
3621 // Get the array position of the user agent name.
3622 int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3624 // Set the user agent.
3625 switch (userAgentArrayPosition) {
3626 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
3627 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3628 nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
3631 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3632 // Set the user agent to `""`, which uses the default value.
3633 nestedScrollWebView.getSettings().setUserAgentString("");
3636 case SETTINGS_CUSTOM_USER_AGENT:
3637 // Set the default custom user agent.
3638 nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
3642 // Get the user agent string from the user agent data array
3643 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3646 // Set the viewport.
3647 nestedScrollWebView.getSettings().setUseWideViewPort(wideViewport);
3649 // Set the loading of webpage images.
3650 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
3652 // Set a transparent background on URL edit text. The deprecated `getResources().getDrawable()` must be used until the minimum API >= 21.
3653 urlRelativeLayout.setBackground(getResources().getDrawable(R.color.transparent));
3656 // Close the domains database helper.
3657 domainsDatabaseHelper.close();
3659 // Update the privacy icons.
3660 updatePrivacyIcons(true);
3663 // Reload the website if returning from the Domains activity.
3664 if (reloadWebsite) {
3665 nestedScrollWebView.reload();
3668 // Return the user agent changed status.
3669 return !nestedScrollWebView.getSettings().getUserAgentString().equals(initialUserAgent);
3672 private void applyProxyThroughOrbot(boolean reloadWebsite) {
3673 // Get a handle for the shared preferences.
3674 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3676 // Get the search and theme preferences.
3677 String torSearchString = sharedPreferences.getString("tor_search", getString(R.string.tor_search_default_value));
3678 String torSearchCustomUrlString = sharedPreferences.getString("tor_search_custom_url", getString(R.string.tor_search_custom_url_default_value));
3679 String searchString = sharedPreferences.getString("search", getString(R.string.search_default_value));
3680 String searchCustomUrlString = sharedPreferences.getString("search_custom_url", getString(R.string.search_custom_url_default_value));
3681 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
3683 // Get a handle for the app bar layout.
3684 AppBarLayout appBarLayout = findViewById(R.id.appbar_layout);
3686 // Set the homepage, search, and proxy options.
3687 if (proxyThroughOrbot) { // Set the Tor options.
3688 // Set the search URL.
3689 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
3690 searchURL = torSearchCustomUrlString;
3691 } else { // Use the string from the pre-built list.
3692 searchURL = torSearchString;
3695 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
3696 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
3698 // Set the app bar background to indicate proxying through Orbot is enabled.
3700 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
3702 appBarLayout.setBackgroundResource(R.color.blue_50);
3705 // Check to see if Orbot is ready.
3706 if (!orbotStatus.equals("ON")) { // Orbot is not ready.
3707 // Set `waitingForOrbot`.
3708 waitingForOrbot = true;
3710 // Disable the wide view port so that the waiting for Orbot text is displayed correctly.
3711 currentWebView.getSettings().setUseWideViewPort(false);
3713 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
3714 currentWebView.loadData("<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>", "text/html", null);
3715 } else if (reloadWebsite) { // Orbot is ready and the website should be reloaded.
3716 // Reload the website.
3717 currentWebView.reload();
3719 } else { // Set the non-Tor options.
3720 // Set the search URL.
3721 if (searchString.equals("Custom URL")) { // Get the custom URL string.
3722 searchURL = searchCustomUrlString;
3723 } else { // Use the string from the pre-built list.
3724 searchURL = searchString;
3727 // Reset the proxy to default. The host is `""` and the port is `"0"`.
3728 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
3730 // Set the default app bar layout background.
3732 appBarLayout.setBackgroundResource(R.color.gray_900);
3734 appBarLayout.setBackgroundResource(R.color.gray_100);
3737 // Reset `waitingForOrbot.
3738 waitingForOrbot = false;
3740 // Reload the WebViews if requested.
3741 if (reloadWebsite) {
3742 // Reload the WebViews.
3743 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3744 // Get the WebView tab fragment.
3745 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3747 // Get the fragment view.
3748 View fragmentView = webViewTabFragment.getView();
3750 // Only reload the WebViews if they exist.
3751 if (fragmentView != null) {
3752 // Get the nested scroll WebView from the tab fragment.
3753 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3755 // Reload the WebView.
3756 nestedScrollWebView.reload();
3763 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
3764 // Only update the privacy icons if the options menu and the current WebView have already been populated.
3765 if ((optionsMenu != null) && (currentWebView != null)) {
3766 // Get a handle for the shared preferences.
3767 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3769 // Get the theme and screenshot preferences.
3770 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
3772 // Get handles for the menu items.
3773 MenuItem privacyMenuItem = optionsMenu.findItem(R.id.toggle_javascript);
3774 MenuItem firstPartyCookiesMenuItem = optionsMenu.findItem(R.id.toggle_first_party_cookies);
3775 MenuItem domStorageMenuItem = optionsMenu.findItem(R.id.toggle_dom_storage);
3776 MenuItem refreshMenuItem = optionsMenu.findItem(R.id.refresh);
3778 // Update the privacy icon.
3779 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is enabled.
3780 privacyMenuItem.setIcon(R.drawable.javascript_enabled);
3781 } else if (currentWebView.getAcceptFirstPartyCookies()) { // JavaScript is disabled but cookies are enabled.
3782 privacyMenuItem.setIcon(R.drawable.warning);
3783 } else { // All the dangerous features are disabled.
3784 privacyMenuItem.setIcon(R.drawable.privacy_mode);
3787 // Update the first-party cookies icon.
3788 if (currentWebView.getAcceptFirstPartyCookies()) { // First-party cookies are enabled.
3789 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
3790 } else { // First-party cookies are disabled.
3792 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_dark);
3794 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_light);
3798 // Update the DOM storage icon.
3799 if (currentWebView.getSettings().getJavaScriptEnabled() && currentWebView.getSettings().getDomStorageEnabled()) { // Both JavaScript and DOM storage are enabled.
3800 domStorageMenuItem.setIcon(R.drawable.dom_storage_enabled);
3801 } else if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is enabled but DOM storage is disabled.
3803 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
3805 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
3807 } else { // JavaScript is disabled, so DOM storage is ghosted.
3809 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
3811 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
3815 // Update the refresh icon.
3817 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
3819 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
3822 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
3823 if (runInvalidateOptionsMenu) {
3824 invalidateOptionsMenu();
3829 private void openUrlWithExternalApp(String url) {
3830 // Create a download intent. Not specifying the action type will display the maximum number of options.
3831 Intent downloadIntent = new Intent();
3833 // Set the URI and the MIME type. Specifying `text/html` displays a good number of options.
3834 downloadIntent.setDataAndType(Uri.parse(url), "text/html");
3836 // Flag the intent to open in a new task.
3837 downloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3839 // Show the chooser.
3840 startActivity(Intent.createChooser(downloadIntent, getString(R.string.open_with)));
3843 private void highlightUrlText() {
3844 // Get a handle for the URL edit text.
3845 EditText urlEditText = findViewById(R.id.url_edittext);
3847 // Only highlight the URL text if the box is not currently selected.
3848 if (!urlEditText.hasFocus()) {
3849 // Get the URL string.
3850 String urlString = urlEditText.getText().toString();
3852 // Highlight the URL according to the protocol.
3853 if (urlString.startsWith("file://")) { // This is a file URL.
3854 // De-emphasize only the protocol.
3855 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3856 } else if (urlString.startsWith("content://")) {
3857 // De-emphasize only the protocol.
3858 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 10, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3859 } else { // This is a web URL.
3860 // Get the index of the `/` immediately after the domain name.
3861 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
3863 // Create a base URL string.
3866 // Get the base URL.
3867 if (endOfDomainName > 0) { // There is at least one character after the base URL.
3868 // Get the base URL.
3869 baseUrl = urlString.substring(0, endOfDomainName);
3870 } else { // There are no characters after the base URL.
3871 // Set the base URL to be the entire URL string.
3872 baseUrl = urlString;
3875 // Get the index of the last `.` in the domain.
3876 int lastDotIndex = baseUrl.lastIndexOf(".");
3878 // Get the index of the penultimate `.` in the domain.
3879 int penultimateDotIndex = baseUrl.lastIndexOf(".", lastDotIndex - 1);
3881 // Markup the beginning of the URL.
3882 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
3883 urlEditText.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3885 // De-emphasize subdomains.
3886 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
3887 urlEditText.getText().setSpan(initialGrayColorSpan, 7, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3889 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
3890 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
3891 // De-emphasize the protocol and the additional subdomains.
3892 urlEditText.getText().setSpan(initialGrayColorSpan, 0, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3893 } else { // There is only one subdomain in the domain name.
3894 // De-emphasize only the protocol.
3895 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3899 // De-emphasize the text after the domain name.
3900 if (endOfDomainName > 0) {
3901 urlEditText.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3907 private void loadBookmarksFolder() {
3908 // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
3909 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
3911 // Populate the bookmarks cursor adapter. `this` specifies the `Context`. `false` disables `autoRequery`.
3912 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
3914 public View newView(Context context, Cursor cursor, ViewGroup parent) {
3915 // Inflate the individual item layout. `false` does not attach it to the root.
3916 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
3920 public void bindView(View view, Context context, Cursor cursor) {
3921 // Get handles for the views.
3922 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
3923 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
3925 // Get the favorite icon byte array from the cursor.
3926 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
3928 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
3929 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
3931 // Display the bitmap in `bookmarkFavoriteIcon`.
3932 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
3934 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
3935 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
3936 bookmarkNameTextView.setText(bookmarkNameString);
3938 // Make the font bold for folders.
3939 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
3940 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
3941 } else { // Reset the font to default for normal bookmarks.
3942 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
3947 // Get a handle for the bookmarks list view.
3948 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
3950 // Populate the list view with the adapter.
3951 bookmarksListView.setAdapter(bookmarksCursorAdapter);
3953 // Get a handle for the bookmarks title text view.
3954 TextView bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
3956 // Set the bookmarks drawer title.
3957 if (currentBookmarksFolder.isEmpty()) {
3958 bookmarksTitleTextView.setText(R.string.bookmarks);
3960 bookmarksTitleTextView.setText(currentBookmarksFolder);
3964 private void openWithApp(String url) {
3965 // Create the open with intent with `ACTION_VIEW`.
3966 Intent openWithAppIntent = new Intent(Intent.ACTION_VIEW);
3968 // Set the URI but not the MIME type. This should open all available apps.
3969 openWithAppIntent.setData(Uri.parse(url));
3971 // Flag the intent to open in a new task.
3972 openWithAppIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3974 // Show the chooser.
3975 startActivity(openWithAppIntent);
3978 private void openWithBrowser(String url) {
3979 // Create the open with intent with `ACTION_VIEW`.
3980 Intent openWithBrowserIntent = new Intent(Intent.ACTION_VIEW);
3982 // Set the URI and the MIME type. `"text/html"` should load browser options.
3983 openWithBrowserIntent.setDataAndType(Uri.parse(url), "text/html");
3985 // Flag the intent to open in a new task.
3986 openWithBrowserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3988 // Show the chooser.
3989 startActivity(openWithBrowserIntent);
3992 private String sanitizeUrl(String url) {
3993 // Sanitize Google Analytics.
3994 if (sanitizeGoogleAnalytics) {
3996 if (url.contains("?utm_")) {
3997 url = url.substring(0, url.indexOf("?utm_"));
4001 if (url.contains("&utm_")) {
4002 url = url.substring(0, url.indexOf("&utm_"));
4006 // Sanitize Facebook Click IDs.
4007 if (sanitizeFacebookClickIds) {
4008 // Remove `?fbclid=`.
4009 if (url.contains("?fbclid=")) {
4010 url = url.substring(0, url.indexOf("?fbclid="));
4013 // Remove `&fbclid=`.
4014 if (url.contains("&fbclid=")) {
4015 url = url.substring(0, url.indexOf("&fbclid="));
4019 // Sanitize Twitter AMP redirects.
4020 if (sanitizeTwitterAmpRedirects) {
4022 if (url.contains("?amp=1")) {
4023 url = url.substring(0, url.indexOf("?amp=1"));
4027 // Return the sanitized URL.
4031 public void addTab(View view) {
4032 // Add a new tab with a blank URL.
4036 private void addNewTab(String url) {
4037 // Sanitize the URL.
4038 url = sanitizeUrl(url);
4040 // Get a handle for the tab layout and the view pager.
4041 TabLayout tabLayout = findViewById(R.id.tablayout);
4042 ViewPager webViewPager = findViewById(R.id.webviewpager);
4044 // Get the new page number. The page numbers are 0 indexed, so the new page number will match the current count.
4045 int newTabNumber = tabLayout.getTabCount();
4048 tabLayout.addTab(tabLayout.newTab());
4051 TabLayout.Tab newTab = tabLayout.getTabAt(newTabNumber);
4053 // Remove the lint warning below that the current tab might be null.
4054 assert newTab != null;
4056 // Set a custom view on the new tab.
4057 newTab.setCustomView(R.layout.tab_custom_view);
4059 // Add the new WebView page.
4060 webViewPagerAdapter.addPage(newTabNumber, webViewPager, url);
4063 public void closeTab(View view) {
4064 // Get a handle for the tab layout.
4065 TabLayout tabLayout = findViewById(R.id.tablayout);
4067 // Run the command according to the number of tabs.
4068 if (tabLayout.getTabCount() > 1) { // There is more than one tab open.
4069 // Close the current tab.
4071 } else { // There is only one tab open.
4076 private void closeCurrentTab() {
4077 // Get handles for the views.
4078 AppBarLayout appBarLayout = findViewById(R.id.appbar_layout);
4079 TabLayout tabLayout = findViewById(R.id.tablayout);
4080 ViewPager webViewPager = findViewById(R.id.webviewpager);
4082 // Get the current tab number.
4083 int currentTabNumber = tabLayout.getSelectedTabPosition();
4085 // Delete the current tab.
4086 tabLayout.removeTabAt(currentTabNumber);
4088 // 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.
4089 if (webViewPagerAdapter.deletePage(currentTabNumber, webViewPager)) {
4090 setCurrentWebView(currentTabNumber);
4093 // Expand the app bar if it is currently collapsed.
4094 appBarLayout.setExpanded(true);
4097 private void clearAndExit() {
4098 // Get a handle for the shared preferences.
4099 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4101 // Close the bookmarks cursor and database.
4102 bookmarksCursor.close();
4103 bookmarksDatabaseHelper.close();
4105 // Get the status of the clear everything preference.
4106 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
4108 // Get a handle for the runtime.
4109 Runtime runtime = Runtime.getRuntime();
4111 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
4112 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
4113 String privateDataDirectoryString = getApplicationInfo().dataDir;
4116 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
4117 // The command to remove cookies changed slightly in API 21.
4118 if (Build.VERSION.SDK_INT >= 21) {
4119 CookieManager.getInstance().removeAllCookies(null);
4121 CookieManager.getInstance().removeAllCookie();
4124 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4126 // Two commands must be used because `Runtime.exec()` does not like `*`.
4127 Process deleteCookiesProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
4128 Process deleteCookiesJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
4130 // Wait until the processes have finished.
4131 deleteCookiesProcess.waitFor();
4132 deleteCookiesJournalProcess.waitFor();
4133 } catch (Exception exception) {
4134 // Do nothing if an error is thrown.
4138 // Clear DOM storage.
4139 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
4140 // Ask `WebStorage` to clear the DOM storage.
4141 WebStorage webStorage = WebStorage.getInstance();
4142 webStorage.deleteAllData();
4144 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4146 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4147 Process deleteLocalStorageProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
4149 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
4150 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
4151 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
4152 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
4153 Process deleteDatabaseProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
4155 // Wait until the processes have finished.
4156 deleteLocalStorageProcess.waitFor();
4157 deleteIndexProcess.waitFor();
4158 deleteQuotaManagerProcess.waitFor();
4159 deleteQuotaManagerJournalProcess.waitFor();
4160 deleteDatabaseProcess.waitFor();
4161 } catch (Exception exception) {
4162 // Do nothing if an error is thrown.
4166 // Clear form data if the API < 26.
4167 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
4168 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
4169 webViewDatabase.clearFormData();
4171 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4173 // A string array must be used because the database contains a space and `Runtime.exec` will not otherwise escape the string correctly.
4174 Process deleteWebDataProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
4175 Process deleteWebDataJournalProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
4177 // Wait until the processes have finished.
4178 deleteWebDataProcess.waitFor();
4179 deleteWebDataJournalProcess.waitFor();
4180 } catch (Exception exception) {
4181 // Do nothing if an error is thrown.
4186 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
4187 // Clear the cache from each WebView.
4188 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4189 // Get the WebView tab fragment.
4190 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4192 // Get the fragment view.
4193 View fragmentView = webViewTabFragment.getView();
4195 // Only clear the cache if the WebView exists.
4196 if (fragmentView != null) {
4197 // Get the nested scroll WebView from the tab fragment.
4198 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4200 // Clear the cache for this WebView.
4201 nestedScrollWebView.clearCache(true);
4205 // Manually delete the cache directories.
4207 // Delete the main cache directory.
4208 Process deleteCacheProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/cache");
4210 // Delete the secondary `Service Worker` cache directory.
4211 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4212 Process deleteServiceWorkerProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
4214 // Wait until the processes have finished.
4215 deleteCacheProcess.waitFor();
4216 deleteServiceWorkerProcess.waitFor();
4217 } catch (Exception exception) {
4218 // Do nothing if an error is thrown.
4222 // Wipe out each WebView.
4223 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4224 // Get the WebView tab fragment.
4225 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4227 // Get the fragment view.
4228 View fragmentView = webViewTabFragment.getView();
4230 // Only wipe out the WebView if it exists.
4231 if (fragmentView != null) {
4232 // Get the nested scroll WebView from the tab fragment.
4233 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4235 // Clear SSL certificate preferences for this WebView.
4236 nestedScrollWebView.clearSslPreferences();
4238 // Clear the back/forward history for this WebView.
4239 nestedScrollWebView.clearHistory();
4241 // Destroy the internal state of `mainWebView`.
4242 nestedScrollWebView.destroy();
4246 // Clear the custom headers.
4247 customHeaders.clear();
4249 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
4250 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
4251 if (clearEverything) {
4253 // Delete the folder.
4254 Process deleteAppWebviewProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
4256 // Wait until the process has finished.
4257 deleteAppWebviewProcess.waitFor();
4258 } catch (Exception exception) {
4259 // Do nothing if an error is thrown.
4263 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
4264 if (Build.VERSION.SDK_INT >= 21) {
4265 finishAndRemoveTask();
4270 // Remove the terminated program from RAM. The status code is `0`.
4274 private void setCurrentWebView(int pageNumber) {
4275 // Get a handle for the shared preferences.
4276 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4278 // Get the theme preference.
4279 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
4281 // Get handles for the URL views.
4282 RelativeLayout urlRelativeLayout = findViewById(R.id.url_relativelayout);
4283 EditText urlEditText = findViewById(R.id.url_edittext);
4284 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
4286 //Stop the swipe to refresh indicator if it is running
4287 swipeRefreshLayout.setRefreshing(false);
4289 // Get the WebView tab fragment.
4290 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(pageNumber);
4292 // Get the fragment view.
4293 View fragmentView = webViewTabFragment.getView();
4295 // Set the current WebView if the fragment view is not null.
4296 if (fragmentView != null) {
4297 // Store the current WebView.
4298 currentWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4300 // Update the status of swipe to refresh.
4301 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
4302 if (Build.VERSION.SDK_INT >= 23) { // For API >= 23, swipe refresh layout is continuously updated with an on scroll change listener and only enabled if the WebView is scrolled to the top.
4303 // Enable the swipe refresh layout if the WebView is scrolled all the way to the top.
4304 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
4306 // Enable the swipe refresh layout.
4307 swipeRefreshLayout.setEnabled(true);
4309 } else { // Swipe to refresh is disabled.
4310 // Disable the swipe refresh layout.
4311 swipeRefreshLayout.setEnabled(false);
4314 // Get a handle for the cookie manager.
4315 CookieManager cookieManager = CookieManager.getInstance();
4317 // Set the first-party cookie status.
4318 cookieManager.setAcceptCookie(currentWebView.getAcceptFirstPartyCookies());
4320 // Update the privacy icons. `true` redraws the icons in the app bar.
4321 updatePrivacyIcons(true);
4323 // Get a handle for the input method manager.
4324 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
4326 // Remove the lint warning below that the input method manager might be null.
4327 assert inputMethodManager != null;
4329 // Get the current URL.
4330 String url = currentWebView.getUrl();
4332 // Update the URL edit text if not loading a new intent. Otherwise, this will be handled by `onPageStarted()` (if called) and `onPageFinished()`.
4333 if (!loadingNewIntent) { // A new intent is not being loaded.
4334 if ((url == null) || url.equals("about:blank")) { // The WebView is blank.
4335 // Display the hint in the URL edit text.
4336 urlEditText.setText("");
4338 // Request focus for the URL text box.
4339 urlEditText.requestFocus();
4341 // Display the keyboard.
4342 inputMethodManager.showSoftInput(urlEditText, 0);
4343 } else { // The WebView has a loaded URL.
4344 // Clear the focus from the URL text box.
4345 urlEditText.clearFocus();
4347 // Hide the soft keyboard.
4348 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
4350 // Display the current URL in the URL text box.
4351 urlEditText.setText(url);
4353 // Highlight the URL text.
4356 } else { // A new intent is being loaded.
4357 // Reset the loading new intent tracker.
4358 loadingNewIntent = false;
4361 // Set the background to indicate the domain settings status.
4362 if (currentWebView.getDomainSettingsApplied()) {
4363 // 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.
4365 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
4367 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
4370 urlRelativeLayout.setBackground(getResources().getDrawable(R.color.transparent));
4376 public void initializeWebView(NestedScrollWebView nestedScrollWebView, int pageNumber, ProgressBar progressBar, String url) {
4377 // Get handles for the activity views.
4378 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
4379 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
4380 RelativeLayout mainContentRelativeLayout = findViewById(R.id.main_content_relativelayout);
4381 ActionBar actionBar = getSupportActionBar();
4382 LinearLayout tabsLinearLayout = findViewById(R.id.tabs_linearlayout);
4383 EditText urlEditText = findViewById(R.id.url_edittext);
4384 TabLayout tabLayout = findViewById(R.id.tablayout);
4385 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
4387 // Remove the incorrect lint warning below that the action bar might be null.
4388 assert actionBar != null;
4390 // Get a handle for the activity
4391 Activity activity = this;
4393 // Get a handle for the input method manager.
4394 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
4396 // Instantiate the blocklist helper.
4397 BlockListHelper blockListHelper = new BlockListHelper();
4399 // Remove the lint warning below that the input method manager might be null.
4400 assert inputMethodManager != null;
4402 // Get a handle for the shared preferences.
4403 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4405 // Get the relevant preferences.
4406 boolean downloadWithExternalApp = sharedPreferences.getBoolean("download_with_external_app", false);
4408 // Initialize the favorite icon.
4409 nestedScrollWebView.initializeFavoriteIcon();
4411 // Set the app bar scrolling.
4412 nestedScrollWebView.setNestedScrollingEnabled(sharedPreferences.getBoolean("scroll_app_bar", true));
4414 // Allow pinch to zoom.
4415 nestedScrollWebView.getSettings().setBuiltInZoomControls(true);
4417 // Hide zoom controls.
4418 nestedScrollWebView.getSettings().setDisplayZoomControls(false);
4420 // Don't allow mixed content (HTTP and HTTPS) on the same website.
4421 if (Build.VERSION.SDK_INT >= 21) {
4422 nestedScrollWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW);
4425 // Set the WebView to load in overview mode (zoomed out to the maximum width).
4426 nestedScrollWebView.getSettings().setLoadWithOverviewMode(true);
4428 // Explicitly disable geolocation.
4429 nestedScrollWebView.getSettings().setGeolocationEnabled(false);
4431 // Create a double-tap gesture detector to toggle full-screen mode.
4432 GestureDetector doubleTapGestureDetector = new GestureDetector(getApplicationContext(), new GestureDetector.SimpleOnGestureListener() {
4433 // Override `onDoubleTap()`. All other events are handled using the default settings.
4435 public boolean onDoubleTap(MotionEvent event) {
4436 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
4437 // Toggle the full screen browsing mode tracker.
4438 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
4440 // Toggle the full screen browsing mode.
4441 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
4442 // Store the swipe refresh layout top padding.
4443 swipeRefreshLayoutPaddingTop = swipeRefreshLayout.getPaddingTop();
4445 // Hide the app bar if specified.
4447 // Close the find on page bar if it is visible.
4448 closeFindOnPage(null);
4450 // Hide the tab linear layout.
4451 tabsLinearLayout.setVisibility(View.GONE);
4453 // Hide the action bar.
4456 // Check to see if app bar scrolling is disabled.
4457 if (!scrollAppBar) {
4458 // Remove the padding from the top of the swipe refresh layout.
4459 swipeRefreshLayout.setPadding(0, 0, 0, 0);
4463 // Hide the banner ad in the free flavor.
4464 if (BuildConfig.FLAVOR.contentEquals("free")) {
4465 AdHelper.hideAd(findViewById(R.id.adview));
4468 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
4469 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4471 /* Hide the system bars.
4472 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4473 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4474 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4475 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4477 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
4478 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
4479 } else { // Switch to normal viewing mode.
4480 // Show the tab linear layout.
4481 tabsLinearLayout.setVisibility(View.VISIBLE);
4483 // Show the action bar.
4486 // Check to see if app bar scrolling is disabled.
4487 if (!scrollAppBar) {
4488 // Add the padding from the top of the swipe refresh layout.
4489 swipeRefreshLayout.setPadding(0, swipeRefreshLayoutPaddingTop, 0, 0);
4492 // Show the banner ad in the free flavor.
4493 if (BuildConfig.FLAVOR.contentEquals("free")) {
4495 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
4498 // Remove the `SYSTEM_UI` flags from the root frame layout.
4499 rootFrameLayout.setSystemUiVisibility(0);
4501 // Add the translucent status flag.
4502 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4505 // Consume the double-tap.
4507 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
4513 // Pass all touch events on the WebView through the double-tap gesture detector.
4514 nestedScrollWebView.setOnTouchListener((View view, MotionEvent event) -> {
4515 // Call `performClick()` on the view, which is required for accessibility.
4516 view.performClick();
4518 // Send the event to the gesture detector.
4519 return doubleTapGestureDetector.onTouchEvent(event);
4522 // Register the WebView for a context menu. This is used to see link targets and download images.
4523 registerForContextMenu(nestedScrollWebView);
4525 // Allow the downloading of files.
4526 nestedScrollWebView.setDownloadListener((String downloadUrl, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
4527 // Check if the download should be processed by an external app.
4528 if (downloadWithExternalApp) { // Download with an external app.
4529 // Create a download intent. Not specifying the action type will display the maximum number of options.
4530 Intent downloadIntent = new Intent();
4532 // Set the URI and the MIME type. Specifying `text/html` displays a good number of options.
4533 downloadIntent.setDataAndType(Uri.parse(downloadUrl), "text/html");
4535 // Flag the intent to open in a new task.
4536 downloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4538 // Show the chooser.
4539 startActivity(Intent.createChooser(downloadIntent, getString(R.string.open_with)));
4540 } else { // Download with Android's download manager.
4541 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
4542 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission has not been granted.
4543 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
4545 // Store the variables for future use by `onRequestPermissionsResult()`.
4546 this.downloadUrl = downloadUrl;
4547 downloadContentDisposition = contentDisposition;
4548 downloadContentLength = contentLength;
4550 // Show a dialog if the user has previously denied the permission.
4551 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
4552 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
4553 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
4555 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
4556 downloadLocationPermissionDialogFragment.show(getSupportFragmentManager(), getString(R.string.download_location));
4557 } else { // Show the permission request directly.
4558 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
4559 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
4561 } else { // The storage permission has already been granted.
4562 // Get a handle for the download file alert dialog.
4563 DialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(downloadUrl, contentDisposition, contentLength);
4565 // Show the download file alert dialog.
4566 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
4571 // Update the find on page count.
4572 nestedScrollWebView.setFindListener(new WebView.FindListener() {
4573 // Get a handle for `findOnPageCountTextView`.
4574 final TextView findOnPageCountTextView = findViewById(R.id.find_on_page_count_textview);
4577 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
4578 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
4579 // Set `findOnPageCountTextView` to `0/0`.
4580 findOnPageCountTextView.setText(R.string.zero_of_zero);
4581 } else if (isDoneCounting) { // There are matches.
4582 // `activeMatchOrdinal` is zero-based.
4583 int activeMatch = activeMatchOrdinal + 1;
4585 // Build the match string.
4586 String matchString = activeMatch + "/" + numberOfMatches;
4588 // Set `findOnPageCountTextView`.
4589 findOnPageCountTextView.setText(matchString);
4594 // Update the status of swipe to refresh based on the scroll position of the nested scroll WebView.
4595 // Once the minimum API >= 23 this can be replaced with `nestedScrollWebView.setOnScrollChangeListener()`.
4596 nestedScrollWebView.getViewTreeObserver().addOnScrollChangedListener(() -> {
4597 if (nestedScrollWebView.getSwipeToRefresh()) {
4598 // Only enable swipe to refresh if the WebView is scrolled to the top.
4599 swipeRefreshLayout.setEnabled(nestedScrollWebView.getScrollY() == 0);
4603 // Set the web chrome client.
4604 nestedScrollWebView.setWebChromeClient(new WebChromeClient() {
4605 // Update the progress bar when a page is loading.
4607 public void onProgressChanged(WebView view, int progress) {
4608 // Inject the night mode CSS if night mode is enabled.
4609 if (nestedScrollWebView.getNightMode()) { // Night mode is enabled.
4610 // `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
4611 // used by WordPress. `text-decoration: none` removes all text underlines. `text-shadow: none` removes text shadows, which usually have a hard coded color.
4612 // `border: none` removes all borders, which can also be used to underline text. `a {color: #1565C0}` sets links to be a dark blue.
4613 // `::selection {background: #0D47A1}' sets the text selection highlight color to be a dark blue. `!important` takes precedent over any existing sub-settings.
4614 nestedScrollWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; " +
4615 "style.innerHTML = '* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important;" +
4616 "text-shadow: none !important; border: none !important;} a {color: #1565C0 !important;} ::selection {background: #0D47A1 !important;}'; parent.appendChild(style)})()", value -> {
4617 // Initialize a handler to display `mainWebView`.
4618 Handler displayWebViewHandler = new Handler();
4620 // Setup a runnable to display `mainWebView` after a delay to allow the CSS to be applied.
4621 Runnable displayWebViewRunnable = () -> {
4622 // Only display `mainWebView` if the progress bar is gone. This prevents the display of the `WebView` while it is still loading.
4623 if (progressBar.getVisibility() == View.GONE) {
4624 nestedScrollWebView.setVisibility(View.VISIBLE);
4628 // Display the WebView after 500 milliseconds.
4629 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
4631 } else { // Night mode is disabled.
4632 // Display the nested scroll WebView if night mode is disabled.
4633 // Because of a race condition between `applyDomainSettings` and `onPageStarted`,
4634 // when night mode is set by domain settings the WebView may be hidden even if night mode is not currently enabled.
4635 nestedScrollWebView.setVisibility(View.VISIBLE);
4638 // Update the progress bar.
4639 progressBar.setProgress(progress);
4641 // Set the visibility of the progress bar.
4642 if (progress < 100) {
4643 // Show the progress bar.
4644 progressBar.setVisibility(View.VISIBLE);
4646 // Hide the progress bar.
4647 progressBar.setVisibility(View.GONE);
4649 //Stop the swipe to refresh indicator if it is running
4650 swipeRefreshLayout.setRefreshing(false);
4654 // Set the favorite icon when it changes.
4656 public void onReceivedIcon(WebView view, Bitmap icon) {
4657 // Only update the favorite icon if the website has finished loading.
4658 if (progressBar.getVisibility() == View.GONE) {
4659 // Store the new favorite icon.
4660 nestedScrollWebView.setFavoriteOrDefaultIcon(icon);
4662 // Get the current page position.
4663 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
4665 // Get the current tab.
4666 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
4668 // Check to see if the tab has been populated.
4670 // Get the custom view from the tab.
4671 View tabView = tab.getCustomView();
4673 // Check to see if the custom tab view has been populated.
4674 if (tabView != null) {
4675 // Get the favorite icon image view from the tab.
4676 ImageView tabFavoriteIconImageView = tabView.findViewById(R.id.favorite_icon_imageview);
4678 // Display the favorite icon in the tab.
4679 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
4685 // Save a copy of the title when it changes.
4687 public void onReceivedTitle(WebView view, String title) {
4688 // Get the current page position.
4689 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
4691 // Get the current tab.
4692 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
4694 // Only populate the title text view if the tab has been fully created.
4696 // Get the custom view from the tab.
4697 View tabView = tab.getCustomView();
4699 // Remove the incorrect warning below that the current tab view might be null.
4700 assert tabView != null;
4702 // Get the title text view from the tab.
4703 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
4705 // Set the title according to the URL.
4706 if (title.equals("about:blank")) {
4707 // Set the title to indicate a new tab.
4708 tabTitleTextView.setText(R.string.new_tab);
4710 // Set the title as the tab text.
4711 tabTitleTextView.setText(title);
4716 // Enter full screen video.
4718 public void onShowCustomView(View video, CustomViewCallback callback) {
4719 // Get a handle for the full screen video frame layout.
4720 FrameLayout fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
4722 // Set the full screen video flag.
4723 displayingFullScreenVideo = true;
4725 // Pause the ad if this is the free flavor.
4726 if (BuildConfig.FLAVOR.contentEquals("free")) {
4727 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
4728 AdHelper.pauseAd(findViewById(R.id.adview));
4731 // Hide the keyboard.
4732 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
4734 // Hide the main content relative layout.
4735 mainContentRelativeLayout.setVisibility(View.GONE);
4737 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
4738 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
4740 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
4741 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4743 /* Hide the system bars.
4744 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4745 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4746 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4747 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4749 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
4750 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
4752 // Disable the sliding drawers.
4753 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
4755 // Add the video view to the full screen video frame layout.
4756 fullScreenVideoFrameLayout.addView(video);
4758 // Show the full screen video frame layout.
4759 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
4762 // Exit full screen video.
4764 public void onHideCustomView() {
4765 // Get a handle for the full screen video frame layout.
4766 FrameLayout fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
4768 // Unset the full screen video flag.
4769 displayingFullScreenVideo = false;
4771 // Remove all the views from the full screen video frame layout.
4772 fullScreenVideoFrameLayout.removeAllViews();
4774 // Hide the full screen video frame layout.
4775 fullScreenVideoFrameLayout.setVisibility(View.GONE);
4777 // Enable the sliding drawers.
4778 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
4780 // Show the main content relative layout.
4781 mainContentRelativeLayout.setVisibility(View.VISIBLE);
4783 // Apply the appropriate full screen mode flags.
4784 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
4785 // Hide the app bar if specified.
4787 // Hide the tab linear layout.
4788 tabsLinearLayout.setVisibility(View.GONE);
4790 // Hide the action bar.
4794 // Hide the banner ad in the free flavor.
4795 if (BuildConfig.FLAVOR.contentEquals("free")) {
4796 AdHelper.hideAd(findViewById(R.id.adview));
4799 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
4800 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4802 /* Hide the system bars.
4803 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4804 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4805 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4806 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4808 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
4809 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
4810 } else { // Switch to normal viewing mode.
4811 // Remove the `SYSTEM_UI` flags from the root frame layout.
4812 rootFrameLayout.setSystemUiVisibility(0);
4814 // Add the translucent status flag.
4815 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4818 // Reload the ad for the free flavor if not in full screen mode.
4819 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
4821 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
4827 public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
4828 // Show the file chooser if the device is running API >= 21.
4829 if (Build.VERSION.SDK_INT >= 21) {
4830 // Store the file path callback.
4831 fileChooserCallback = filePathCallback;
4833 // Create an intent to open a chooser based ont the file chooser parameters.
4834 Intent fileChooserIntent = fileChooserParams.createIntent();
4836 // Open the file chooser. Currently only one `startActivityForResult` exists in this activity, so the request code, used to differentiate them, is simply `0`.
4837 startActivityForResult(fileChooserIntent, 0);
4843 nestedScrollWebView.setWebViewClient(new WebViewClient() {
4844 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
4845 // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
4847 public boolean shouldOverrideUrlLoading(WebView view, String url) {
4848 // Sanitize the url.
4849 url = sanitizeUrl(url);
4851 if (url.startsWith("http")) { // Load the URL in Privacy Browser.
4852 // Apply the domain settings for the new URL. This doesn't do anything if the domain has not changed.
4853 boolean userAgentChanged = applyDomainSettings(nestedScrollWebView, url, true, false);
4855 // Check if the user agent has changed.
4856 if (userAgentChanged) {
4857 // Manually load the URL. The changing of the user agent will cause WebView to reload the previous URL.
4858 nestedScrollWebView.loadUrl(url, customHeaders);
4860 // Returning true indicates that Privacy Browser is manually handling the loading of the URL.
4863 // Returning false causes the current WebView to handle the URL and prevents it from adding redirects to the history list.
4866 } else if (url.startsWith("mailto:")) { // Load the email address in an external email program.
4867 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
4868 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
4870 // Parse the url and set it as the data for the intent.
4871 emailIntent.setData(Uri.parse(url));
4873 // Open the email program in a new task instead of as part of Privacy Browser.
4874 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4877 startActivity(emailIntent);
4879 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
4881 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
4882 // Open the dialer and load the phone number, but wait for the user to place the call.
4883 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
4885 // Add the phone number to the intent.
4886 dialIntent.setData(Uri.parse(url));
4888 // Open the dialer in a new task instead of as part of Privacy Browser.
4889 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4892 startActivity(dialIntent);
4894 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
4896 } else { // Load a system chooser to select an app that can handle the URL.
4897 // Open an app that can handle the URL.
4898 Intent genericIntent = new Intent(Intent.ACTION_VIEW);
4900 // Add the URL to the intent.
4901 genericIntent.setData(Uri.parse(url));
4903 // List all apps that can handle the URL instead of just opening the first one.
4904 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
4906 // Open the app in a new task instead of as part of Privacy Browser.
4907 genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4909 // Start the app or display a snackbar if no app is available to handle the URL.
4911 startActivity(genericIntent);
4912 } catch (ActivityNotFoundException exception) {
4913 Snackbar.make(nestedScrollWebView, getString(R.string.unrecognized_url) + " " + url, Snackbar.LENGTH_SHORT).show();
4916 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
4921 // Check requests against the block lists. The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
4923 public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
4924 // Sanitize the URL.
4925 url = sanitizeUrl(url);
4927 // Get a handle for the navigation view.
4928 NavigationView navigationView = findViewById(R.id.navigationview);
4930 // Get a handle for the navigation menu.
4931 Menu navigationMenu = navigationView.getMenu();
4933 // Get a handle for the navigation requests menu item. The menu is 0 based.
4934 MenuItem navigationRequestsMenuItem = navigationMenu.getItem(5);
4936 // Create an empty web resource response to be used if the resource request is blocked.
4937 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
4939 // Reset the whitelist results tracker.
4940 String[] whitelistResultStringArray = null;
4942 // Initialize the third party request tracker.
4943 boolean isThirdPartyRequest = false;
4945 // Get the current URL. `.getUrl()` throws an error because operations on the WebView cannot be made from this thread.
4946 String currentBaseDomain = nestedScrollWebView.getCurrentDomainName();
4948 // Store a copy of the current domain for use in later requests.
4949 String currentDomain = currentBaseDomain;
4951 // Nobody is happy when comparing null strings.
4952 if ((currentBaseDomain != null) && (url != null)) {
4953 // Convert the request URL to a URI.
4954 Uri requestUri = Uri.parse(url);
4956 // Get the request host name.
4957 String requestBaseDomain = requestUri.getHost();
4959 // Only check for third-party requests if the current base domain is not empty and the request domain is not null.
4960 if (!currentBaseDomain.isEmpty() && (requestBaseDomain != null)) {
4961 // Determine the current base domain.
4962 while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
4963 // Remove the first subdomain.
4964 currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
4967 // Determine the request base domain.
4968 while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
4969 // Remove the first subdomain.
4970 requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
4973 // Update the third party request tracker.
4974 isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
4978 // Get the current WebView page position.
4979 int webViewPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
4981 // Determine if the WebView is currently displayed.
4982 boolean webViewDisplayed = (webViewPagePosition == tabLayout.getSelectedTabPosition());
4984 // Block third-party requests if enabled.
4985 if (isThirdPartyRequest && nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS)) {
4986 // Add the result to the resource requests.
4987 nestedScrollWebView.addResourceRequest(new String[]{BlockListHelper.REQUEST_THIRD_PARTY, url});
4989 // Increment the blocked requests counters.
4990 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
4991 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS);
4993 // Update the titles of the blocklist menu items if the WebView is currently displayed.
4994 if (webViewDisplayed) {
4995 // Updating the UI must be run from the UI thread.
4996 activity.runOnUiThread(() -> {
4997 // Update the menu item titles.
4998 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5000 // Update the options menu if it has been populated.
5001 if (optionsMenu != null) {
5002 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5003 optionsMenu.findItem(R.id.block_all_third_party_requests).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " +
5004 getString(R.string.block_all_third_party_requests));
5009 // Return an empty web resource response.
5010 return emptyWebResourceResponse;
5013 // Check UltraPrivacy if it is enabled.
5014 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY)) {
5015 // Check the URL against UltraPrivacy.
5016 String[] ultraPrivacyResults = blockListHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraPrivacy);
5018 // Process the UltraPrivacy results.
5019 if (ultraPrivacyResults[0].equals(BlockListHelper.REQUEST_BLOCKED)) { // The resource request matched UltraPrivacy's blacklist.
5020 // Add the result to the resource requests.
5021 nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5022 ultraPrivacyResults[5]});
5024 // Increment the blocked requests counters.
5025 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5026 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRA_PRIVACY);
5028 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5029 if (webViewDisplayed) {
5030 // Updating the UI must be run from the UI thread.
5031 activity.runOnUiThread(() -> {
5032 // Update the menu item titles.
5033 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5035 // Update the options menu if it has been populated.
5036 if (optionsMenu != null) {
5037 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5038 optionsMenu.findItem(R.id.ultraprivacy).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRA_PRIVACY) + " - " + getString(R.string.ultraprivacy));
5043 // The resource request was blocked. Return an empty web resource response.
5044 return emptyWebResourceResponse;
5045 } else if (ultraPrivacyResults[0].equals(BlockListHelper.REQUEST_ALLOWED)) { // The resource request matched UltraPrivacy's whitelist.
5046 // Add a whitelist entry to the resource requests array.
5047 nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5048 ultraPrivacyResults[5]});
5050 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
5055 // Check EasyList if it is enabled.
5056 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST)) {
5057 // Check the URL against EasyList.
5058 String[] easyListResults = blockListHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyList);
5060 // Process the EasyList results.
5061 if (easyListResults[0].equals(BlockListHelper.REQUEST_BLOCKED)) { // The resource request matched EasyList's blacklist.
5062 // Add the result to the resource requests.
5063 nestedScrollWebView.addResourceRequest(new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]});
5065 // Increment the blocked requests counters.
5066 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5067 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASY_LIST);
5069 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5070 if (webViewDisplayed) {
5071 // Updating the UI must be run from the UI thread.
5072 activity.runOnUiThread(() -> {
5073 // Update the menu item titles.
5074 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5076 // Update the options menu if it has been populated.
5077 if (optionsMenu != null) {
5078 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5079 optionsMenu.findItem(R.id.easylist).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASY_LIST) + " - " + getString(R.string.easylist));
5084 // The resource request was blocked. Return an empty web resource response.
5085 return emptyWebResourceResponse;
5086 } else if (easyListResults[0].equals(BlockListHelper.REQUEST_ALLOWED)) { // The resource request matched EasyList's whitelist.
5087 // Update the whitelist result string array tracker.
5088 whitelistResultStringArray = new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]};
5092 // Check EasyPrivacy if it is enabled.
5093 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY)) {
5094 // Check the URL against EasyPrivacy.
5095 String[] easyPrivacyResults = blockListHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyPrivacy);
5097 // Process the EasyPrivacy results.
5098 if (easyPrivacyResults[0].equals(BlockListHelper.REQUEST_BLOCKED)) { // The resource request matched EasyPrivacy's blacklist.
5099 // Add the result to the resource requests.
5100 nestedScrollWebView.addResourceRequest(new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4],
5101 easyPrivacyResults[5]});
5103 // Increment the blocked requests counters.
5104 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5105 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASY_PRIVACY);
5107 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5108 if (webViewDisplayed) {
5109 // Updating the UI must be run from the UI thread.
5110 activity.runOnUiThread(() -> {
5111 // Update the menu item titles.
5112 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5114 // Update the options menu if it has been populated.
5115 if (optionsMenu != null) {
5116 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5117 optionsMenu.findItem(R.id.easyprivacy).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASY_PRIVACY) + " - " + getString(R.string.easyprivacy));
5122 // The resource request was blocked. Return an empty web resource response.
5123 return emptyWebResourceResponse;
5124 } else if (easyPrivacyResults[0].equals(BlockListHelper.REQUEST_ALLOWED)) { // The resource request matched EasyPrivacy's whitelist.
5125 // Update the whitelist result string array tracker.
5126 whitelistResultStringArray = new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5]};
5130 // Check Fanboy’s Annoyance List if it is enabled.
5131 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST)) {
5132 // Check the URL against Fanboy's Annoyance List.
5133 String[] fanboysAnnoyanceListResults = blockListHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList);
5135 // Process the Fanboy's Annoyance List results.
5136 if (fanboysAnnoyanceListResults[0].equals(BlockListHelper.REQUEST_BLOCKED)) { // The resource request matched Fanboy's Annoyance List's blacklist.
5137 // Add the result to the resource requests.
5138 nestedScrollWebView.addResourceRequest(new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5139 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]});
5141 // Increment the blocked requests counters.
5142 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5143 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST);
5145 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5146 if (webViewDisplayed) {
5147 // Updating the UI must be run from the UI thread.
5148 activity.runOnUiThread(() -> {
5149 // Update the menu item titles.
5150 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5152 // Update the options menu if it has been populated.
5153 if (optionsMenu != null) {
5154 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5155 optionsMenu.findItem(R.id.fanboys_annoyance_list).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " +
5156 getString(R.string.fanboys_annoyance_list));
5161 // The resource request was blocked. Return an empty web resource response.
5162 return emptyWebResourceResponse;
5163 } else if (fanboysAnnoyanceListResults[0].equals(BlockListHelper.REQUEST_ALLOWED)){ // The resource request matched Fanboy's Annoyance List's whitelist.
5164 // Update the whitelist result string array tracker.
5165 whitelistResultStringArray = new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5166 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]};
5168 } else if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST)) { // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
5169 // Check the URL against Fanboy's Annoyance List.
5170 String[] fanboysSocialListResults = blockListHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysSocialList);
5172 // Process the Fanboy's Social Blocking List results.
5173 if (fanboysSocialListResults[0].equals(BlockListHelper.REQUEST_BLOCKED)) { // The resource request matched Fanboy's Social Blocking List's blacklist.
5174 // Add the result to the resource requests.
5175 nestedScrollWebView.addResourceRequest(new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5176 fanboysSocialListResults[4], fanboysSocialListResults[5]});
5178 // Increment the blocked requests counters.
5179 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5180 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST);
5182 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5183 if (webViewDisplayed) {
5184 // Updating the UI must be run from the UI thread.
5185 activity.runOnUiThread(() -> {
5186 // Update the menu item titles.
5187 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5189 // Update the options menu if it has been populated.
5190 if (optionsMenu != null) {
5191 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5192 optionsMenu.findItem(R.id.fanboys_social_blocking_list).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " +
5193 getString(R.string.fanboys_social_blocking_list));
5198 // The resource request was blocked. Return an empty web resource response.
5199 return emptyWebResourceResponse;
5200 } else if (fanboysSocialListResults[0].equals(BlockListHelper.REQUEST_ALLOWED)) { // The resource request matched Fanboy's Social Blocking List's whitelist.
5201 // Update the whitelist result string array tracker.
5202 whitelistResultStringArray = new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5203 fanboysSocialListResults[4], fanboysSocialListResults[5]};
5207 // Add the request to the log because it hasn't been processed by any of the previous checks.
5208 if (whitelistResultStringArray != null) { // The request was processed by a whitelist.
5209 nestedScrollWebView.addResourceRequest(whitelistResultStringArray);
5210 } else { // The request didn't match any blocklist entry. Log it as a default request.
5211 nestedScrollWebView.addResourceRequest(new String[]{BlockListHelper.REQUEST_DEFAULT, url});
5214 // The resource request has not been blocked. `return null` loads the requested resource.
5218 // Handle HTTP authentication requests.
5220 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
5221 // Store the handler.
5222 nestedScrollWebView.setHttpAuthHandler(handler);
5224 // Instantiate an HTTP authentication dialog.
5225 DialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm, nestedScrollWebView.getWebViewFragmentId());
5227 // Show the HTTP authentication dialog.
5228 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
5232 public void onPageStarted(WebView view, String url, Bitmap favicon) {
5233 // Get the preferences.
5234 boolean scrollAppBar = sharedPreferences.getBoolean("scroll_app_bar", true);
5235 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
5237 // Get a handler for the app bar layout.
5238 AppBarLayout appBarLayout = findViewById(R.id.appbar_layout);
5240 // Set the top padding of the swipe refresh layout according to the app bar scrolling preference.
5242 // No padding is needed because it will automatically be placed below the app bar layout due to the scrolling layout behavior.
5243 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5245 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5246 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10, defaultProgressViewEndOffset);
5248 // Get the app bar layout height. This can't be done in `applyAppSettings()` because the app bar is not yet populated.
5249 int appBarHeight = appBarLayout.getHeight();
5251 // The swipe refresh layout must be manually moved below the app bar layout.
5252 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0);
5254 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5255 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight);
5258 // Reset the list of resource requests.
5259 nestedScrollWebView.clearResourceRequests();
5261 // Reset the requests counters.
5262 nestedScrollWebView.resetRequestsCounters();
5264 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
5265 if (nestedScrollWebView.getNightMode()) {
5266 nestedScrollWebView.setVisibility(View.INVISIBLE);
5268 nestedScrollWebView.setVisibility(View.VISIBLE);
5271 // Hide the keyboard.
5272 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
5274 // Check to see if Privacy Browser is waiting on Orbot.
5275 if (!waitingForOrbot) { // Process the URL.
5276 // Get the current page position.
5277 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5279 // Update the URL text bar if the page is currently selected.
5280 if (tabLayout.getSelectedTabPosition() == currentPagePosition) {
5281 // Clear the focus from the URL edit text.
5282 urlEditText.clearFocus();
5284 // Display the formatted URL text.
5285 urlEditText.setText(url);
5287 // Apply text highlighting to `urlTextBox`.
5291 // Reset the list of host IP addresses.
5292 nestedScrollWebView.clearCurrentIpAddresses();
5294 // Get a URI for the current URL.
5295 Uri currentUri = Uri.parse(url);
5297 // Get the IP addresses for the host.
5298 new GetHostIpAddresses(activity, getSupportFragmentManager(), nestedScrollWebView).execute(currentUri.getHost());
5300 // Apply any custom domain settings if the URL was loaded by navigating history.
5301 if (nestedScrollWebView.getNavigatingHistory()) {
5302 // Reset navigating history.
5303 nestedScrollWebView.setNavigatingHistory(false);
5305 // Apply the domain settings.
5306 boolean userAgentChanged = applyDomainSettings(nestedScrollWebView, url, true, false);
5308 // Manually load the URL if the user agent has changed, which will have caused the previous URL to be reloaded.
5309 if (userAgentChanged) {
5314 // Replace Refresh with Stop if the options menu has been created. (The first WebView typically begins loading before the menu items are instantiated.)
5315 if (optionsMenu != null) {
5316 // Get a handle for the refresh menu item.
5317 MenuItem refreshMenuItem = optionsMenu.findItem(R.id.refresh);
5320 refreshMenuItem.setTitle(R.string.stop);
5322 // Get the app bar and theme preferences.
5323 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
5325 // If the icon is displayed in the AppBar, set it according to the theme.
5326 if (displayAdditionalAppBarIcons) {
5328 refreshMenuItem.setIcon(R.drawable.close_dark);
5330 refreshMenuItem.setIcon(R.drawable.close_light);
5338 public void onPageFinished(WebView view, String url) {
5339 // Flush any cookies to persistent storage. The cookie manager has become very lazy about flushing cookies in recent versions.
5340 if (nestedScrollWebView.getAcceptFirstPartyCookies() && Build.VERSION.SDK_INT >= 21) {
5341 CookieManager.getInstance().flush();
5344 // Update the Refresh menu item if the options menu has been created.
5345 if (optionsMenu != null) {
5346 // Get a handle for the refresh menu item.
5347 MenuItem refreshMenuItem = optionsMenu.findItem(R.id.refresh);
5349 // Reset the Refresh title.
5350 refreshMenuItem.setTitle(R.string.refresh);
5352 // Get the app bar and theme preferences.
5353 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
5354 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
5356 // If the icon is displayed in the AppBar, reset it according to the theme.
5357 if (displayAdditionalAppBarIcons) {
5359 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
5361 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
5366 // Clear the cache and history if Incognito Mode is enabled.
5367 if (incognitoModeEnabled) {
5368 // Clear the cache. `true` includes disk files.
5369 nestedScrollWebView.clearCache(true);
5371 // Clear the back/forward history.
5372 nestedScrollWebView.clearHistory();
5374 // Manually delete cache folders.
5376 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
5377 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
5378 String privateDataDirectoryString = getApplicationInfo().dataDir;
5380 // Delete the main cache directory.
5381 Runtime.getRuntime().exec("rm -rf " + privateDataDirectoryString + "/cache");
5383 // Delete the secondary `Service Worker` cache directory.
5384 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
5385 Runtime.getRuntime().exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
5386 } catch (IOException e) {
5387 // Do nothing if an error is thrown.
5391 // Update the URL text box and apply domain settings if not waiting on Orbot.
5392 if (!waitingForOrbot) {
5393 // Get the current page position.
5394 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5396 // Check the current website information against any pinned domain information if the current IP addresses have been loaded.
5397 if ((nestedScrollWebView.hasPinnedSslCertificate() || nestedScrollWebView.hasPinnedIpAddresses()) && nestedScrollWebView.hasCurrentIpAddresses() &&
5398 !nestedScrollWebView.ignorePinnedDomainInformation()) {
5399 CheckPinnedMismatchHelper.checkPinnedMismatch(getSupportFragmentManager(), nestedScrollWebView);
5402 // 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.
5403 String currentUrl = nestedScrollWebView.getUrl();
5405 // Get the current tab.
5406 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
5408 // Update the URL text bar if the page is currently selected and the user is not currently typing in the URL edit text.
5409 // Crash records show that, in some crazy way, it is possible for the current URL to be blank at this point.
5410 // Probably some sort of race condition when Privacy Browser is being resumed.
5411 if ((tabLayout.getSelectedTabPosition() == currentPagePosition) && !urlEditText.hasFocus() && (currentUrl != null)) {
5412 // Check to see if the URL is `about:blank`.
5413 if (currentUrl.equals("about:blank")) { // The WebView is blank.
5414 // Display the hint in the URL edit text.
5415 urlEditText.setText("");
5417 // Request focus for the URL text box.
5418 urlEditText.requestFocus();
5420 // Display the keyboard.
5421 inputMethodManager.showSoftInput(urlEditText, 0);
5423 // Apply the domain settings. This clears any settings from the previous domain.
5424 applyDomainSettings(nestedScrollWebView, "", true, false);
5426 // Only populate the title text view if the tab has been fully created.
5428 // Get the custom view from the tab.
5429 View tabView = tab.getCustomView();
5431 // Remove the incorrect warning below that the current tab view might be null.
5432 assert tabView != null;
5434 // Get the title text view from the tab.
5435 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
5437 // Set the title as the tab text.
5438 tabTitleTextView.setText(R.string.new_tab);
5440 } else { // The WebView has loaded a webpage.
5441 // Display the final URL. Getting the URL from the WebView instead of using the one provided by `onPageFinished()` makes websites like YouTube function correctly.
5442 urlEditText.setText(currentUrl);
5444 // Apply text highlighting to the URL.
5447 // Only populate the title text view if the tab has been fully created.
5449 // Get the custom view from the tab.
5450 View tabView = tab.getCustomView();
5452 // Remove the incorrect warning below that the current tab view might be null.
5453 assert tabView != null;
5455 // Get the title text view from the tab.
5456 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
5458 // Set the title as the tab text. Sometimes `onReceivedTitle()` is not called, especially when navigating history.
5459 tabTitleTextView.setText(nestedScrollWebView.getTitle());
5466 // Handle SSL Certificate errors.
5468 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
5469 // Get the current website SSL certificate.
5470 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
5472 // Extract the individual pieces of information from the current website SSL certificate.
5473 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
5474 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
5475 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
5476 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
5477 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
5478 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
5479 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
5480 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
5482 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
5483 if (nestedScrollWebView.hasPinnedSslCertificate()) {
5484 // Get the pinned SSL certificate.
5485 ArrayList<Object> pinnedSslCertificateArrayList = nestedScrollWebView.getPinnedSslCertificate();
5487 // Extract the arrays from the array list.
5488 String[] pinnedSslCertificateStringArray = (String[]) pinnedSslCertificateArrayList.get(0);
5489 Date[] pinnedSslCertificateDateArray = (Date[]) pinnedSslCertificateArrayList.get(1);
5491 // Check if the current SSL certificate matches the pinned certificate.
5492 if (currentWebsiteIssuedToCName.equals(pinnedSslCertificateStringArray[0]) && currentWebsiteIssuedToOName.equals(pinnedSslCertificateStringArray[1]) &&
5493 currentWebsiteIssuedToUName.equals(pinnedSslCertificateStringArray[2]) && currentWebsiteIssuedByCName.equals(pinnedSslCertificateStringArray[3]) &&
5494 currentWebsiteIssuedByOName.equals(pinnedSslCertificateStringArray[4]) && currentWebsiteIssuedByUName.equals(pinnedSslCertificateStringArray[5]) &&
5495 currentWebsiteSslStartDate.equals(pinnedSslCertificateDateArray[0]) && currentWebsiteSslEndDate.equals(pinnedSslCertificateDateArray[1])) {
5497 // An SSL certificate is pinned and matches the current domain certificate. Proceed to the website without displaying an error.
5500 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
5501 // Store the SSL error handler.
5502 nestedScrollWebView.setSslErrorHandler(handler);
5504 // Instantiate an SSL certificate error alert dialog.
5505 DialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error, nestedScrollWebView.getWebViewFragmentId());
5507 // Show the SSL certificate error dialog.
5508 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
5513 // Check to see if this is the first page.
5514 if (pageNumber == 0) {
5515 // Set this nested scroll WebView as the current WebView.
5516 currentWebView = nestedScrollWebView;
5518 // Apply the app settings from the shared preferences.
5521 // Load the website if not waiting for Orbot to connect.
5522 if (!waitingForOrbot) {
5523 // Get the intent that started the app.
5524 Intent launchingIntent = getIntent();
5526 // Get the information from the intent.
5527 String launchingIntentAction = launchingIntent.getAction();
5528 Uri launchingIntentUriData = launchingIntent.getData();
5530 // If the intent action is a web search, perform the search.
5531 if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) {
5532 // Create an encoded URL string.
5533 String encodedUrlString;
5535 // Sanitize the search input and convert it to a search.
5537 encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
5538 } catch (UnsupportedEncodingException exception) {
5539 encodedUrlString = "";
5542 // Load the completed search URL.
5543 loadUrl(searchURL + encodedUrlString);
5544 } else if (launchingIntentUriData != null){ // Check to see if the intent contains a new URL.
5545 // Load the URL from the intent.
5546 loadUrl(launchingIntentUriData.toString());
5547 } else { // The is no URL in the intent.
5548 // Select the homepage based on the proxy through Orbot status.
5549 if (proxyThroughOrbot) {
5550 // Load the Tor homepage.
5551 loadUrl(sharedPreferences.getString("tor_homepage", getString(R.string.tor_homepage_default_value)));
5553 // Load the normal homepage.
5554 loadUrl(sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
5558 } else { // This is not the first tab.
5559 // Apply the domain settings.
5560 applyDomainSettings(nestedScrollWebView, url, false, false);
5563 nestedScrollWebView.loadUrl(url, customHeaders);
5565 // Set the focus and display the keyboard if the URL is blank.
5566 if (url.equals("")) {
5567 // Request focus for the URL text box.
5568 urlEditText.requestFocus();
5570 // Create a display keyboard handler.
5571 Handler displayKeyboardHandler = new Handler();
5573 // Create a display keyboard runnable.
5574 Runnable displayKeyboardRunnable = () -> {
5575 // Display the keyboard.
5576 inputMethodManager.showSoftInput(urlEditText, 0);
5579 // Display the keyboard after 100 milliseconds, which leaves enough time for the tab to transition.
5580 displayKeyboardHandler.postDelayed(displayKeyboardRunnable, 100);