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;
286 // The download strings are used in `onCreate()`, `onRequestPermissionResult()` and `initializeWebView()`.
287 private String downloadUrl;
288 private String downloadContentDisposition;
289 private long downloadContentLength;
291 // `downloadImageUrl` is used in `onCreateContextMenu()` and `onRequestPermissionResult()`.
292 private String downloadImageUrl;
294 // The request codes are used in `onCreate()`, `onCreateContextMenu()`, `onCloseDownloadLocationPermissionDialog()`, `onRequestPermissionResult()`, and `initializeWebView()`.
295 private final int DOWNLOAD_FILE_REQUEST_CODE = 1;
296 private final int DOWNLOAD_IMAGE_REQUEST_CODE = 2;
299 // Remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
300 @SuppressLint("ClickableViewAccessibility")
301 protected void onCreate(Bundle savedInstanceState) {
302 // Get a handle for the shared preferences.
303 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
305 // Get the theme and screenshot preferences.
306 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
307 boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
309 // Disable screenshots if not allowed.
310 if (!allowScreenshots) {
311 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
314 // Set the activity theme.
316 setTheme(R.style.PrivacyBrowserDark);
318 setTheme(R.style.PrivacyBrowserLight);
321 // Run the default commands.
322 super.onCreate(savedInstanceState);
324 // Set the content view.
325 setContentView(R.layout.main_framelayout);
327 // Get a handle for the input method.
328 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
330 // Remove the lint warning below that the input method manager might be null.
331 assert inputMethodManager != null;
333 // Get a handle for the toolbar.
334 Toolbar toolbar = findViewById(R.id.toolbar);
336 // Set the action bar. `SupportActionBar` must be used until the minimum API is >= 21.
337 setSupportActionBar(toolbar);
339 // Get a handle for the action bar.
340 ActionBar actionBar = getSupportActionBar();
342 // This is needed to get rid of the Android Studio warning that the action bar might be null.
343 assert actionBar != null;
345 // Add the custom layout, which shows the URL text bar.
346 actionBar.setCustomView(R.layout.url_app_bar);
347 actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
349 // Initialize the foreground color spans for highlighting the URLs. We have to use the deprecated `getColor()` until API >= 23.
350 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
351 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
352 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
354 // Get handles for the URL views.
355 EditText urlEditText = findViewById(R.id.url_edittext);
357 // Remove the formatting from `urlTextBar` when the user is editing the text.
358 urlEditText.setOnFocusChangeListener((View v, boolean hasFocus) -> {
359 if (hasFocus) { // The user is editing the URL text box.
360 // Remove the highlighting.
361 urlEditText.getText().removeSpan(redColorSpan);
362 urlEditText.getText().removeSpan(initialGrayColorSpan);
363 urlEditText.getText().removeSpan(finalGrayColorSpan);
364 } else { // The user has stopped editing the URL text box.
365 // Move to the beginning of the string.
366 urlEditText.setSelection(0);
368 // Reapply the highlighting.
373 // Set the go button on the keyboard to load the URL in `urlTextBox`.
374 urlEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
375 // If the event is a key-down event on the `enter` button, load the URL.
376 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
377 // Load the URL into the mainWebView and consume the event.
378 loadUrlFromTextBox();
380 // If the enter key was pressed, consume the event.
383 // If any other key was pressed, do not consume the event.
388 // Initialize the Orbot status and the waiting for Orbot trackers.
389 orbotStatus = "unknown";
390 waitingForOrbot = false;
392 // Create an Orbot status `BroadcastReceiver`.
393 orbotStatusBroadcastReceiver = new BroadcastReceiver() {
395 public void onReceive(Context context, Intent intent) {
396 // Store the content of the status message in `orbotStatus`.
397 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
399 // If Privacy Browser is waiting on Orbot, load the website now that Orbot is connected.
400 if (orbotStatus.equals("ON") && waitingForOrbot) {
401 // Reset the waiting for Orbot status.
402 waitingForOrbot = false;
404 // Get the intent that started the app.
405 Intent launchingIntent = getIntent();
407 // Get the information from the intent.
408 String launchingIntentAction = launchingIntent.getAction();
409 Uri launchingIntentUriData = launchingIntent.getData();
411 // If the intent action is a web search, perform the search.
412 if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) {
413 // Create an encoded URL string.
414 String encodedUrlString;
416 // Sanitize the search input and convert it to a search.
418 encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
419 } catch (UnsupportedEncodingException exception) {
420 encodedUrlString = "";
423 // Load the completed search URL.
424 loadUrl(searchURL + encodedUrlString);
425 } else if (launchingIntentUriData != null){ // Check to see if the intent contains a new URL.
426 // Load the URL from the intent.
427 loadUrl(launchingIntentUriData.toString());
428 } else { // The is no URL in the intent.
429 // Select the homepage based on the proxy through Orbot status.
430 if (proxyThroughOrbot) {
431 // Load the Tor homepage.
432 loadUrl(sharedPreferences.getString("tor_homepage", getString(R.string.tor_homepage_default_value)));
434 // Load the normal homepage.
435 loadUrl(sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
442 // Register `orbotStatusBroadcastReceiver` on `this` context.
443 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
445 // Instantiate the blocklist helper.
446 BlockListHelper blockListHelper = new BlockListHelper();
448 // Parse the block lists.
449 easyList = blockListHelper.parseBlockList(getAssets(), "blocklists/easylist.txt");
450 easyPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/easyprivacy.txt");
451 fanboysAnnoyanceList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-annoyance.txt");
452 fanboysSocialList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-social.txt");
453 ultraPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/ultraprivacy.txt");
455 // Get handles for views that need to be modified.
456 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
457 NavigationView navigationView = findViewById(R.id.navigationview);
458 TabLayout tabLayout = findViewById(R.id.tablayout);
459 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
460 ViewPager webViewPager = findViewById(R.id.webviewpager);
461 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
462 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
463 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
464 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
465 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
467 // Listen for touches on the navigation menu.
468 navigationView.setNavigationItemSelectedListener(this);
470 // Get handles for the navigation menu and the back and forward menu items. The menu is zero-based.
471 Menu navigationMenu = navigationView.getMenu();
472 MenuItem navigationBackMenuItem = navigationMenu.getItem(2);
473 MenuItem navigationForwardMenuItem = navigationMenu.getItem(3);
474 MenuItem navigationHistoryMenuItem = navigationMenu.getItem(4);
475 MenuItem navigationRequestsMenuItem = navigationMenu.getItem(5);
477 // Initialize the web view pager adapter.
478 webViewPagerAdapter = new WebViewPagerAdapter(getSupportFragmentManager());
480 // Set the pager adapter on the web view pager.
481 webViewPager.setAdapter(webViewPagerAdapter);
483 // Store up to 100 tabs in memory.
484 webViewPager.setOffscreenPageLimit(100);
486 // Update the web view pager every time a tab is modified.
487 webViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
489 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
494 public void onPageSelected(int position) {
495 // Close the find on page bar if it is open.
496 closeFindOnPage(null);
498 // Set the current WebView.
499 setCurrentWebView(position);
501 // 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.
502 if (tabLayout.getSelectedTabPosition() != position) {
503 // Create a handler to select the tab.
504 Handler selectTabHandler = new Handler();
506 // Create a runnable select the new tab.
507 Runnable selectTabRunnable = () -> {
508 // Get a handle for the tab.
509 TabLayout.Tab tab = tabLayout.getTabAt(position);
511 // Assert that the tab is not null.
518 // Select the tab layout after 100 milliseconds, which leaves enough time for a new tab to be created.
519 selectTabHandler.postDelayed(selectTabRunnable, 100);
524 public void onPageScrollStateChanged(int state) {
529 // Display the View SSL Certificate dialog when the currently selected tab is reselected.
530 tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
532 public void onTabSelected(TabLayout.Tab tab) {
533 // Select the same page in the view pager.
534 webViewPager.setCurrentItem(tab.getPosition());
538 public void onTabUnselected(TabLayout.Tab tab) {
543 public void onTabReselected(TabLayout.Tab tab) {
544 // Instantiate the View SSL Certificate dialog.
545 DialogFragment viewSslCertificateDialogFragment = ViewSslCertificateDialog.displayDialog(currentWebView.getWebViewFragmentId());
547 // Display the View SSL Certificate dialog.
548 viewSslCertificateDialogFragment.show(getSupportFragmentManager(), getString(R.string.view_ssl_certificate));
552 // Add the first tab.
555 // 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.
556 // The deprecated `getResources().getDrawable()` must be used until the minimum API >= 21 and and `getResources().getColor()` must be used until the minimum API >= 23.
558 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
559 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
560 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
561 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
563 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
564 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
565 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
566 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
569 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
570 launchBookmarksActivityFab.setOnClickListener(v -> {
571 // Get a copy of the favorite icon bitmap.
572 Bitmap favoriteIconBitmap = currentWebView.getFavoriteOrDefaultIcon();
574 // Create a favorite icon byte array output stream.
575 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
577 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
578 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
580 // Convert the favorite icon byte array stream to a byte array.
581 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
583 // Create an intent to launch the bookmarks activity.
584 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
586 // Add the extra information to the intent.
587 bookmarksIntent.putExtra("current_url", currentWebView.getUrl());
588 bookmarksIntent.putExtra("current_title", currentWebView.getTitle());
589 bookmarksIntent.putExtra("current_folder", currentBookmarksFolder);
590 bookmarksIntent.putExtra("favorite_icon_byte_array", favoriteIconByteArray);
593 startActivity(bookmarksIntent);
596 // Set the create new bookmark folder FAB to display an alert dialog.
597 createBookmarkFolderFab.setOnClickListener(v -> {
598 // Create a create bookmark folder dialog.
599 DialogFragment createBookmarkFolderDialog = CreateBookmarkFolderDialog.createBookmarkFolder(currentWebView.getFavoriteOrDefaultIcon());
601 // Show the create bookmark folder dialog.
602 createBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.create_folder));
605 // Set the create new bookmark FAB to display an alert dialog.
606 createBookmarkFab.setOnClickListener(view -> {
607 // Instantiate the create bookmark dialog.
608 DialogFragment createBookmarkDialog = CreateBookmarkDialog.createBookmark(currentWebView.getUrl(), currentWebView.getTitle(), currentWebView.getFavoriteOrDefaultIcon());
610 // Display the create bookmark dialog.
611 createBookmarkDialog.show(getSupportFragmentManager(), getString(R.string.create_bookmark));
614 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
615 findOnPageEditText.addTextChangedListener(new TextWatcher() {
617 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
622 public void onTextChanged(CharSequence s, int start, int before, int count) {
627 public void afterTextChanged(Editable s) {
628 // 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.
629 if (currentWebView != null) {
630 currentWebView.findAllAsync(findOnPageEditText.getText().toString());
635 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
636 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
637 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
638 // Hide the soft keyboard.
639 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
641 // Consume the event.
643 } else { // A different key was pressed.
644 // Do not consume the event.
649 // Implement swipe to refresh.
650 swipeRefreshLayout.setOnRefreshListener(() -> currentWebView.reload());
652 // Store the default progress view offsets for use later in `initializeWebView()`.
653 defaultProgressViewStartOffset = swipeRefreshLayout.getProgressViewStartOffset();
654 defaultProgressViewEndOffset = swipeRefreshLayout.getProgressViewEndOffset();
656 // Set the swipe to refresh color according to the theme.
658 swipeRefreshLayout.setColorSchemeResources(R.color.blue_800);
659 swipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.gray_850);
661 swipeRefreshLayout.setColorSchemeResources(R.color.blue_500);
664 // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
665 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
666 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
668 // Initialize the bookmarks database helper. The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
669 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
671 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
672 currentBookmarksFolder = "";
674 // Load the home folder, which is `""` in the database.
675 loadBookmarksFolder();
677 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
678 // Convert the id from long to int to match the format of the bookmarks database.
679 int databaseID = (int) id;
681 // Get the bookmark cursor for this ID and move it to the first row.
682 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseID);
683 bookmarkCursor.moveToFirst();
685 // Act upon the bookmark according to the type.
686 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
687 // Store the new folder name in `currentBookmarksFolder`.
688 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
690 // Load the new folder.
691 loadBookmarksFolder();
692 } else { // The selected bookmark is not a folder.
693 // Load the bookmark URL.
694 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
696 // Close the bookmarks drawer.
697 drawerLayout.closeDrawer(GravityCompat.END);
700 // Close the `Cursor`.
701 bookmarkCursor.close();
704 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
705 // Convert the database ID from `long` to `int`.
706 int databaseId = (int) id;
708 // Find out if the selected bookmark is a folder.
709 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
712 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
713 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
715 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
716 DialogFragment editBookmarkFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId, currentWebView.getFavoriteOrDefaultIcon());
717 editBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.edit_folder));
719 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
720 DialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId, currentWebView.getFavoriteOrDefaultIcon());
721 editBookmarkDialog.show(getSupportFragmentManager(), getString(R.string.edit_bookmark));
724 // Consume the event.
728 // Get the status bar pixel size.
729 int statusBarResourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
730 int statusBarPixelSize = getResources().getDimensionPixelSize(statusBarResourceId);
732 // Get the resource density.
733 float screenDensity = getResources().getDisplayMetrics().density;
735 // Calculate the drawer header padding. This is used to move the text in the drawer headers below any cutouts.
736 drawerHeaderPaddingLeftAndRight = (int) (15 * screenDensity);
737 drawerHeaderPaddingTop = statusBarPixelSize + (int) (4 * screenDensity);
738 drawerHeaderPaddingBottom = (int) (8 * screenDensity);
740 // The drawer listener is used to update the navigation menu.`
741 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
743 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
747 public void onDrawerOpened(@NonNull View drawerView) {
751 public void onDrawerClosed(@NonNull View drawerView) {
755 public void onDrawerStateChanged(int newState) {
756 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // A drawer is opening or closing.
757 // Get handles for the drawer headers.
758 TextView navigationHeaderTextView = findViewById(R.id.navigationText);
759 TextView bookmarksHeaderTextView = findViewById(R.id.bookmarks_title_textview);
761 // 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.
762 if (navigationHeaderTextView != null) {
763 navigationHeaderTextView.setPadding(drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingTop, drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingBottom);
766 // 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.
767 if (bookmarksHeaderTextView != null) {
768 bookmarksHeaderTextView.setPadding(drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingTop, drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingBottom);
771 // Update the navigation menu items.
772 navigationBackMenuItem.setEnabled(currentWebView.canGoBack());
773 navigationForwardMenuItem.setEnabled(currentWebView.canGoForward());
774 navigationHistoryMenuItem.setEnabled((currentWebView.canGoBack() || currentWebView.canGoForward()));
775 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
777 // Hide the keyboard (if displayed).
778 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
780 // 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.
781 urlEditText.clearFocus();
782 currentWebView.clearFocus();
787 // Create the hamburger icon at the start of the AppBar.
788 actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
790 // 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).
791 customHeaders.put("X-Requested-With", "");
793 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
794 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
796 // Inflate a bare WebView to get the default user agent. It is not used to render content on the screen.
797 @SuppressLint("InflateParams") View webViewLayout = getLayoutInflater().inflate(R.layout.bare_webview, null, false);
799 // Get a handle for the WebView.
800 WebView bareWebView = webViewLayout.findViewById(R.id.bare_webview);
802 // Store the default user agent.
803 webViewDefaultUserAgent = bareWebView.getSettings().getUserAgentString();
805 // Destroy the bare WebView.
806 bareWebView.destroy();
810 protected void onNewIntent(Intent intent) {
811 // Get the information from the intent.
812 String intentAction = intent.getAction();
813 Uri intentUriData = intent.getData();
815 // Determine if this is a web search.
816 boolean isWebSearch = ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH));
818 // 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.
819 if (intentUriData != null || isWebSearch) {
820 // Get the shared preferences.
821 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
823 // Create a URL string.
826 // If the intent action is a web search, perform the search.
828 // Create an encoded URL string.
829 String encodedUrlString;
831 // Sanitize the search input and convert it to a search.
833 encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
834 } catch (UnsupportedEncodingException exception) {
835 encodedUrlString = "";
838 // Add the base search URL.
839 url = searchURL + encodedUrlString;
840 } else { // The intent should contain a URL.
841 // Set the intent data as the URL.
842 url = intentUriData.toString();
845 // Add a new tab if specified in the preferences.
846 if (sharedPreferences.getBoolean("open_intents_in_new_tab", true)) { // Load the URL in a new tab.
847 // Set the loading new intent flag.
848 loadingNewIntent = true;
852 } else { // Load the URL in the current tab.
857 // Get a handle for the drawer layout.
858 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
860 // Close the navigation drawer if it is open.
861 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
862 drawerLayout.closeDrawer(GravityCompat.START);
865 // Close the bookmarks drawer if it is open.
866 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
867 drawerLayout.closeDrawer(GravityCompat.END);
873 public void onRestart() {
874 // Run the default commands.
877 // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
878 if (proxyThroughOrbot) {
879 // Request Orbot to start. If Orbot is already running no hard will be caused by this request.
880 Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
882 // Send the intent to the Orbot package.
883 orbotIntent.setPackage("org.torproject.android");
886 sendBroadcast(orbotIntent);
889 // Apply the app settings if returning from the Settings activity.
890 if (reapplyAppSettingsOnRestart) {
891 // Reset the reapply app settings on restart tracker.
892 reapplyAppSettingsOnRestart = false;
894 // Apply the app settings.
898 // Apply the domain settings if returning from the settings or domains activity.
899 if (reapplyDomainSettingsOnRestart) {
900 // Reset the reapply domain settings on restart tracker.
901 reapplyDomainSettingsOnRestart = false;
903 // Reapply the domain settings for each tab.
904 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
905 // Get the WebView tab fragment.
906 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
908 // Get the fragment view.
909 View fragmentView = webViewTabFragment.getView();
911 // Only reload the WebViews if they exist.
912 if (fragmentView != null) {
913 // Get the nested scroll WebView from the tab fragment.
914 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
916 // Reset the current domain name so the domain settings will be reapplied.
917 nestedScrollWebView.resetCurrentDomainName();
919 // Reapply the domain settings if the URL is not null, which can happen if an empty tab is active when returning from settings.
920 if (nestedScrollWebView.getUrl() != null) {
921 applyDomainSettings(nestedScrollWebView, nestedScrollWebView.getUrl(), false, true);
927 // Load the URL on restart (used when loading a bookmark).
928 if (loadUrlOnRestart) {
929 // Load the specified URL.
930 loadUrl(urlToLoadOnRestart);
932 // Reset the load on restart tracker.
933 loadUrlOnRestart = false;
936 // Update the bookmarks drawer if returning from the Bookmarks activity.
937 if (restartFromBookmarksActivity) {
938 // Get a handle for the drawer layout.
939 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
941 // Close the bookmarks drawer.
942 drawerLayout.closeDrawer(GravityCompat.END);
944 // Reload the bookmarks drawer.
945 loadBookmarksFolder();
947 // Reset `restartFromBookmarksActivity`.
948 restartFromBookmarksActivity = false;
951 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
952 updatePrivacyIcons(true);
955 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
957 public void onResume() {
958 // Run the default commands.
961 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
962 // Get the WebView tab fragment.
963 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
965 // Get the fragment view.
966 View fragmentView = webViewTabFragment.getView();
968 // Only resume the WebViews if they exist (they won't when the app is first created).
969 if (fragmentView != null) {
970 // Get the nested scroll WebView from the tab fragment.
971 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
973 // Resume the nested scroll WebView JavaScript timers.
974 nestedScrollWebView.resumeTimers();
976 // Resume the nested scroll WebView.
977 nestedScrollWebView.onResume();
981 // Display a message to the user if waiting for Orbot.
982 if (waitingForOrbot && !orbotStatus.equals("ON")) {
983 // Disable the wide view port so that the waiting for Orbot text is displayed correctly.
984 currentWebView.getSettings().setUseWideViewPort(false);
986 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
987 currentWebView.loadData("<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>", "text/html", null);
990 if (displayingFullScreenVideo || inFullScreenBrowsingMode) {
991 // Get a handle for the root frame layouts.
992 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
994 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
995 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
997 /* Hide the system bars.
998 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
999 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
1000 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1001 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1003 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
1004 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1005 } else if (BuildConfig.FLAVOR.contentEquals("free")) { // Resume the adView for the free flavor.
1007 AdHelper.resumeAd(findViewById(R.id.adview));
1012 public void onPause() {
1013 // Run the default commands.
1016 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
1017 // Get the WebView tab fragment.
1018 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
1020 // Get the fragment view.
1021 View fragmentView = webViewTabFragment.getView();
1023 // Only pause the WebViews if they exist (they won't when the app is first created).
1024 if (fragmentView != null) {
1025 // Get the nested scroll WebView from the tab fragment.
1026 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
1028 // Pause the nested scroll WebView.
1029 nestedScrollWebView.onPause();
1031 // Pause the nested scroll WebView JavaScript timers.
1032 nestedScrollWebView.pauseTimers();
1036 // Pause the ad or it will continue to consume resources in the background on the free flavor.
1037 if (BuildConfig.FLAVOR.contentEquals("free")) {
1039 AdHelper.pauseAd(findViewById(R.id.adview));
1044 public void onDestroy() {
1045 // Unregister the Orbot status broadcast receiver.
1046 this.unregisterReceiver(orbotStatusBroadcastReceiver);
1048 // Close the bookmarks cursor and database.
1049 bookmarksCursor.close();
1050 bookmarksDatabaseHelper.close();
1052 // Run the default commands.
1057 public boolean onCreateOptionsMenu(Menu menu) {
1058 // Inflate the menu. This adds items to the action bar if it is present.
1059 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1061 // Store a handle for the options menu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons()`.
1064 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1065 updatePrivacyIcons(false);
1067 // Get handles for the menu items.
1068 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1069 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1070 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1071 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
1072 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
1073 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1074 MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
1076 // Only display third-party cookies if API >= 21
1077 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1079 // Only display the form data menu items if the API < 26.
1080 toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1081 clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1083 // Disable the clear form data menu item if the API >= 26 so that the status of the main Clear Data is calculated correctly.
1084 clearFormDataMenuItem.setEnabled(Build.VERSION.SDK_INT < 26);
1086 // Only show Ad Consent if this is the free flavor.
1087 adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
1089 // Get the shared preferences.
1090 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1092 // Get the dark theme and app bar preferences..
1093 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
1094 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
1096 // 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.
1097 if (displayAdditionalAppBarIcons) {
1098 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1099 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1100 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
1101 } else { //Do not display the additional icons.
1102 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1103 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1104 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1107 // Replace Refresh with Stop if a URL is already loading.
1108 if (currentWebView != null && currentWebView.getProgress() != 100) {
1110 refreshMenuItem.setTitle(R.string.stop);
1112 // If the icon is displayed in the AppBar, set it according to the theme.
1113 if (displayAdditionalAppBarIcons) {
1115 refreshMenuItem.setIcon(R.drawable.close_dark);
1117 refreshMenuItem.setIcon(R.drawable.close_light);
1126 public boolean onPrepareOptionsMenu(Menu menu) {
1127 // Get handles for the menu items.
1128 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
1129 MenuItem firstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1130 MenuItem thirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1131 MenuItem domStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1132 MenuItem saveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
1133 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
1134 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1135 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1136 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
1137 MenuItem blocklistsMenuItem = menu.findItem(R.id.blocklists);
1138 MenuItem easyListMenuItem = menu.findItem(R.id.easylist);
1139 MenuItem easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
1140 MenuItem fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
1141 MenuItem fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
1142 MenuItem ultraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
1143 MenuItem blockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
1144 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1145 MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
1146 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1147 MenuItem nightModeMenuItem = menu.findItem(R.id.night_mode);
1148 MenuItem proxyThroughOrbotMenuItem = menu.findItem(R.id.proxy_through_orbot);
1150 // Get a handle for the cookie manager.
1151 CookieManager cookieManager = CookieManager.getInstance();
1153 // Initialize the current user agent string and the font size.
1154 String currentUserAgent = getString(R.string.user_agent_privacy_browser);
1157 // 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.
1158 if (currentWebView != null) {
1159 // Set the add or edit domain text.
1160 if (currentWebView.getDomainSettingsApplied()) {
1161 addOrEditDomain.setTitle(R.string.edit_domain_settings);
1163 addOrEditDomain.setTitle(R.string.add_domain_settings);
1166 // Get the current user agent from the WebView.
1167 currentUserAgent = currentWebView.getSettings().getUserAgentString();
1169 // Get the current font size from the
1170 fontSize = currentWebView.getSettings().getTextZoom();
1172 // Set the status of the menu item checkboxes.
1173 domStorageMenuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1174 saveFormDataMenuItem.setChecked(currentWebView.getSettings().getSaveFormData()); // Form data can be removed once the minimum API >= 26.
1175 easyListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST));
1176 easyPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY));
1177 fanboysAnnoyanceListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1178 fanboysSocialBlockingListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1179 ultraPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY));
1180 blockAllThirdPartyRequestsMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1181 swipeToRefreshMenuItem.setChecked(currentWebView.getSwipeToRefresh());
1182 displayImagesMenuItem.setChecked(currentWebView.getSettings().getLoadsImagesAutomatically());
1183 nightModeMenuItem.setChecked(currentWebView.getNightMode());
1185 // Initialize the display names for the blocklists with the number of blocked requests.
1186 blocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
1187 easyListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASY_LIST) + " - " + getString(R.string.easylist));
1188 easyPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASY_PRIVACY) + " - " + getString(R.string.easyprivacy));
1189 fanboysAnnoyanceListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " + getString(R.string.fanboys_annoyance_list));
1190 fanboysSocialBlockingListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " + getString(R.string.fanboys_social_blocking_list));
1191 ultraPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRA_PRIVACY) + " - " + getString(R.string.ultraprivacy));
1192 blockAllThirdPartyRequestsMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " + getString(R.string.block_all_third_party_requests));
1194 // Only modify third-party cookies if the API >= 21.
1195 if (Build.VERSION.SDK_INT >= 21) {
1196 // Set the status of the third-party cookies checkbox.
1197 thirdPartyCookiesMenuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
1199 // Enable third-party cookies if first-party cookies are enabled.
1200 thirdPartyCookiesMenuItem.setEnabled(cookieManager.acceptCookie());
1203 // Enable DOM Storage if JavaScript is enabled.
1204 domStorageMenuItem.setEnabled(currentWebView.getSettings().getJavaScriptEnabled());
1207 // Set the status of the menu item checkboxes.
1208 firstPartyCookiesMenuItem.setChecked(cookieManager.acceptCookie());
1209 proxyThroughOrbotMenuItem.setChecked(proxyThroughOrbot);
1211 // Enable Clear Cookies if there are any.
1212 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1214 // 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`.
1215 String privateDataDirectoryString = getApplicationInfo().dataDir;
1217 // Get a count of the number of files in the Local Storage directory.
1218 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1219 int localStorageDirectoryNumberOfFiles = 0;
1220 if (localStorageDirectory.exists()) {
1221 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1224 // Get a count of the number of files in the IndexedDB directory.
1225 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1226 int indexedDBDirectoryNumberOfFiles = 0;
1227 if (indexedDBDirectory.exists()) {
1228 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1231 // Enable Clear DOM Storage if there is any.
1232 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1234 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
1235 if (Build.VERSION.SDK_INT < 26) {
1236 // Get the WebView database.
1237 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1239 // Enable the clear form data menu item if there is anything to clear.
1240 clearFormDataMenuItem.setEnabled(webViewDatabase.hasFormData());
1243 // Enable Clear Data if any of the submenu items are enabled.
1244 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
1246 // Disable Fanboy's Social Blocking List menu item if Fanboy's Annoyance List is checked.
1247 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListMenuItem.isChecked());
1249 // Select the current user agent menu item. A switch statement cannot be used because the user agents are not compile time constants.
1250 if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) { // Privacy Browser.
1251 menu.findItem(R.id.user_agent_privacy_browser).setChecked(true);
1252 } else if (currentUserAgent.equals(webViewDefaultUserAgent)) { // WebView Default.
1253 menu.findItem(R.id.user_agent_webview_default).setChecked(true);
1254 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) { // Firefox on Android.
1255 menu.findItem(R.id.user_agent_firefox_on_android).setChecked(true);
1256 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) { // Chrome on Android.
1257 menu.findItem(R.id.user_agent_chrome_on_android).setChecked(true);
1258 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) { // Safari on iOS.
1259 menu.findItem(R.id.user_agent_safari_on_ios).setChecked(true);
1260 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) { // Firefox on Linux.
1261 menu.findItem(R.id.user_agent_firefox_on_linux).setChecked(true);
1262 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) { // Chromium on Linux.
1263 menu.findItem(R.id.user_agent_chromium_on_linux).setChecked(true);
1264 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) { // Firefox on Windows.
1265 menu.findItem(R.id.user_agent_firefox_on_windows).setChecked(true);
1266 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) { // Chrome on Windows.
1267 menu.findItem(R.id.user_agent_chrome_on_windows).setChecked(true);
1268 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) { // Edge on Windows.
1269 menu.findItem(R.id.user_agent_edge_on_windows).setChecked(true);
1270 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) { // Internet Explorer on Windows.
1271 menu.findItem(R.id.user_agent_internet_explorer_on_windows).setChecked(true);
1272 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) { // Safari on macOS.
1273 menu.findItem(R.id.user_agent_safari_on_macos).setChecked(true);
1274 } else { // Custom user agent.
1275 menu.findItem(R.id.user_agent_custom).setChecked(true);
1278 // Instantiate the font size title and the selected font size menu item.
1279 String fontSizeTitle;
1280 MenuItem selectedFontSizeMenuItem;
1282 // Prepare the font size title and current size menu item.
1285 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
1286 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1290 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
1291 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1295 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
1296 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1300 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1301 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1305 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
1306 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1310 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
1311 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1315 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
1316 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1320 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
1321 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1325 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1326 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1330 // Set the font size title and select the current size menu item.
1331 fontSizeMenuItem.setTitle(fontSizeTitle);
1332 selectedFontSizeMenuItem.setChecked(true);
1334 // Run all the other default commands.
1335 super.onPrepareOptionsMenu(menu);
1337 // Display the menu.
1342 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1343 @SuppressLint("SetJavaScriptEnabled")
1344 public boolean onOptionsItemSelected(MenuItem menuItem) {
1345 // Reenter full screen browsing mode if it was interrupted by the options menu. <https://redmine.stoutner.com/issues/389>
1346 if (inFullScreenBrowsingMode) {
1347 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
1348 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1350 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
1352 /* Hide the system bars.
1353 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1354 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
1355 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1356 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1358 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
1359 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1362 // Get the selected menu item ID.
1363 int menuItemId = menuItem.getItemId();
1365 // Get a handle for the shared preferences.
1366 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1368 // Get a handle for the cookie manager.
1369 CookieManager cookieManager = CookieManager.getInstance();
1371 // Run the commands that correlate to the selected menu item.
1372 switch (menuItemId) {
1373 case R.id.toggle_javascript:
1374 // Toggle the JavaScript status.
1375 currentWebView.getSettings().setJavaScriptEnabled(!currentWebView.getSettings().getJavaScriptEnabled());
1377 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1378 updatePrivacyIcons(true);
1380 // Display a `Snackbar`.
1381 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScrip is enabled.
1382 Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1383 } else if (cookieManager.acceptCookie()) { // JavaScript is disabled, but first-party cookies are enabled.
1384 Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1385 } else { // Privacy mode.
1386 Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1389 // Reload the current WebView.
1390 currentWebView.reload();
1393 case R.id.add_or_edit_domain:
1394 if (currentWebView.getDomainSettingsApplied()) { // Edit the current domain settings.
1395 // Reapply the domain settings on returning to `MainWebViewActivity`.
1396 reapplyDomainSettingsOnRestart = true;
1398 // Create an intent to launch the domains activity.
1399 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1401 // Add the extra information to the intent.
1402 domainsIntent.putExtra("load_domain", currentWebView.getDomainSettingsDatabaseId());
1403 domainsIntent.putExtra("close_on_back", true);
1404 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1406 // Get the current certificate.
1407 SslCertificate sslCertificate = currentWebView.getCertificate();
1409 // Check to see if the SSL certificate is populated.
1410 if (sslCertificate != null) {
1411 // Extract the certificate to strings.
1412 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1413 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1414 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1415 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1416 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1417 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1418 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1419 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1421 // Add the certificate to the intent.
1422 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1423 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1424 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1425 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1426 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1427 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1428 domainsIntent.putExtra("ssl_start_date", startDateLong);
1429 domainsIntent.putExtra("ssl_end_date", endDateLong);
1432 // Check to see if the current IP addresses have been received.
1433 if (currentWebView.hasCurrentIpAddresses()) {
1434 // Add the current IP addresses to the intent.
1435 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1439 startActivity(domainsIntent);
1440 } else { // Add a new domain.
1441 // Apply the new domain settings on returning to `MainWebViewActivity`.
1442 reapplyDomainSettingsOnRestart = true;
1444 // Get the current domain
1445 Uri currentUri = Uri.parse(currentWebView.getUrl());
1446 String currentDomain = currentUri.getHost();
1448 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1449 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1451 // Create the domain and store the database ID.
1452 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1454 // Create an intent to launch the domains activity.
1455 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1457 // Add the extra information to the intent.
1458 domainsIntent.putExtra("load_domain", newDomainDatabaseId);
1459 domainsIntent.putExtra("close_on_back", true);
1460 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1462 // Get the current certificate.
1463 SslCertificate sslCertificate = currentWebView.getCertificate();
1465 // Check to see if the SSL certificate is populated.
1466 if (sslCertificate != null) {
1467 // Extract the certificate to strings.
1468 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1469 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1470 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1471 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1472 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1473 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1474 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1475 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1477 // Add the certificate to the intent.
1478 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1479 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1480 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1481 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1482 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1483 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1484 domainsIntent.putExtra("ssl_start_date", startDateLong);
1485 domainsIntent.putExtra("ssl_end_date", endDateLong);
1488 // Check to see if the current IP addresses have been received.
1489 if (currentWebView.hasCurrentIpAddresses()) {
1490 // Add the current IP addresses to the intent.
1491 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1495 startActivity(domainsIntent);
1499 case R.id.toggle_first_party_cookies:
1500 // Switch the first-party cookie status.
1501 cookieManager.setAcceptCookie(!cookieManager.acceptCookie());
1503 // Store the first-party cookie status.
1504 currentWebView.setAcceptFirstPartyCookies(cookieManager.acceptCookie());
1506 // Update the menu checkbox.
1507 menuItem.setChecked(cookieManager.acceptCookie());
1509 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1510 updatePrivacyIcons(true);
1512 // Display a snackbar.
1513 if (cookieManager.acceptCookie()) { // First-party cookies are enabled.
1514 Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1515 } else if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is still enabled.
1516 Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1517 } else { // Privacy mode.
1518 Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1521 // Reload the current WebView.
1522 currentWebView.reload();
1525 case R.id.toggle_third_party_cookies:
1526 if (Build.VERSION.SDK_INT >= 21) {
1527 // Switch the status of thirdPartyCookiesEnabled.
1528 cookieManager.setAcceptThirdPartyCookies(currentWebView, !cookieManager.acceptThirdPartyCookies(currentWebView));
1530 // Update the menu checkbox.
1531 menuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
1533 // Display a snackbar.
1534 if (cookieManager.acceptThirdPartyCookies(currentWebView)) {
1535 Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1537 Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1540 // Reload the current WebView.
1541 currentWebView.reload();
1542 } // Else do nothing because SDK < 21.
1545 case R.id.toggle_dom_storage:
1546 // Toggle the status of domStorageEnabled.
1547 currentWebView.getSettings().setDomStorageEnabled(!currentWebView.getSettings().getDomStorageEnabled());
1549 // Update the menu checkbox.
1550 menuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1552 // Update the privacy icon. `true` refreshes the app bar icons.
1553 updatePrivacyIcons(true);
1555 // Display a snackbar.
1556 if (currentWebView.getSettings().getDomStorageEnabled()) {
1557 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1559 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1562 // Reload the current WebView.
1563 currentWebView.reload();
1566 // Form data can be removed once the minimum API >= 26.
1567 case R.id.toggle_save_form_data:
1568 // Switch the status of saveFormDataEnabled.
1569 currentWebView.getSettings().setSaveFormData(!currentWebView.getSettings().getSaveFormData());
1571 // Update the menu checkbox.
1572 menuItem.setChecked(currentWebView.getSettings().getSaveFormData());
1574 // Display a snackbar.
1575 if (currentWebView.getSettings().getSaveFormData()) {
1576 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1578 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1581 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1582 updatePrivacyIcons(true);
1584 // Reload the current WebView.
1585 currentWebView.reload();
1588 case R.id.clear_cookies:
1589 Snackbar.make(findViewById(R.id.webviewpager), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1590 .setAction(R.string.undo, v -> {
1591 // Do nothing because everything will be handled by `onDismissed()` below.
1593 .addCallback(new Snackbar.Callback() {
1594 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1596 public void onDismissed(Snackbar snackbar, int event) {
1597 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1598 // Delete the cookies, which command varies by SDK.
1599 if (Build.VERSION.SDK_INT < 21) {
1600 cookieManager.removeAllCookie();
1602 cookieManager.removeAllCookies(null);
1610 case R.id.clear_dom_storage:
1611 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1612 .setAction(R.string.undo, v -> {
1613 // Do nothing because everything will be handled by `onDismissed()` below.
1615 .addCallback(new Snackbar.Callback() {
1616 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1618 public void onDismissed(Snackbar snackbar, int event) {
1619 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1620 // Delete the DOM Storage.
1621 WebStorage webStorage = WebStorage.getInstance();
1622 webStorage.deleteAllData();
1624 // Initialize a handler to manually delete the DOM storage files and directories.
1625 Handler deleteDomStorageHandler = new Handler();
1627 // Setup a runnable to manually delete the DOM storage files and directories.
1628 Runnable deleteDomStorageRunnable = () -> {
1630 // Get a handle for the runtime.
1631 Runtime runtime = Runtime.getRuntime();
1633 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
1634 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
1635 String privateDataDirectoryString = getApplicationInfo().dataDir;
1637 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1638 Process deleteLocalStorageProcess = runtime.exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1640 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1641 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1642 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1643 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1644 Process deleteDatabasesProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1646 // Wait for the processes to finish.
1647 deleteLocalStorageProcess.waitFor();
1648 deleteIndexProcess.waitFor();
1649 deleteQuotaManagerProcess.waitFor();
1650 deleteQuotaManagerJournalProcess.waitFor();
1651 deleteDatabasesProcess.waitFor();
1652 } catch (Exception exception) {
1653 // Do nothing if an error is thrown.
1657 // Manually delete the DOM storage files after 200 milliseconds.
1658 deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200);
1665 // Form data can be remove once the minimum API >= 26.
1666 case R.id.clear_form_data:
1667 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1668 .setAction(R.string.undo, v -> {
1669 // Do nothing because everything will be handled by `onDismissed()` below.
1671 .addCallback(new Snackbar.Callback() {
1672 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1674 public void onDismissed(Snackbar snackbar, int event) {
1675 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1676 // Delete the form data.
1677 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1678 mainWebViewDatabase.clearFormData();
1686 // Toggle the EasyList status.
1687 currentWebView.enableBlocklist(NestedScrollWebView.EASY_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST));
1689 // Update the menu checkbox.
1690 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST));
1692 // Reload the current WebView.
1693 currentWebView.reload();
1696 case R.id.easyprivacy:
1697 // Toggle the EasyPrivacy status.
1698 currentWebView.enableBlocklist(NestedScrollWebView.EASY_PRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY));
1700 // Update the menu checkbox.
1701 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY));
1703 // Reload the current WebView.
1704 currentWebView.reload();
1707 case R.id.fanboys_annoyance_list:
1708 // Toggle Fanboy's Annoyance List status.
1709 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1711 // Update the menu checkbox.
1712 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1714 // Update the staus of Fanboy's Social Blocking List.
1715 MenuItem fanboysSocialBlockingListMenuItem = optionsMenu.findItem(R.id.fanboys_social_blocking_list);
1716 fanboysSocialBlockingListMenuItem.setEnabled(!currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1718 // Reload the current WebView.
1719 currentWebView.reload();
1722 case R.id.fanboys_social_blocking_list:
1723 // Toggle Fanboy's Social Blocking List status.
1724 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1726 // Update the menu checkbox.
1727 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1729 // Reload the current WebView.
1730 currentWebView.reload();
1733 case R.id.ultraprivacy:
1734 // Toggle the UltraPrivacy status.
1735 currentWebView.enableBlocklist(NestedScrollWebView.ULTRA_PRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY));
1737 // Update the menu checkbox.
1738 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY));
1740 // Reload the current WebView.
1741 currentWebView.reload();
1744 case R.id.block_all_third_party_requests:
1745 //Toggle the third-party requests blocker status.
1746 currentWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, !currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1748 // Update the menu checkbox.
1749 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1751 // Reload the current WebView.
1752 currentWebView.reload();
1755 case R.id.user_agent_privacy_browser:
1756 // Update the user agent.
1757 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
1759 // Reload the current WebView.
1760 currentWebView.reload();
1763 case R.id.user_agent_webview_default:
1764 // Update the user agent.
1765 currentWebView.getSettings().setUserAgentString("");
1767 // Reload the current WebView.
1768 currentWebView.reload();
1771 case R.id.user_agent_firefox_on_android:
1772 // Update the user agent.
1773 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
1775 // Reload the current WebView.
1776 currentWebView.reload();
1779 case R.id.user_agent_chrome_on_android:
1780 // Update the user agent.
1781 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
1783 // Reload the current WebView.
1784 currentWebView.reload();
1787 case R.id.user_agent_safari_on_ios:
1788 // Update the user agent.
1789 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
1791 // Reload the current WebView.
1792 currentWebView.reload();
1795 case R.id.user_agent_firefox_on_linux:
1796 // Update the user agent.
1797 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
1799 // Reload the current WebView.
1800 currentWebView.reload();
1803 case R.id.user_agent_chromium_on_linux:
1804 // Update the user agent.
1805 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
1807 // Reload the current WebView.
1808 currentWebView.reload();
1811 case R.id.user_agent_firefox_on_windows:
1812 // Update the user agent.
1813 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
1815 // Reload the current WebView.
1816 currentWebView.reload();
1819 case R.id.user_agent_chrome_on_windows:
1820 // Update the user agent.
1821 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
1823 // Reload the current WebView.
1824 currentWebView.reload();
1827 case R.id.user_agent_edge_on_windows:
1828 // Update the user agent.
1829 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
1831 // Reload the current WebView.
1832 currentWebView.reload();
1835 case R.id.user_agent_internet_explorer_on_windows:
1836 // Update the user agent.
1837 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
1839 // Reload the current WebView.
1840 currentWebView.reload();
1843 case R.id.user_agent_safari_on_macos:
1844 // Update the user agent.
1845 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
1847 // Reload the current WebView.
1848 currentWebView.reload();
1851 case R.id.user_agent_custom:
1852 // Update the user agent.
1853 currentWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
1855 // Reload the current WebView.
1856 currentWebView.reload();
1859 case R.id.font_size_twenty_five_percent:
1860 currentWebView.getSettings().setTextZoom(25);
1863 case R.id.font_size_fifty_percent:
1864 currentWebView.getSettings().setTextZoom(50);
1867 case R.id.font_size_seventy_five_percent:
1868 currentWebView.getSettings().setTextZoom(75);
1871 case R.id.font_size_one_hundred_percent:
1872 currentWebView.getSettings().setTextZoom(100);
1875 case R.id.font_size_one_hundred_twenty_five_percent:
1876 currentWebView.getSettings().setTextZoom(125);
1879 case R.id.font_size_one_hundred_fifty_percent:
1880 currentWebView.getSettings().setTextZoom(150);
1883 case R.id.font_size_one_hundred_seventy_five_percent:
1884 currentWebView.getSettings().setTextZoom(175);
1887 case R.id.font_size_two_hundred_percent:
1888 currentWebView.getSettings().setTextZoom(200);
1891 case R.id.swipe_to_refresh:
1892 // Toggle the stored status of swipe to refresh.
1893 currentWebView.setSwipeToRefresh(!currentWebView.getSwipeToRefresh());
1895 // Get a handle for the swipe refresh layout.
1896 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
1898 // Update the swipe refresh layout.
1899 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
1900 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.
1901 // Only enable the swipe refresh layout if the WebView is scrolled to the top.
1902 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
1903 } else { // For API < 23, the swipe refresh layout is always enabled.
1904 // Enable the swipe refresh layout.
1905 swipeRefreshLayout.setEnabled(true);
1907 } else { // Swipe to refresh is disabled.
1908 // Disable the swipe refresh layout.
1909 swipeRefreshLayout.setEnabled(false);
1913 case R.id.display_images:
1914 if (currentWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1915 // Disable loading of images.
1916 currentWebView.getSettings().setLoadsImagesAutomatically(false);
1918 // Reload the website to remove existing images.
1919 currentWebView.reload();
1920 } else { // Images are not currently loaded automatically.
1921 // Enable loading of images. Missing images will be loaded without the need for a reload.
1922 currentWebView.getSettings().setLoadsImagesAutomatically(true);
1926 case R.id.night_mode:
1927 // Toggle night mode.
1928 currentWebView.setNightMode(!currentWebView.getNightMode());
1930 // Enable or disable JavaScript according to night mode, the global preference, and any domain settings.
1931 if (currentWebView.getNightMode()) { // Night mode is enabled, which requires JavaScript.
1932 // Enable JavaScript.
1933 currentWebView.getSettings().setJavaScriptEnabled(true);
1934 } else if (currentWebView.getDomainSettingsApplied()) { // Night mode is disabled and domain settings are applied. Set JavaScript according to the domain settings.
1935 // Apply the JavaScript preference that was stored the last time domain settings were loaded.
1936 currentWebView.getSettings().setJavaScriptEnabled(currentWebView.getDomainSettingsJavaScriptEnabled());
1937 } else { // Night mode is disabled and domain settings are not applied. Set JavaScript according to the global preference.
1938 // Apply the JavaScript preference.
1939 currentWebView.getSettings().setJavaScriptEnabled(sharedPreferences.getBoolean("javascript", false));
1942 // Update the privacy icons.
1943 updatePrivacyIcons(false);
1945 // Reload the website.
1946 currentWebView.reload();
1949 case R.id.find_on_page:
1950 // Get a handle for the views.
1951 Toolbar toolbar = findViewById(R.id.toolbar);
1952 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
1953 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
1955 // Set the minimum height of the find on page linear layout to match the toolbar.
1956 findOnPageLinearLayout.setMinimumHeight(toolbar.getHeight());
1958 // Hide the toolbar.
1959 toolbar.setVisibility(View.GONE);
1961 // Show the find on page linear layout.
1962 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1964 // Display the keyboard. The app must wait 200 ms before running the command to work around a bug in Android.
1965 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1966 findOnPageEditText.postDelayed(() -> {
1967 // Set the focus on `findOnPageEditText`.
1968 findOnPageEditText.requestFocus();
1970 // Get a handle for the input method manager.
1971 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1973 // Remove the lint warning below that the input method manager might be null.
1974 assert inputMethodManager != null;
1976 // Display the keyboard. `0` sets no input flags.
1977 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1981 case R.id.view_source:
1982 // Create an intent to launch the view source activity.
1983 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
1985 // Add the variables to the intent.
1986 viewSourceIntent.putExtra("user_agent", currentWebView.getSettings().getUserAgentString());
1987 viewSourceIntent.putExtra("current_url", currentWebView.getUrl());
1990 startActivity(viewSourceIntent);
1993 case R.id.share_url:
1994 // Setup the share string.
1995 String shareString = currentWebView.getTitle() + " – " + currentWebView.getUrl();
1997 // Create the share intent.
1998 Intent shareIntent = new Intent(Intent.ACTION_SEND);
1999 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
2000 shareIntent.setType("text/plain");
2003 startActivity(Intent.createChooser(shareIntent, getString(R.string.share_url)));
2007 // Get a print manager instance.
2008 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
2010 // Remove the lint error below that print manager might be null.
2011 assert printManager != null;
2013 // Create a print document adapter from the current WebView.
2014 PrintDocumentAdapter printDocumentAdapter = currentWebView.createPrintDocumentAdapter();
2016 // Print the document.
2017 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
2020 case R.id.open_with_app:
2021 openWithApp(currentWebView.getUrl());
2024 case R.id.open_with_browser:
2025 openWithBrowser(currentWebView.getUrl());
2028 case R.id.add_to_homescreen:
2029 // Instantiate the create home screen shortcut dialog.
2030 DialogFragment createHomeScreenShortcutDialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView.getTitle(), currentWebView.getUrl(),
2031 currentWebView.getFavoriteOrDefaultIcon());
2033 // Show the create home screen shortcut dialog.
2034 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2037 case R.id.proxy_through_orbot:
2038 // Toggle the proxy through Orbot variable.
2039 proxyThroughOrbot = !proxyThroughOrbot;
2041 // Apply the proxy through Orbot settings.
2042 applyProxyThroughOrbot(true);
2046 if (menuItem.getTitle().equals(getString(R.string.refresh))) { // The refresh button was pushed.
2047 // Reload the current WebView.
2048 currentWebView.reload();
2049 } else { // The stop button was pushed.
2050 // Stop the loading of the WebView.
2051 currentWebView.stopLoading();
2055 case R.id.ad_consent:
2056 // Display the ad consent dialog.
2057 DialogFragment adConsentDialogFragment = new AdConsentDialog();
2058 adConsentDialogFragment.show(getSupportFragmentManager(), getString(R.string.ad_consent));
2062 // Don't consume the event.
2063 return super.onOptionsItemSelected(menuItem);
2067 // removeAllCookies is deprecated, but it is required for API < 21.
2069 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2070 // Get the menu item ID.
2071 int menuItemId = menuItem.getItemId();
2073 // Get a handle for the shared preferences.
2074 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2076 // Run the commands that correspond to the selected menu item.
2077 switch (menuItemId) {
2078 case R.id.clear_and_exit:
2079 // Clear and exit Privacy Browser.
2084 // Select the homepage based on the proxy through Orbot status.
2085 if (proxyThroughOrbot) {
2086 // Load the Tor homepage.
2087 loadUrl(sharedPreferences.getString("tor_homepage", getString(R.string.tor_homepage_default_value)));
2089 // Load the normal homepage.
2090 loadUrl(sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
2095 if (currentWebView.canGoBack()) {
2096 // Reset the current domain name so that navigation works if third-party requests are blocked.
2097 currentWebView.resetCurrentDomainName();
2099 // Set navigating history so that the domain settings are applied when the new URL is loaded.
2100 currentWebView.setNavigatingHistory(true);
2102 // Load the previous website in the history.
2103 currentWebView.goBack();
2108 if (currentWebView.canGoForward()) {
2109 // Reset the current domain name so that navigation works if third-party requests are blocked.
2110 currentWebView.resetCurrentDomainName();
2112 // Set navigating history so that the domain settings are applied when the new URL is loaded.
2113 currentWebView.setNavigatingHistory(true);
2115 // Load the next website in the history.
2116 currentWebView.goForward();
2121 // Instantiate the URL history dialog.
2122 DialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(currentWebView.getWebViewFragmentId());
2124 // Show the URL history dialog.
2125 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2129 // Populate the resource requests.
2130 RequestsActivity.resourceRequests = currentWebView.getResourceRequests();
2132 // Create an intent to launch the Requests activity.
2133 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2135 // Add the block third-party requests status to the intent.
2136 requestsIntent.putExtra("block_all_third_party_requests", currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
2139 startActivity(requestsIntent);
2142 case R.id.downloads:
2143 // Launch the system Download Manager.
2144 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2146 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2147 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2149 startActivity(downloadManagerIntent);
2153 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2154 reapplyDomainSettingsOnRestart = true;
2156 // Launch the domains activity.
2157 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2159 // Add the extra information to the intent.
2160 domainsIntent.putExtra("current_url", currentWebView.getUrl());
2162 // Get the current certificate.
2163 SslCertificate sslCertificate = currentWebView.getCertificate();
2165 // Check to see if the SSL certificate is populated.
2166 if (sslCertificate != null) {
2167 // Extract the certificate to strings.
2168 String issuedToCName = sslCertificate.getIssuedTo().getCName();
2169 String issuedToOName = sslCertificate.getIssuedTo().getOName();
2170 String issuedToUName = sslCertificate.getIssuedTo().getUName();
2171 String issuedByCName = sslCertificate.getIssuedBy().getCName();
2172 String issuedByOName = sslCertificate.getIssuedBy().getOName();
2173 String issuedByUName = sslCertificate.getIssuedBy().getUName();
2174 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
2175 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
2177 // Add the certificate to the intent.
2178 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
2179 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
2180 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
2181 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
2182 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
2183 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
2184 domainsIntent.putExtra("ssl_start_date", startDateLong);
2185 domainsIntent.putExtra("ssl_end_date", endDateLong);
2188 // Check to see if the current IP addresses have been received.
2189 if (currentWebView.hasCurrentIpAddresses()) {
2190 // Add the current IP addresses to the intent.
2191 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
2195 startActivity(domainsIntent);
2199 // Set the flag to reapply app settings on restart when returning from Settings.
2200 reapplyAppSettingsOnRestart = true;
2202 // Set the flag to reapply the domain settings on restart when returning from Settings.
2203 reapplyDomainSettingsOnRestart = true;
2205 // Launch the settings activity.
2206 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2207 startActivity(settingsIntent);
2210 case R.id.import_export:
2211 // Launch the import/export activity.
2212 Intent importExportIntent = new Intent (this, ImportExportActivity.class);
2213 startActivity(importExportIntent);
2217 // Launch the logcat activity.
2218 Intent logcatIntent = new Intent(this, LogcatActivity.class);
2219 startActivity(logcatIntent);
2223 // Launch `GuideActivity`.
2224 Intent guideIntent = new Intent(this, GuideActivity.class);
2225 startActivity(guideIntent);
2229 // Create an intent to launch the about activity.
2230 Intent aboutIntent = new Intent(this, AboutActivity.class);
2232 // Create a string array for the blocklist versions.
2233 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],
2234 ultraPrivacy.get(0).get(0)[0]};
2236 // Add the blocklist versions to the intent.
2237 aboutIntent.putExtra("blocklist_versions", blocklistVersions);
2240 startActivity(aboutIntent);
2244 // Get a handle for the drawer layout.
2245 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
2247 // Close the navigation drawer.
2248 drawerLayout.closeDrawer(GravityCompat.START);
2253 public void onPostCreate(Bundle savedInstanceState) {
2254 // Run the default commands.
2255 super.onPostCreate(savedInstanceState);
2257 // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished. This creates the navigation drawer icon.
2258 actionBarDrawerToggle.syncState();
2262 public void onConfigurationChanged(Configuration newConfig) {
2263 // Run the default commands.
2264 super.onConfigurationChanged(newConfig);
2266 // Get the status bar pixel size.
2267 int statusBarResourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
2268 int statusBarPixelSize = getResources().getDimensionPixelSize(statusBarResourceId);
2270 // Get the resource density.
2271 float screenDensity = getResources().getDisplayMetrics().density;
2273 // Recalculate the drawer header padding.
2274 drawerHeaderPaddingLeftAndRight = (int) (15 * screenDensity);
2275 drawerHeaderPaddingTop = statusBarPixelSize + (int) (4 * screenDensity);
2276 drawerHeaderPaddingBottom = (int) (8 * screenDensity);
2278 // Reload the ad for the free flavor if not in full screen mode.
2279 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2280 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2281 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
2284 // `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:
2285 // https://code.google.com/p/android/issues/detail?id=20493#c8
2286 // ActivityCompat.invalidateOptionsMenu(this);
2290 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2291 // Store the hit test result.
2292 final WebView.HitTestResult hitTestResult = currentWebView.getHitTestResult();
2294 // Create the URL strings.
2295 final String imageUrl;
2296 final String linkUrl;
2298 // Get handles for the system managers.
2299 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2300 FragmentManager fragmentManager = getSupportFragmentManager();
2301 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2303 // Remove the lint errors below that the clipboard manager might be null.
2304 assert clipboardManager != null;
2306 // Process the link according to the type.
2307 switch (hitTestResult.getType()) {
2308 // `SRC_ANCHOR_TYPE` is a link.
2309 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2310 // Get the target URL.
2311 linkUrl = hitTestResult.getExtra();
2313 // Set the target URL as the title of the `ContextMenu`.
2314 menu.setHeaderTitle(linkUrl);
2316 // Add an Open in New Tab entry.
2317 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2318 // Load the link URL in a new tab.
2323 // Add an Open with App entry.
2324 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2325 openWithApp(linkUrl);
2329 // Add an Open with Browser entry.
2330 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2331 openWithBrowser(linkUrl);
2335 // Add a Copy URL entry.
2336 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2337 // Save the link URL in a `ClipData`.
2338 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2340 // Set the `ClipData` as the clipboard's primary clip.
2341 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2345 // Add a Download URL entry.
2346 menu.add(R.string.download_url).setOnMenuItemClickListener((MenuItem item) -> {
2347 // Check if the download should be processed by an external app.
2348 if (sharedPreferences.getBoolean("download_with_external_app", false)) { // Download with an external app.
2349 openUrlWithExternalApp(linkUrl);
2350 } else { // Download with Android's download manager.
2351 // Check to see if the storage permission has already been granted.
2352 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission needs to be requested.
2353 // Store the variables for future use by `onRequestPermissionsResult()`.
2354 downloadUrl = linkUrl;
2355 downloadContentDisposition = "none";
2356 downloadContentLength = -1;
2358 // Show a dialog if the user has previously denied the permission.
2359 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2360 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
2361 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
2363 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
2364 downloadLocationPermissionDialogFragment.show(fragmentManager, getString(R.string.download_location));
2365 } else { // Show the permission request directly.
2366 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
2367 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2369 } else { // The storage permission has already been granted.
2370 // Get a handle for the download file alert dialog.
2371 DialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(linkUrl, "none", -1);
2373 // Show the download file alert dialog.
2374 downloadFileDialogFragment.show(fragmentManager, getString(R.string.download));
2380 // Add a Cancel entry, which by default closes the context menu.
2381 menu.add(R.string.cancel);
2384 case WebView.HitTestResult.EMAIL_TYPE:
2385 // Get the target URL.
2386 linkUrl = hitTestResult.getExtra();
2388 // Set the target URL as the title of the `ContextMenu`.
2389 menu.setHeaderTitle(linkUrl);
2391 // Add a Write Email entry.
2392 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2393 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2394 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2396 // Parse the url and set it as the data for the `Intent`.
2397 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2399 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2400 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2403 startActivity(emailIntent);
2407 // Add a Copy Email Address entry.
2408 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2409 // Save the email address in a `ClipData`.
2410 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2412 // Set the `ClipData` as the clipboard's primary clip.
2413 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2417 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2418 menu.add(R.string.cancel);
2421 // `IMAGE_TYPE` is an image. `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link. Privacy Browser processes them the same.
2422 case WebView.HitTestResult.IMAGE_TYPE:
2423 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2424 // Get the image URL.
2425 imageUrl = hitTestResult.getExtra();
2427 // Set the image URL as the title of the context menu.
2428 menu.setHeaderTitle(imageUrl);
2430 // Add an Open in New Tab entry.
2431 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2432 // Load the image URL in a new tab.
2433 addNewTab(imageUrl);
2437 // Add a View Image entry.
2438 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2443 // Add a `Download Image` entry.
2444 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2445 // Check if the download should be processed by an external app.
2446 if (sharedPreferences.getBoolean("download_with_external_app", false)) { // Download with an external app.
2447 openUrlWithExternalApp(imageUrl);
2448 } else { // Download with Android's download manager.
2449 // Check to see if the storage permission has already been granted.
2450 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission needs to be requested.
2451 // Store the image URL for use by `onRequestPermissionResult()`.
2452 downloadImageUrl = imageUrl;
2454 // Show a dialog if the user has previously denied the permission.
2455 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2456 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2457 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2459 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
2460 downloadLocationPermissionDialogFragment.show(fragmentManager, getString(R.string.download_location));
2461 } else { // Show the permission request directly.
2462 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
2463 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2465 } else { // The storage permission has already been granted.
2466 // Get a handle for the download image alert dialog.
2467 DialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2469 // Show the download image alert dialog.
2470 downloadImageDialogFragment.show(fragmentManager, getString(R.string.download));
2476 // Add a `Copy URL` entry.
2477 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2478 // Save the image URL in a `ClipData`.
2479 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2481 // Set the `ClipData` as the clipboard's primary clip.
2482 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2486 // Add an Open with App entry.
2487 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2488 openWithApp(imageUrl);
2492 // Add an Open with Browser entry.
2493 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2494 openWithBrowser(imageUrl);
2498 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2499 menu.add(R.string.cancel);
2505 public void onCreateBookmark(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2506 // Get a handle for the bookmarks list view.
2507 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2509 // Get the views from the dialog fragment.
2510 EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
2511 EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
2513 // Extract the strings from the edit texts.
2514 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2515 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2517 // Create a favorite icon byte array output stream.
2518 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2520 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2521 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2523 // Convert the favorite icon byte array stream to a byte array.
2524 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2526 // Display the new bookmark below the current items in the (0 indexed) list.
2527 int newBookmarkDisplayOrder = bookmarksListView.getCount();
2529 // Create the bookmark.
2530 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2532 // Update the bookmarks cursor with the current contents of this folder.
2533 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2535 // Update the list view.
2536 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2538 // Scroll to the new bookmark.
2539 bookmarksListView.setSelection(newBookmarkDisplayOrder);
2543 public void onCreateBookmarkFolder(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2544 // Get a handle for the bookmarks list view.
2545 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2547 // Get handles for the views in the dialog fragment.
2548 EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
2549 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
2550 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
2552 // Get new folder name string.
2553 String folderNameString = createFolderNameEditText.getText().toString();
2555 // Create a folder icon bitmap.
2556 Bitmap folderIconBitmap;
2558 // Set the folder icon bitmap according to the dialog.
2559 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
2560 // Get the default folder icon drawable.
2561 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2563 // Convert the folder icon drawable to a bitmap drawable.
2564 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2566 // Convert the folder icon bitmap drawable to a bitmap.
2567 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2568 } else { // Use the WebView favorite icon.
2569 // Copy the favorite icon bitmap to the folder icon bitmap.
2570 folderIconBitmap = favoriteIconBitmap;
2573 // Create a folder icon byte array output stream.
2574 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2576 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2577 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2579 // Convert the folder icon byte array stream to a byte array.
2580 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2582 // Move all the bookmarks down one in the display order.
2583 for (int i = 0; i < bookmarksListView.getCount(); i++) {
2584 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2585 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2588 // Create the folder, which will be placed at the top of the `ListView`.
2589 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2591 // Update the bookmarks cursor with the current contents of this folder.
2592 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2594 // Update the `ListView`.
2595 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2597 // Scroll to the new folder.
2598 bookmarksListView.setSelection(0);
2602 public void onSaveBookmark(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, Bitmap favoriteIconBitmap) {
2603 // Get handles for the views from `dialogFragment`.
2604 EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
2605 EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
2606 RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
2608 // Store the bookmark strings.
2609 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
2610 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
2612 // Update the bookmark.
2613 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
2614 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
2615 } else { // Update the bookmark using the `WebView` favorite icon.
2616 // Create a favorite icon byte array output stream.
2617 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2619 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2620 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
2622 // Convert the favorite icon byte array stream to a byte array.
2623 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
2625 // Update the bookmark and the favorite icon.
2626 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
2629 // Update the bookmarks cursor with the current contents of this folder.
2630 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2632 // Update the list view.
2633 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2637 public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId, Bitmap favoriteIconBitmap) {
2638 // Get handles for the views from `dialogFragment`.
2639 EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
2640 RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
2641 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
2642 ImageView defaultFolderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
2644 // Get the new folder name.
2645 String newFolderNameString = editFolderNameEditText.getText().toString();
2647 // Check if the favorite icon has changed.
2648 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
2649 // Update the name in the database.
2650 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2651 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
2652 // Create the new folder icon Bitmap.
2653 Bitmap folderIconBitmap;
2655 // Populate the new folder icon bitmap.
2656 if (defaultFolderIconRadioButton.isChecked()) {
2657 // Get the default folder icon drawable.
2658 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2660 // Convert the folder icon drawable to a bitmap drawable.
2661 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2663 // Convert the folder icon bitmap drawable to a bitmap.
2664 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2665 } else { // Use the `WebView` favorite icon.
2666 // Copy the favorite icon bitmap to the folder icon bitmap.
2667 folderIconBitmap = favoriteIconBitmap;
2670 // Create a folder icon byte array output stream.
2671 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2673 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2674 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2676 // Convert the folder icon byte array stream to a byte array.
2677 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2679 // Update the folder icon in the database.
2680 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, newFolderIconByteArray);
2681 } else { // The folder icon and the name have changed.
2682 // Get the new folder icon `Bitmap`.
2683 Bitmap folderIconBitmap;
2684 if (defaultFolderIconRadioButton.isChecked()) {
2685 // Get the default folder icon drawable.
2686 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2688 // Convert the folder icon drawable to a bitmap drawable.
2689 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2691 // Convert the folder icon bitmap drawable to a bitmap.
2692 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2693 } else { // Use the `WebView` favorite icon.
2694 // Copy the favorite icon bitmap to the folder icon bitmap.
2695 folderIconBitmap = favoriteIconBitmap;
2698 // Create a folder icon byte array output stream.
2699 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2701 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2702 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2704 // Convert the folder icon byte array stream to a byte array.
2705 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2707 // Update the folder name and icon in the database.
2708 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, newFolderIconByteArray);
2711 // Update the bookmarks cursor with the current contents of this folder.
2712 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2714 // Update the `ListView`.
2715 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2719 public void onCloseDownloadLocationPermissionDialog(int downloadType) {
2720 switch (downloadType) {
2721 case DownloadLocationPermissionDialog.DOWNLOAD_FILE:
2722 // Request the WRITE_EXTERNAL_STORAGE permission with a file request code.
2723 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2726 case DownloadLocationPermissionDialog.DOWNLOAD_IMAGE:
2727 // Request the WRITE_EXTERNAL_STORAGE permission with an image request code.
2728 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2734 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
2735 // Get a handle for the fragment manager.
2736 FragmentManager fragmentManager = getSupportFragmentManager();
2738 switch (requestCode) {
2739 case DOWNLOAD_FILE_REQUEST_CODE:
2740 // Show the download file alert dialog. When the dialog closes, the correct command will be used based on the permission status.
2741 DialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(downloadUrl, downloadContentDisposition, downloadContentLength);
2743 // On API 23, displaying the fragment must be delayed or the app will crash.
2744 if (Build.VERSION.SDK_INT == 23) {
2745 new Handler().postDelayed(() -> downloadFileDialogFragment.show(fragmentManager, getString(R.string.download)), 500);
2747 downloadFileDialogFragment.show(fragmentManager, getString(R.string.download));
2750 // Reset the download variables.
2752 downloadContentDisposition = "";
2753 downloadContentLength = 0;
2756 case DOWNLOAD_IMAGE_REQUEST_CODE:
2757 // Show the download image alert dialog. When the dialog closes, the correct command will be used based on the permission status.
2758 DialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(downloadImageUrl);
2760 // On API 23, displaying the fragment must be delayed or the app will crash.
2761 if (Build.VERSION.SDK_INT == 23) {
2762 new Handler().postDelayed(() -> downloadImageDialogFragment.show(fragmentManager, getString(R.string.download)), 500);
2764 downloadImageDialogFragment.show(fragmentManager, getString(R.string.download));
2767 // Reset the image URL variable.
2768 downloadImageUrl = "";
2774 public void onDownloadImage(DialogFragment dialogFragment, String imageUrl) {
2775 // Download the image if it has an HTTP or HTTPS URI.
2776 if (imageUrl.startsWith("http")) {
2777 // Get a handle for the system `DOWNLOAD_SERVICE`.
2778 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2780 // Parse `imageUrl`.
2781 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
2783 // Get a handle for the cookie manager.
2784 CookieManager cookieManager = CookieManager.getInstance();
2786 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
2787 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2788 if (cookieManager.acceptCookie()) {
2789 // Get the cookies for `imageUrl`.
2790 String cookies = cookieManager.getCookie(imageUrl);
2792 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2793 downloadRequest.addRequestHeader("Cookie", cookies);
2796 // Get the file name from the dialog fragment.
2797 EditText downloadImageNameEditText = dialogFragment.getDialog().findViewById(R.id.download_image_name);
2798 String imageName = downloadImageNameEditText.getText().toString();
2800 // Specify the download location.
2801 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
2802 // Download to the public download directory.
2803 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, imageName);
2804 } else { // External write permission denied.
2805 // Download to the app's external download directory.
2806 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, imageName);
2809 // Allow `MediaScanner` to index the download if it is a media file.
2810 downloadRequest.allowScanningByMediaScanner();
2812 // Add the URL as the description for the download.
2813 downloadRequest.setDescription(imageUrl);
2815 // Show the download notification after the download is completed.
2816 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2818 // Remove the lint warning below that `downloadManager` might be `null`.
2819 assert downloadManager != null;
2821 // Initiate the download.
2822 downloadManager.enqueue(downloadRequest);
2823 } else { // The image is not an HTTP or HTTPS URI.
2824 Snackbar.make(currentWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
2829 public void onDownloadFile(DialogFragment dialogFragment, String downloadUrl) {
2830 // Download the file if it has an HTTP or HTTPS URI.
2831 if (downloadUrl.startsWith("http")) {
2832 // Get a handle for the system `DOWNLOAD_SERVICE`.
2833 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2835 // Parse `downloadUrl`.
2836 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
2838 // Get a handle for the cookie manager.
2839 CookieManager cookieManager = CookieManager.getInstance();
2841 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
2842 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2843 if (cookieManager.acceptCookie()) {
2844 // Get the cookies for `downloadUrl`.
2845 String cookies = cookieManager.getCookie(downloadUrl);
2847 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2848 downloadRequest.addRequestHeader("Cookie", cookies);
2851 // Get the file name from the dialog fragment.
2852 EditText downloadFileNameEditText = dialogFragment.getDialog().findViewById(R.id.download_file_name);
2853 String fileName = downloadFileNameEditText.getText().toString();
2855 // Specify the download location.
2856 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
2857 // Download to the public download directory.
2858 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
2859 } else { // External write permission denied.
2860 // Download to the app's external download directory.
2861 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, fileName);
2864 // Allow `MediaScanner` to index the download if it is a media file.
2865 downloadRequest.allowScanningByMediaScanner();
2867 // Add the URL as the description for the download.
2868 downloadRequest.setDescription(downloadUrl);
2870 // Show the download notification after the download is completed.
2871 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2873 // Remove the lint warning below that `downloadManager` might be `null`.
2874 assert downloadManager != null;
2876 // Initiate the download.
2877 downloadManager.enqueue(downloadRequest);
2878 } else { // The download is not an HTTP or HTTPS URI.
2879 Snackbar.make(currentWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
2883 // Override `onBackPressed` to handle the navigation drawer and and the WebView.
2885 public void onBackPressed() {
2886 // Get a handle for the drawer layout and the tab layout.
2887 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
2888 TabLayout tabLayout = findViewById(R.id.tablayout);
2890 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
2891 // Close the navigation drawer.
2892 drawerLayout.closeDrawer(GravityCompat.START);
2893 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
2894 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
2895 // close the bookmarks drawer.
2896 drawerLayout.closeDrawer(GravityCompat.END);
2897 } else { // A subfolder is displayed.
2898 // Place the former parent folder in `currentFolder`.
2899 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolderName(currentBookmarksFolder);
2901 // Load the new folder.
2902 loadBookmarksFolder();
2904 } else if (currentWebView.canGoBack()) { // There is at least one item in the current WebView history.
2905 // Reset the current domain name so that navigation works if third-party requests are blocked.
2906 currentWebView.resetCurrentDomainName();
2908 // Set navigating history so that the domain settings are applied when the new URL is loaded.
2909 currentWebView.setNavigatingHistory(true);
2912 currentWebView.goBack();
2913 } else if (tabLayout.getTabCount() > 1) { // There are at least two tabs.
2914 // Close the current tab.
2916 } else { // There isn't anything to do in Privacy Browser.
2917 // Run the default commands.
2918 super.onBackPressed();
2920 // Manually kill Privacy Browser. Otherwise, it is glitchy when restarted.
2925 // 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.
2927 public void onActivityResult(int requestCode, int resultCode, Intent data) {
2928 // File uploads only work on API >= 21.
2929 if (Build.VERSION.SDK_INT >= 21) {
2930 // Pass the file to the WebView.
2931 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
2935 private void loadUrlFromTextBox() {
2936 // Get a handle for the URL edit text.
2937 EditText urlEditText = findViewById(R.id.url_edittext);
2939 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
2940 String unformattedUrlString = urlEditText.getText().toString().trim();
2942 // Initialize the formatted URL string.
2945 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
2946 if (unformattedUrlString.startsWith("content://")) { // This is a Content URL.
2947 // Load the entire content URL.
2948 url = unformattedUrlString;
2949 } else if (Patterns.WEB_URL.matcher(unformattedUrlString).matches() || unformattedUrlString.startsWith("http://") || unformattedUrlString.startsWith("https://") ||
2950 unformattedUrlString.startsWith("file://")) { // This is a standard URL.
2951 // Add `https://` at the beginning if there is no protocol. Otherwise the app will segfault.
2952 if (!unformattedUrlString.startsWith("http") && !unformattedUrlString.startsWith("file://") && !unformattedUrlString.startsWith("content://")) {
2953 unformattedUrlString = "https://" + unformattedUrlString;
2956 // Initialize `unformattedUrl`.
2957 URL unformattedUrl = null;
2959 // 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.
2961 unformattedUrl = new URL(unformattedUrlString);
2962 } catch (MalformedURLException e) {
2963 e.printStackTrace();
2966 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2967 String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2968 String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2969 String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2970 String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2971 String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2974 Uri.Builder uri = new Uri.Builder();
2975 uri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2977 // Decode the URI as a UTF-8 string in.
2979 url = URLDecoder.decode(uri.build().toString(), "UTF-8");
2980 } catch (UnsupportedEncodingException exception) {
2981 // Do nothing. The formatted URL string will remain blank.
2983 } else if (!unformattedUrlString.isEmpty()){ // This is not a URL, but rather a search string.
2984 // Create an encoded URL String.
2985 String encodedUrlString;
2987 // Sanitize the search input.
2989 encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2990 } catch (UnsupportedEncodingException exception) {
2991 encodedUrlString = "";
2994 // Add the base search URL.
2995 url = searchURL + encodedUrlString;
2998 // 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.
2999 urlEditText.clearFocus();
3005 private void loadUrl(String url) {
3006 // Sanitize the URL.
3007 url = sanitizeUrl(url);
3009 // Apply the domain settings.
3010 applyDomainSettings(currentWebView, url, true, false);
3013 currentWebView.loadUrl(url, customHeaders);
3016 public void findPreviousOnPage(View view) {
3017 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
3018 currentWebView.findNext(false);
3021 public void findNextOnPage(View view) {
3022 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
3023 currentWebView.findNext(true);
3026 public void closeFindOnPage(View view) {
3027 // Get a handle for the views.
3028 Toolbar toolbar = findViewById(R.id.toolbar);
3029 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
3030 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
3032 // Delete the contents of `find_on_page_edittext`.
3033 findOnPageEditText.setText(null);
3035 // Clear the highlighted phrases if the WebView is not null.
3036 if (currentWebView != null) {
3037 currentWebView.clearMatches();
3040 // Hide the find on page linear layout.
3041 findOnPageLinearLayout.setVisibility(View.GONE);
3043 // Show the toolbar.
3044 toolbar.setVisibility(View.VISIBLE);
3046 // Get a handle for the input method manager.
3047 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
3049 // Remove the lint warning below that the input method manager might be null.
3050 assert inputMethodManager != null;
3052 // Hide the keyboard.
3053 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
3056 private void applyAppSettings() {
3057 // Get a handle for the shared preferences.
3058 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3060 // Store the values from the shared preferences in variables.
3061 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3062 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
3063 sanitizeGoogleAnalytics = sharedPreferences.getBoolean("google_analytics", true);
3064 sanitizeFacebookClickIds = sharedPreferences.getBoolean("facebook_click_ids", true);
3065 proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
3066 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3067 hideAppBar = sharedPreferences.getBoolean("hide_app_bar", true);
3068 scrollAppBar = sharedPreferences.getBoolean("scroll_app_bar", true);
3070 // Get handles for the views that need to be modified.
3071 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
3072 AppBarLayout appBarLayout = findViewById(R.id.appbar_layout);
3073 ActionBar actionBar = getSupportActionBar();
3074 Toolbar toolbar = findViewById(R.id.toolbar);
3075 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
3076 LinearLayout tabsLinearLayout = findViewById(R.id.tabs_linearlayout);
3077 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
3079 // Remove the incorrect lint warning below that the action bar might be null.
3080 assert actionBar != null;
3082 // Apply the proxy through Orbot settings.
3083 applyProxyThroughOrbot(false);
3085 // Set Do Not Track status.
3086 if (doNotTrackEnabled) {
3087 customHeaders.put("DNT", "1");
3089 customHeaders.remove("DNT");
3092 // Get the current layout parameters. Using coordinator layout parameters allows the `setBehavior()` command and using app bar layout parameters allows the `setScrollFlags()` command.
3093 CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
3094 AppBarLayout.LayoutParams toolbarLayoutParams = (AppBarLayout.LayoutParams) toolbar.getLayoutParams();
3095 AppBarLayout.LayoutParams findOnPageLayoutParams = (AppBarLayout.LayoutParams) findOnPageLinearLayout.getLayoutParams();
3096 AppBarLayout.LayoutParams tabsLayoutParams = (AppBarLayout.LayoutParams) tabsLinearLayout.getLayoutParams();
3098 // Add the scrolling behavior to the layout parameters.
3100 // Enable scrolling of the app bar.
3101 swipeRefreshLayoutParams.setBehavior(new AppBarLayout.ScrollingViewBehavior());
3102 toolbarLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3103 findOnPageLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3104 tabsLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3106 // Disable scrolling of the app bar.
3107 swipeRefreshLayoutParams.setBehavior(null);
3108 toolbarLayoutParams.setScrollFlags(0);
3109 findOnPageLayoutParams.setScrollFlags(0);
3110 tabsLayoutParams.setScrollFlags(0);
3112 // Expand the app bar if it is currently collapsed.
3113 appBarLayout.setExpanded(true);
3116 // Apply the modified layout parameters.
3117 swipeRefreshLayout.setLayoutParams(swipeRefreshLayoutParams);
3118 toolbar.setLayoutParams(toolbarLayoutParams);
3119 findOnPageLinearLayout.setLayoutParams(findOnPageLayoutParams);
3120 tabsLinearLayout.setLayoutParams(tabsLayoutParams);
3122 // Set the app bar scrolling for each WebView.
3123 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3124 // Get the WebView tab fragment.
3125 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3127 // Get the fragment view.
3128 View fragmentView = webViewTabFragment.getView();
3130 // Only modify the WebViews if they exist.
3131 if (fragmentView != null) {
3132 // Get the nested scroll WebView from the tab fragment.
3133 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3135 // Set the app bar scrolling.
3136 nestedScrollWebView.setNestedScrollingEnabled(scrollAppBar);
3140 // Update the full screen browsing mode settings.
3141 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
3142 // Update the visibility of the app bar, which might have changed in the settings.
3144 // Hide the tab linear layout.
3145 tabsLinearLayout.setVisibility(View.GONE);
3147 // Hide the action bar.
3150 // Show the tab linear layout.
3151 tabsLinearLayout.setVisibility(View.VISIBLE);
3153 // Show the action bar.
3157 // Hide the banner ad in the free flavor.
3158 if (BuildConfig.FLAVOR.contentEquals("free")) {
3159 AdHelper.hideAd(findViewById(R.id.adview));
3162 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
3163 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3165 /* Hide the system bars.
3166 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3167 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
3168 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3169 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3171 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
3172 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3173 } else { // Privacy Browser is not in full screen browsing mode.
3174 // Reset the full screen tracker, which could be true if Privacy Browser was in full screen mode before entering settings and full screen browsing was disabled.
3175 inFullScreenBrowsingMode = false;
3177 // Show the tab linear layout.
3178 tabsLinearLayout.setVisibility(View.VISIBLE);
3180 // Show the action bar.
3183 // Show the banner ad in the free flavor.
3184 if (BuildConfig.FLAVOR.contentEquals("free")) {
3185 // Initialize the ads. If this isn't the first run, `loadAd()` will be automatically called instead.
3186 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getSupportFragmentManager(), getString(R.string.google_app_id), getString(R.string.ad_unit_id));
3189 // Remove the `SYSTEM_UI` flags from the root frame layout.
3190 rootFrameLayout.setSystemUiVisibility(0);
3192 // Add the translucent status flag.
3193 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3198 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
3199 @SuppressLint("SetJavaScriptEnabled")
3200 private boolean applyDomainSettings(NestedScrollWebView nestedScrollWebView, String url, boolean resetTab, boolean reloadWebsite) {
3201 // Store a copy of the current user agent to track changes for the return boolean.
3202 String initialUserAgent = nestedScrollWebView.getSettings().getUserAgentString();
3204 // Parse the URL into a URI.
3205 Uri uri = Uri.parse(url);
3207 // Extract the domain from `uri`.
3208 String newHostName = uri.getHost();
3210 // Strings don't like to be null.
3211 if (newHostName == null) {
3215 // Only apply the domain settings if a new domain is being loaded. This allows the user to set temporary settings for JavaScript, cookies, DOM storage, etc.
3216 if (!nestedScrollWebView.getCurrentDomainName().equals(newHostName)) {
3217 // Set the new host name as the current domain name.
3218 nestedScrollWebView.setCurrentDomainName(newHostName);
3220 // Reset the ignoring of pinned domain information.
3221 nestedScrollWebView.setIgnorePinnedDomainInformation(false);
3223 // Clear any pinned SSL certificate or IP addresses.
3224 nestedScrollWebView.clearPinnedSslCertificate();
3225 nestedScrollWebView.clearPinnedIpAddresses();
3227 // Reset the favorite icon if specified.
3229 // Initialize the favorite icon.
3230 nestedScrollWebView.initializeFavoriteIcon();
3232 // Get the current page position.
3233 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
3235 // Get a handle for the tab layout.
3236 TabLayout tabLayout = findViewById(R.id.tablayout);
3238 // Get the corresponding tab.
3239 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
3241 // Update the tab if it isn't null, which sometimes happens when restarting from the background.
3243 // Get the tab custom view.
3244 View tabCustomView = tab.getCustomView();
3246 // Remove the warning below that the tab custom view might be null.
3247 assert tabCustomView != null;
3249 // Get the tab views.
3250 ImageView tabFavoriteIconImageView = tabCustomView.findViewById(R.id.favorite_icon_imageview);
3251 TextView tabTitleTextView = tabCustomView.findViewById(R.id.title_textview);
3253 // Set the default favorite icon as the favorite icon for this tab.
3254 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(nestedScrollWebView.getFavoriteOrDefaultIcon(), 64, 64, true));
3256 // Set the loading title text.
3257 tabTitleTextView.setText(R.string.loading);
3261 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3262 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3264 // Get a full cursor from `domainsDatabaseHelper`.
3265 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3267 // Initialize `domainSettingsSet`.
3268 Set<String> domainSettingsSet = new HashSet<>();
3270 // Get the domain name column index.
3271 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3273 // Populate `domainSettingsSet`.
3274 for (int i = 0; i < domainNameCursor.getCount(); i++) {
3275 // Move `domainsCursor` to the current row.
3276 domainNameCursor.moveToPosition(i);
3278 // Store the domain name in `domainSettingsSet`.
3279 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3282 // Close `domainNameCursor.
3283 domainNameCursor.close();
3285 // Initialize the domain name in database variable.
3286 String domainNameInDatabase = null;
3288 // Check the hostname against the domain settings set.
3289 if (domainSettingsSet.contains(newHostName)) { // The hostname is contained in the domain settings set.
3290 // Record the domain name in the database.
3291 domainNameInDatabase = newHostName;
3293 // Set the domain settings applied tracker to true.
3294 nestedScrollWebView.setDomainSettingsApplied(true);
3295 } else { // The hostname is not contained in the domain settings set.
3296 // Set the domain settings applied tracker to false.
3297 nestedScrollWebView.setDomainSettingsApplied(false);
3300 // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3301 while (!nestedScrollWebView.getDomainSettingsApplied() && newHostName.contains(".")) { // Stop checking if domain settings are already applied or there are no more `.` in the host name.
3302 if (domainSettingsSet.contains("*." + newHostName)) { // Check the host name prepended by `*.`.
3303 // Set the domain settings applied tracker to true.
3304 nestedScrollWebView.setDomainSettingsApplied(true);
3306 // Store the applied domain names as it appears in the database.
3307 domainNameInDatabase = "*." + newHostName;
3310 // Strip out the lowest subdomain of of the host name.
3311 newHostName = newHostName.substring(newHostName.indexOf(".") + 1);
3315 // Get a handle for the shared preferences.
3316 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3318 // Store the general preference information.
3319 String defaultFontSizeString = sharedPreferences.getString("font_size", getString(R.string.font_size_default_value));
3320 String defaultUserAgentName = sharedPreferences.getString("user_agent", getString(R.string.user_agent_default_value));
3321 boolean defaultSwipeToRefresh = sharedPreferences.getBoolean("swipe_to_refresh", true);
3322 boolean displayWebpageImages = sharedPreferences.getBoolean("display_webpage_images", true);
3323 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
3325 // Get a handle for the cookie manager.
3326 CookieManager cookieManager = CookieManager.getInstance();
3328 // Get handles for the views.
3329 RelativeLayout urlRelativeLayout = findViewById(R.id.url_relativelayout);
3330 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
3332 // Initialize the user agent array adapter and string array.
3333 ArrayAdapter<CharSequence> userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item);
3334 String[] userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
3336 if (nestedScrollWebView.getDomainSettingsApplied()) { // The url has custom domain settings.
3337 // Get a cursor for the current host and move it to the first position.
3338 Cursor currentDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3339 currentDomainSettingsCursor.moveToFirst();
3341 // Get the settings from the cursor.
3342 nestedScrollWebView.setDomainSettingsDatabaseId(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3343 nestedScrollWebView.setDomainSettingsJavaScriptEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3344 nestedScrollWebView.setAcceptFirstPartyCookies(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3345 boolean domainThirdPartyCookiesEnabled = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3346 nestedScrollWebView.getSettings().setDomStorageEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3347 // Form data can be removed once the minimum API >= 26.
3348 boolean saveFormData = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3349 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASY_LIST,
3350 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3351 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASY_PRIVACY,
3352 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3353 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST,
3354 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3355 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST,
3356 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3357 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRA_PRIVACY,
3358 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_ULTRAPRIVACY)) == 1);
3359 nestedScrollWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS,
3360 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
3361 String userAgentName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3362 int fontSize = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3363 int swipeToRefreshInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
3364 int nightModeInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
3365 int displayWebpageImagesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3366 boolean pinnedSslCertificate = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3367 String pinnedSslIssuedToCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3368 String pinnedSslIssuedToOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3369 String pinnedSslIssuedToUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3370 String pinnedSslIssuedByCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3371 String pinnedSslIssuedByOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3372 String pinnedSslIssuedByUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3373 boolean pinnedIpAddresses = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_IP_ADDRESSES)) == 1);
3374 String pinnedHostIpAddresses = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.IP_ADDRESSES));
3376 // Create the pinned SSL date variables.
3377 Date pinnedSslStartDate;
3378 Date pinnedSslEndDate;
3380 // 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.
3381 if (currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
3382 pinnedSslStartDate = null;
3384 pinnedSslStartDate = new Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
3387 // 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.
3388 if (currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
3389 pinnedSslEndDate = null;
3391 pinnedSslEndDate = new Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
3394 // If there is a pinned SSL certificate, store it in the WebView.
3395 if (pinnedSslCertificate) {
3396 nestedScrollWebView.setPinnedSslCertificate(pinnedSslIssuedToCName, pinnedSslIssuedToOName, pinnedSslIssuedToUName, pinnedSslIssuedByCName, pinnedSslIssuedByOName, pinnedSslIssuedByUName,
3397 pinnedSslStartDate, pinnedSslEndDate);
3400 // If there is a pinned IP address, store it in the WebView.
3401 if (pinnedIpAddresses) {
3402 nestedScrollWebView.setPinnedIpAddresses(pinnedHostIpAddresses);
3405 // Set night mode according to the night mode int.
3406 switch (nightModeInt) {
3407 case DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT:
3408 // Set night mode according to the current default.
3409 nestedScrollWebView.setNightMode(sharedPreferences.getBoolean("night_mode", false));
3412 case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
3413 // Enable night mode.
3414 nestedScrollWebView.setNightMode(true);
3417 case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
3418 // Disable night mode.
3419 nestedScrollWebView.setNightMode(false);
3423 // Enable JavaScript if night mode is enabled.
3424 if (nestedScrollWebView.getNightMode()) {
3425 // Enable JavaScript.
3426 nestedScrollWebView.getSettings().setJavaScriptEnabled(true);
3428 // Set JavaScript according to the domain settings.
3429 nestedScrollWebView.getSettings().setJavaScriptEnabled(nestedScrollWebView.getDomainSettingsJavaScriptEnabled());
3432 // Close the current host domain settings cursor.
3433 currentDomainSettingsCursor.close();
3435 // Apply the domain settings.
3436 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptFirstPartyCookies());
3438 // Set third-party cookies status if API >= 21.
3439 if (Build.VERSION.SDK_INT >= 21) {
3440 cookieManager.setAcceptThirdPartyCookies(nestedScrollWebView, domainThirdPartyCookiesEnabled);
3443 // Apply the form data setting if the API < 26.
3444 if (Build.VERSION.SDK_INT < 26) {
3445 nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
3448 // Apply the font size.
3449 if (fontSize == 0) { // Apply the default font size.
3450 nestedScrollWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3451 } else { // Apply the specified font size.
3452 nestedScrollWebView.getSettings().setTextZoom(fontSize);
3455 // Only set the user agent if the webpage is not currently loading. Otherwise, changing the user agent on redirects can cause the original website to reload.
3456 // <https://redmine.stoutner.com/issues/160>
3457 if (nestedScrollWebView.getProgress() == 100) { // A URL is not loading.
3458 // Set the user agent.
3459 if (userAgentName.equals(getString(R.string.system_default_user_agent))) { // Use the system default user agent.
3460 // Get the array position of the default user agent name.
3461 int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3463 // Set the user agent according to the system default.
3464 switch (defaultUserAgentArrayPosition) {
3465 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
3466 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3467 nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
3470 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3471 // Set the user agent to `""`, which uses the default value.
3472 nestedScrollWebView.getSettings().setUserAgentString("");
3475 case SETTINGS_CUSTOM_USER_AGENT:
3476 // Set the default custom user agent.
3477 nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
3481 // Get the user agent string from the user agent data array
3482 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
3484 } else { // Set the user agent according to the stored name.
3485 // Get the array position of the user agent name.
3486 int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
3488 switch (userAgentArrayPosition) {
3489 case UNRECOGNIZED_USER_AGENT: // The user agent name contains a custom user agent.
3490 nestedScrollWebView.getSettings().setUserAgentString(userAgentName);
3493 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3494 // Set the user agent to `""`, which uses the default value.
3495 nestedScrollWebView.getSettings().setUserAgentString("");
3499 // Get the user agent string from the user agent data array.
3500 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3505 // Set swipe to refresh.
3506 switch (swipeToRefreshInt) {
3507 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_SYSTEM_DEFAULT:
3508 // Store the swipe to refresh status in the nested scroll WebView.
3509 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
3511 // 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.
3512 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
3515 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_ENABLED:
3516 // Store the swipe to refresh status in the nested scroll WebView.
3517 nestedScrollWebView.setSwipeToRefresh(true);
3519 // Enable swipe to refresh. This can be removed once the minimum API >= 23 because it is continuously set by an on scroll change listener.
3520 swipeRefreshLayout.setEnabled(true);
3523 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_DISABLED:
3524 // Store the swipe to refresh status in the nested scroll WebView.
3525 nestedScrollWebView.setSwipeToRefresh(false);
3527 // Disable swipe to refresh. This can be removed once the minimum API >= 23 because it is continuously set by an on scroll change listener.
3528 swipeRefreshLayout.setEnabled(false);
3531 // Set the loading of webpage images.
3532 switch (displayWebpageImagesInt) {
3533 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
3534 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
3537 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
3538 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(true);
3541 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
3542 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(false);
3546 // 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.
3548 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
3550 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
3552 } else { // The new URL does not have custom domain settings. Load the defaults.
3553 // Store the values from the shared preferences.
3554 boolean defaultJavaScriptEnabled = sharedPreferences.getBoolean("javascript", false);
3555 nestedScrollWebView.setAcceptFirstPartyCookies(sharedPreferences.getBoolean("first_party_cookies", false));
3556 boolean defaultThirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies", false);
3557 nestedScrollWebView.getSettings().setDomStorageEnabled(sharedPreferences.getBoolean("dom_storage", false));
3558 boolean saveFormData = sharedPreferences.getBoolean("save_form_data", false); // Form data can be removed once the minimum API >= 26.
3559 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASY_LIST, sharedPreferences.getBoolean("easylist", true));
3560 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASY_PRIVACY, sharedPreferences.getBoolean("easyprivacy", true));
3561 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, sharedPreferences.getBoolean("fanboys_annoyance_list", true));
3562 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, sharedPreferences.getBoolean("fanboys_social_blocking_list", true));
3563 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRA_PRIVACY, sharedPreferences.getBoolean("ultraprivacy", true));
3564 nestedScrollWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, sharedPreferences.getBoolean("block_all_third_party_requests", false));
3565 nestedScrollWebView.setNightMode(sharedPreferences.getBoolean("night_mode", false));
3567 // Enable JavaScript if night mode is enabled.
3568 if (nestedScrollWebView.getNightMode()) {
3569 // Enable JavaScript.
3570 nestedScrollWebView.getSettings().setJavaScriptEnabled(true);
3572 // Set JavaScript according to the domain settings.
3573 nestedScrollWebView.getSettings().setJavaScriptEnabled(defaultJavaScriptEnabled);
3576 // Apply the default settings.
3577 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptFirstPartyCookies());
3578 nestedScrollWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3580 // Apply the form data setting if the API < 26.
3581 if (Build.VERSION.SDK_INT < 26) {
3582 nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
3585 // Store the swipe to refresh status in the nested scroll WebView.
3586 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
3588 // Apply swipe to refresh according to the default.
3589 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
3591 // Reset the pinned variables.
3592 nestedScrollWebView.setDomainSettingsDatabaseId(-1);
3594 // Set third-party cookies status if API >= 21.
3595 if (Build.VERSION.SDK_INT >= 21) {
3596 cookieManager.setAcceptThirdPartyCookies(nestedScrollWebView, defaultThirdPartyCookiesEnabled);
3599 // Only set the user agent if the webpage is not currently loading. Otherwise, changing the user agent on redirects can cause the original website to reload.
3600 // <https://redmine.stoutner.com/issues/160>
3601 if (nestedScrollWebView.getProgress() == 100) { // A URL is not loading.
3602 // Get the array position of the user agent name.
3603 int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3605 // Set the user agent.
3606 switch (userAgentArrayPosition) {
3607 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
3608 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3609 nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
3612 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3613 // Set the user agent to `""`, which uses the default value.
3614 nestedScrollWebView.getSettings().setUserAgentString("");
3617 case SETTINGS_CUSTOM_USER_AGENT:
3618 // Set the default custom user agent.
3619 nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
3623 // Get the user agent string from the user agent data array
3624 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3628 // Set the loading of webpage images.
3629 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
3631 // Set a transparent background on URL edit text. The deprecated `getResources().getDrawable()` must be used until the minimum API >= 21.
3632 urlRelativeLayout.setBackground(getResources().getDrawable(R.color.transparent));
3635 // Close the domains database helper.
3636 domainsDatabaseHelper.close();
3638 // Update the privacy icons.
3639 updatePrivacyIcons(true);
3642 // Reload the website if returning from the Domains activity.
3643 if (reloadWebsite) {
3644 nestedScrollWebView.reload();
3647 // Return the user agent changed status.
3648 return !nestedScrollWebView.getSettings().getUserAgentString().equals(initialUserAgent);
3651 private void applyProxyThroughOrbot(boolean reloadWebsite) {
3652 // Get a handle for the shared preferences.
3653 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3655 // Get the search and theme preferences.
3656 String torSearchString = sharedPreferences.getString("tor_search", getString(R.string.tor_search_default_value));
3657 String torSearchCustomUrlString = sharedPreferences.getString("tor_search_custom_url", getString(R.string.tor_search_custom_url_default_value));
3658 String searchString = sharedPreferences.getString("search", getString(R.string.search_default_value));
3659 String searchCustomUrlString = sharedPreferences.getString("search_custom_url", getString(R.string.search_custom_url_default_value));
3660 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
3662 // Get a handle for the app bar layout.
3663 AppBarLayout appBarLayout = findViewById(R.id.appbar_layout);
3665 // Set the homepage, search, and proxy options.
3666 if (proxyThroughOrbot) { // Set the Tor options.
3667 // Set the search URL.
3668 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
3669 searchURL = torSearchCustomUrlString;
3670 } else { // Use the string from the pre-built list.
3671 searchURL = torSearchString;
3674 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
3675 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
3677 // Set the app bar background to indicate proxying through Orbot is enabled.
3679 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
3681 appBarLayout.setBackgroundResource(R.color.blue_50);
3684 // Check to see if Orbot is ready.
3685 if (!orbotStatus.equals("ON")) { // Orbot is not ready.
3686 // Set `waitingForOrbot`.
3687 waitingForOrbot = true;
3689 // Disable the wide view port so that the waiting for Orbot text is displayed correctly.
3690 currentWebView.getSettings().setUseWideViewPort(false);
3692 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
3693 currentWebView.loadData("<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>", "text/html", null);
3694 } else if (reloadWebsite) { // Orbot is ready and the website should be reloaded.
3695 // Reload the website.
3696 currentWebView.reload();
3698 } else { // Set the non-Tor options.
3699 // Set the search URL.
3700 if (searchString.equals("Custom URL")) { // Get the custom URL string.
3701 searchURL = searchCustomUrlString;
3702 } else { // Use the string from the pre-built list.
3703 searchURL = searchString;
3706 // Reset the proxy to default. The host is `""` and the port is `"0"`.
3707 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
3709 // Set the default app bar layout background.
3711 appBarLayout.setBackgroundResource(R.color.gray_900);
3713 appBarLayout.setBackgroundResource(R.color.gray_100);
3716 // Reset `waitingForOrbot.
3717 waitingForOrbot = false;
3719 // Reload the WebViews if requested.
3720 if (reloadWebsite) {
3721 // Reload the WebViews.
3722 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3723 // Get the WebView tab fragment.
3724 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3726 // Get the fragment view.
3727 View fragmentView = webViewTabFragment.getView();
3729 // Only reload the WebViews if they exist.
3730 if (fragmentView != null) {
3731 // Get the nested scroll WebView from the tab fragment.
3732 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3734 // Reload the WebView.
3735 nestedScrollWebView.reload();
3742 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
3743 // Only update the privacy icons if the options menu and the current WebView have already been populated.
3744 if ((optionsMenu != null) && (currentWebView != null)) {
3745 // Get a handle for the shared preferences.
3746 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3748 // Get the theme and screenshot preferences.
3749 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
3751 // Get handles for the menu items.
3752 MenuItem privacyMenuItem = optionsMenu.findItem(R.id.toggle_javascript);
3753 MenuItem firstPartyCookiesMenuItem = optionsMenu.findItem(R.id.toggle_first_party_cookies);
3754 MenuItem domStorageMenuItem = optionsMenu.findItem(R.id.toggle_dom_storage);
3755 MenuItem refreshMenuItem = optionsMenu.findItem(R.id.refresh);
3757 // Update the privacy icon.
3758 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is enabled.
3759 privacyMenuItem.setIcon(R.drawable.javascript_enabled);
3760 } else if (currentWebView.getAcceptFirstPartyCookies()) { // JavaScript is disabled but cookies are enabled.
3761 privacyMenuItem.setIcon(R.drawable.warning);
3762 } else { // All the dangerous features are disabled.
3763 privacyMenuItem.setIcon(R.drawable.privacy_mode);
3766 // Update the first-party cookies icon.
3767 if (currentWebView.getAcceptFirstPartyCookies()) { // First-party cookies are enabled.
3768 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
3769 } else { // First-party cookies are disabled.
3771 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_dark);
3773 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_light);
3777 // Update the DOM storage icon.
3778 if (currentWebView.getSettings().getJavaScriptEnabled() && currentWebView.getSettings().getDomStorageEnabled()) { // Both JavaScript and DOM storage are enabled.
3779 domStorageMenuItem.setIcon(R.drawable.dom_storage_enabled);
3780 } else if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is enabled but DOM storage is disabled.
3782 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
3784 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
3786 } else { // JavaScript is disabled, so DOM storage is ghosted.
3788 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
3790 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
3794 // Update the refresh icon.
3796 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
3798 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
3801 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
3802 if (runInvalidateOptionsMenu) {
3803 invalidateOptionsMenu();
3808 private void openUrlWithExternalApp(String url) {
3809 // Create a download intent. Not specifying the action type will display the maximum number of options.
3810 Intent downloadIntent = new Intent();
3812 // Set the URI and the MIME type. Specifying `text/html` displays a good number of options.
3813 downloadIntent.setDataAndType(Uri.parse(url), "text/html");
3815 // Flag the intent to open in a new task.
3816 downloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3818 // Show the chooser.
3819 startActivity(Intent.createChooser(downloadIntent, getString(R.string.open_with)));
3822 private void highlightUrlText() {
3823 // Get a handle for the URL edit text.
3824 EditText urlEditText = findViewById(R.id.url_edittext);
3826 // Only highlight the URL text if the box is not currently selected.
3827 if (!urlEditText.hasFocus()) {
3828 // Get the URL string.
3829 String urlString = urlEditText.getText().toString();
3831 // Highlight the URL according to the protocol.
3832 if (urlString.startsWith("file://")) { // This is a file URL.
3833 // De-emphasize only the protocol.
3834 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3835 } else if (urlString.startsWith("content://")) {
3836 // De-emphasize only the protocol.
3837 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 10, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3838 } else { // This is a web URL.
3839 // Get the index of the `/` immediately after the domain name.
3840 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
3842 // Create a base URL string.
3845 // Get the base URL.
3846 if (endOfDomainName > 0) { // There is at least one character after the base URL.
3847 // Get the base URL.
3848 baseUrl = urlString.substring(0, endOfDomainName);
3849 } else { // There are no characters after the base URL.
3850 // Set the base URL to be the entire URL string.
3851 baseUrl = urlString;
3854 // Get the index of the last `.` in the domain.
3855 int lastDotIndex = baseUrl.lastIndexOf(".");
3857 // Get the index of the penultimate `.` in the domain.
3858 int penultimateDotIndex = baseUrl.lastIndexOf(".", lastDotIndex - 1);
3860 // Markup the beginning of the URL.
3861 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
3862 urlEditText.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3864 // De-emphasize subdomains.
3865 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
3866 urlEditText.getText().setSpan(initialGrayColorSpan, 7, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3868 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
3869 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
3870 // De-emphasize the protocol and the additional subdomains.
3871 urlEditText.getText().setSpan(initialGrayColorSpan, 0, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3872 } else { // There is only one subdomain in the domain name.
3873 // De-emphasize only the protocol.
3874 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3878 // De-emphasize the text after the domain name.
3879 if (endOfDomainName > 0) {
3880 urlEditText.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3886 private void loadBookmarksFolder() {
3887 // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
3888 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
3890 // Populate the bookmarks cursor adapter. `this` specifies the `Context`. `false` disables `autoRequery`.
3891 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
3893 public View newView(Context context, Cursor cursor, ViewGroup parent) {
3894 // Inflate the individual item layout. `false` does not attach it to the root.
3895 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
3899 public void bindView(View view, Context context, Cursor cursor) {
3900 // Get handles for the views.
3901 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
3902 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
3904 // Get the favorite icon byte array from the cursor.
3905 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
3907 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
3908 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
3910 // Display the bitmap in `bookmarkFavoriteIcon`.
3911 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
3913 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
3914 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
3915 bookmarkNameTextView.setText(bookmarkNameString);
3917 // Make the font bold for folders.
3918 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
3919 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
3920 } else { // Reset the font to default for normal bookmarks.
3921 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
3926 // Get a handle for the bookmarks list view.
3927 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
3929 // Populate the list view with the adapter.
3930 bookmarksListView.setAdapter(bookmarksCursorAdapter);
3932 // Get a handle for the bookmarks title text view.
3933 TextView bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
3935 // Set the bookmarks drawer title.
3936 if (currentBookmarksFolder.isEmpty()) {
3937 bookmarksTitleTextView.setText(R.string.bookmarks);
3939 bookmarksTitleTextView.setText(currentBookmarksFolder);
3943 private void openWithApp(String url) {
3944 // Create the open with intent with `ACTION_VIEW`.
3945 Intent openWithAppIntent = new Intent(Intent.ACTION_VIEW);
3947 // Set the URI but not the MIME type. This should open all available apps.
3948 openWithAppIntent.setData(Uri.parse(url));
3950 // Flag the intent to open in a new task.
3951 openWithAppIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3953 // Show the chooser.
3954 startActivity(openWithAppIntent);
3957 private void openWithBrowser(String url) {
3958 // Create the open with intent with `ACTION_VIEW`.
3959 Intent openWithBrowserIntent = new Intent(Intent.ACTION_VIEW);
3961 // Set the URI and the MIME type. `"text/html"` should load browser options.
3962 openWithBrowserIntent.setDataAndType(Uri.parse(url), "text/html");
3964 // Flag the intent to open in a new task.
3965 openWithBrowserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3967 // Show the chooser.
3968 startActivity(openWithBrowserIntent);
3971 private String sanitizeUrl(String url) {
3972 // Sanitize Google Analytics.
3973 if (sanitizeGoogleAnalytics) {
3975 if (url.contains("?utm_")) {
3976 url = url.substring(0, url.indexOf("?utm_"));
3980 if (url.contains("&utm_")) {
3981 url = url.substring(0, url.indexOf("&utm_"));
3985 // Sanitize Facebook Click IDs.
3986 if (sanitizeFacebookClickIds) {
3987 // Remove `?fbclid=`.
3988 if (url.contains("?fbclid=")) {
3989 url = url.substring(0, url.indexOf("?fbclid="));
3992 // Remove &fbclid=`.
3993 if (url.contains("&fbclid=")) {
3994 url = url.substring(0, url.indexOf("&fbclid="));
3998 // Return the sanitized URL.
4002 public void addTab(View view) {
4003 // Add a new tab with a blank URL.
4007 private void addNewTab(String url) {
4008 // Sanitize the URL.
4009 url = sanitizeUrl(url);
4011 // Get a handle for the tab layout and the view pager.
4012 TabLayout tabLayout = findViewById(R.id.tablayout);
4013 ViewPager webViewPager = findViewById(R.id.webviewpager);
4015 // Get the new page number. The page numbers are 0 indexed, so the new page number will match the current count.
4016 int newTabNumber = tabLayout.getTabCount();
4019 tabLayout.addTab(tabLayout.newTab());
4022 TabLayout.Tab newTab = tabLayout.getTabAt(newTabNumber);
4024 // Remove the lint warning below that the current tab might be null.
4025 assert newTab != null;
4027 // Set a custom view on the new tab.
4028 newTab.setCustomView(R.layout.tab_custom_view);
4030 // Add the new WebView page.
4031 webViewPagerAdapter.addPage(newTabNumber, webViewPager, url);
4034 public void closeTab(View view) {
4035 // Get a handle for the tab layout.
4036 TabLayout tabLayout = findViewById(R.id.tablayout);
4038 // Run the command according to the number of tabs.
4039 if (tabLayout.getTabCount() > 1) { // There is more than one tab open.
4040 // Close the current tab.
4042 } else { // There is only one tab open.
4047 private void closeCurrentTab() {
4048 // Get handles for the views.
4049 AppBarLayout appBarLayout = findViewById(R.id.appbar_layout);
4050 TabLayout tabLayout = findViewById(R.id.tablayout);
4051 ViewPager webViewPager = findViewById(R.id.webviewpager);
4053 // Get the current tab number.
4054 int currentTabNumber = tabLayout.getSelectedTabPosition();
4056 // Delete the current tab.
4057 tabLayout.removeTabAt(currentTabNumber);
4059 // 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.
4060 if (webViewPagerAdapter.deletePage(currentTabNumber, webViewPager)) {
4061 setCurrentWebView(currentTabNumber);
4064 // Expand the app bar if it is currently collapsed.
4065 appBarLayout.setExpanded(true);
4068 private void clearAndExit() {
4069 // Get a handle for the shared preferences.
4070 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4072 // Close the bookmarks cursor and database.
4073 bookmarksCursor.close();
4074 bookmarksDatabaseHelper.close();
4076 // Get the status of the clear everything preference.
4077 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
4079 // Get a handle for the runtime.
4080 Runtime runtime = Runtime.getRuntime();
4082 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
4083 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
4084 String privateDataDirectoryString = getApplicationInfo().dataDir;
4087 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
4088 // The command to remove cookies changed slightly in API 21.
4089 if (Build.VERSION.SDK_INT >= 21) {
4090 CookieManager.getInstance().removeAllCookies(null);
4092 CookieManager.getInstance().removeAllCookie();
4095 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4097 // Two commands must be used because `Runtime.exec()` does not like `*`.
4098 Process deleteCookiesProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
4099 Process deleteCookiesJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
4101 // Wait until the processes have finished.
4102 deleteCookiesProcess.waitFor();
4103 deleteCookiesJournalProcess.waitFor();
4104 } catch (Exception exception) {
4105 // Do nothing if an error is thrown.
4109 // Clear DOM storage.
4110 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
4111 // Ask `WebStorage` to clear the DOM storage.
4112 WebStorage webStorage = WebStorage.getInstance();
4113 webStorage.deleteAllData();
4115 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4117 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4118 Process deleteLocalStorageProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
4120 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
4121 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
4122 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
4123 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
4124 Process deleteDatabaseProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
4126 // Wait until the processes have finished.
4127 deleteLocalStorageProcess.waitFor();
4128 deleteIndexProcess.waitFor();
4129 deleteQuotaManagerProcess.waitFor();
4130 deleteQuotaManagerJournalProcess.waitFor();
4131 deleteDatabaseProcess.waitFor();
4132 } catch (Exception exception) {
4133 // Do nothing if an error is thrown.
4137 // Clear form data if the API < 26.
4138 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
4139 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
4140 webViewDatabase.clearFormData();
4142 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4144 // A string array must be used because the database contains a space and `Runtime.exec` will not otherwise escape the string correctly.
4145 Process deleteWebDataProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
4146 Process deleteWebDataJournalProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
4148 // Wait until the processes have finished.
4149 deleteWebDataProcess.waitFor();
4150 deleteWebDataJournalProcess.waitFor();
4151 } catch (Exception exception) {
4152 // Do nothing if an error is thrown.
4157 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
4158 // Clear the cache from each WebView.
4159 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4160 // Get the WebView tab fragment.
4161 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4163 // Get the fragment view.
4164 View fragmentView = webViewTabFragment.getView();
4166 // Only clear the cache if the WebView exists.
4167 if (fragmentView != null) {
4168 // Get the nested scroll WebView from the tab fragment.
4169 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4171 // Clear the cache for this WebView.
4172 nestedScrollWebView.clearCache(true);
4176 // Manually delete the cache directories.
4178 // Delete the main cache directory.
4179 Process deleteCacheProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/cache");
4181 // Delete the secondary `Service Worker` cache directory.
4182 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4183 Process deleteServiceWorkerProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
4185 // Wait until the processes have finished.
4186 deleteCacheProcess.waitFor();
4187 deleteServiceWorkerProcess.waitFor();
4188 } catch (Exception exception) {
4189 // Do nothing if an error is thrown.
4193 // Wipe out each WebView.
4194 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4195 // Get the WebView tab fragment.
4196 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4198 // Get the fragment view.
4199 View fragmentView = webViewTabFragment.getView();
4201 // Only wipe out the WebView if it exists.
4202 if (fragmentView != null) {
4203 // Get the nested scroll WebView from the tab fragment.
4204 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4206 // Clear SSL certificate preferences for this WebView.
4207 nestedScrollWebView.clearSslPreferences();
4209 // Clear the back/forward history for this WebView.
4210 nestedScrollWebView.clearHistory();
4212 // Destroy the internal state of `mainWebView`.
4213 nestedScrollWebView.destroy();
4217 // Clear the custom headers.
4218 customHeaders.clear();
4220 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
4221 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
4222 if (clearEverything) {
4224 // Delete the folder.
4225 Process deleteAppWebviewProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
4227 // Wait until the process has finished.
4228 deleteAppWebviewProcess.waitFor();
4229 } catch (Exception exception) {
4230 // Do nothing if an error is thrown.
4234 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
4235 if (Build.VERSION.SDK_INT >= 21) {
4236 finishAndRemoveTask();
4241 // Remove the terminated program from RAM. The status code is `0`.
4245 private void setCurrentWebView(int pageNumber) {
4246 // Get a handle for the shared preferences.
4247 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4249 // Get the theme preference.
4250 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
4252 // Get handles for the URL views.
4253 RelativeLayout urlRelativeLayout = findViewById(R.id.url_relativelayout);
4254 EditText urlEditText = findViewById(R.id.url_edittext);
4255 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
4257 //Stop the swipe to refresh indicator if it is running
4258 swipeRefreshLayout.setRefreshing(false);
4260 // Get the WebView tab fragment.
4261 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(pageNumber);
4263 // Get the fragment view.
4264 View fragmentView = webViewTabFragment.getView();
4266 // Set the current WebView if the fragment view is not null.
4267 if (fragmentView != null) {
4268 // Store the current WebView.
4269 currentWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4271 // Update the status of swipe to refresh.
4272 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
4273 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.
4274 // Enable the swipe refresh layout if the WebView is scrolled all the way to the top.
4275 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
4277 // Enable the swipe refresh layout.
4278 swipeRefreshLayout.setEnabled(true);
4280 } else { // Swipe to refresh is disabled.
4281 // Disable the swipe refresh layout.
4282 swipeRefreshLayout.setEnabled(false);
4285 // Get a handle for the cookie manager.
4286 CookieManager cookieManager = CookieManager.getInstance();
4288 // Set the first-party cookie status.
4289 cookieManager.setAcceptCookie(currentWebView.getAcceptFirstPartyCookies());
4291 // Update the privacy icons. `true` redraws the icons in the app bar.
4292 updatePrivacyIcons(true);
4294 // Get a handle for the input method manager.
4295 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
4297 // Remove the lint warning below that the input method manager might be null.
4298 assert inputMethodManager != null;
4300 // Get the current URL.
4301 String url = currentWebView.getUrl();
4303 // Update the URL edit text if not loading a new intent. Otherwise, this will be handled by `onPageStarted()` (if called) and `onPageFinished()`.
4304 if (!loadingNewIntent) { // A new intent is not being loaded.
4305 if ((url == null) || url.equals("about:blank")) { // The WebView is blank.
4306 // Display the hint in the URL edit text.
4307 urlEditText.setText("");
4309 // Request focus for the URL text box.
4310 urlEditText.requestFocus();
4312 // Display the keyboard.
4313 inputMethodManager.showSoftInput(urlEditText, 0);
4314 } else { // The WebView has a loaded URL.
4315 // Clear the focus from the URL text box.
4316 urlEditText.clearFocus();
4318 // Hide the soft keyboard.
4319 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
4321 // Display the current URL in the URL text box.
4322 urlEditText.setText(url);
4324 // Highlight the URL text.
4327 } else { // A new intent is being loaded.
4328 // Reset the loading new intent tracker.
4329 loadingNewIntent = false;
4332 // Set the background to indicate the domain settings status.
4333 if (currentWebView.getDomainSettingsApplied()) {
4334 // 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.
4336 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
4338 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
4341 urlRelativeLayout.setBackground(getResources().getDrawable(R.color.transparent));
4347 public void initializeWebView(NestedScrollWebView nestedScrollWebView, int pageNumber, ProgressBar progressBar, String url) {
4348 // Get handles for the activity views.
4349 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
4350 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
4351 RelativeLayout mainContentRelativeLayout = findViewById(R.id.main_content_relativelayout);
4352 ActionBar actionBar = getSupportActionBar();
4353 LinearLayout tabsLinearLayout = findViewById(R.id.tabs_linearlayout);
4354 EditText urlEditText = findViewById(R.id.url_edittext);
4355 TabLayout tabLayout = findViewById(R.id.tablayout);
4356 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
4358 // Remove the incorrect lint warning below that the action bar might be null.
4359 assert actionBar != null;
4361 // Get a handle for the activity
4362 Activity activity = this;
4364 // Get a handle for the input method manager.
4365 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
4367 // Instantiate the blocklist helper.
4368 BlockListHelper blockListHelper = new BlockListHelper();
4370 // Remove the lint warning below that the input method manager might be null.
4371 assert inputMethodManager != null;
4373 // Get a handle for the shared preferences.
4374 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4376 // Get the relevant preferences.
4377 boolean downloadWithExternalApp = sharedPreferences.getBoolean("download_with_external_app", false);
4379 // Initialize the favorite icon.
4380 nestedScrollWebView.initializeFavoriteIcon();
4382 // Set the app bar scrolling.
4383 nestedScrollWebView.setNestedScrollingEnabled(sharedPreferences.getBoolean("scroll_app_bar", true));
4385 // Allow pinch to zoom.
4386 nestedScrollWebView.getSettings().setBuiltInZoomControls(true);
4388 // Hide zoom controls.
4389 nestedScrollWebView.getSettings().setDisplayZoomControls(false);
4391 // Don't allow mixed content (HTTP and HTTPS) on the same website.
4392 if (Build.VERSION.SDK_INT >= 21) {
4393 nestedScrollWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW);
4396 // Set the WebView to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
4397 nestedScrollWebView.getSettings().setUseWideViewPort(true);
4399 // Set the WebView to load in overview mode (zoomed out to the maximum width).
4400 nestedScrollWebView.getSettings().setLoadWithOverviewMode(true);
4402 // Explicitly disable geolocation.
4403 nestedScrollWebView.getSettings().setGeolocationEnabled(false);
4405 // Create a double-tap gesture detector to toggle full-screen mode.
4406 GestureDetector doubleTapGestureDetector = new GestureDetector(getApplicationContext(), new GestureDetector.SimpleOnGestureListener() {
4407 // Override `onDoubleTap()`. All other events are handled using the default settings.
4409 public boolean onDoubleTap(MotionEvent event) {
4410 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
4411 // Toggle the full screen browsing mode tracker.
4412 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
4414 // Toggle the full screen browsing mode.
4415 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
4416 // Store the swipe refresh layout top padding.
4417 swipeRefreshLayoutPaddingTop = swipeRefreshLayout.getPaddingTop();
4419 // Hide the app bar if specified.
4421 // Close the find on page bar if it is visible.
4422 closeFindOnPage(null);
4424 // Hide the tab linear layout.
4425 tabsLinearLayout.setVisibility(View.GONE);
4427 // Hide the action bar.
4430 // Check to see if app bar scrolling is disabled.
4431 if (!scrollAppBar) {
4432 // Remove the padding from the top of the swipe refresh layout.
4433 swipeRefreshLayout.setPadding(0, 0, 0, 0);
4437 // Hide the banner ad in the free flavor.
4438 if (BuildConfig.FLAVOR.contentEquals("free")) {
4439 AdHelper.hideAd(findViewById(R.id.adview));
4442 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
4443 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4445 /* Hide the system bars.
4446 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4447 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4448 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4449 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4451 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
4452 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
4453 } else { // Switch to normal viewing mode.
4454 // Show the tab linear layout.
4455 tabsLinearLayout.setVisibility(View.VISIBLE);
4457 // Show the action bar.
4460 // Check to see if app bar scrolling is disabled.
4461 if (!scrollAppBar) {
4462 // Add the padding from the top of the swipe refresh layout.
4463 swipeRefreshLayout.setPadding(0, swipeRefreshLayoutPaddingTop, 0, 0);
4466 // Show the banner ad in the free flavor.
4467 if (BuildConfig.FLAVOR.contentEquals("free")) {
4469 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
4472 // Remove the `SYSTEM_UI` flags from the root frame layout.
4473 rootFrameLayout.setSystemUiVisibility(0);
4475 // Add the translucent status flag.
4476 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4479 // Consume the double-tap.
4481 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
4487 // Pass all touch events on the WebView through the double-tap gesture detector.
4488 nestedScrollWebView.setOnTouchListener((View view, MotionEvent event) -> {
4489 // Call `performClick()` on the view, which is required for accessibility.
4490 view.performClick();
4492 // Send the event to the gesture detector.
4493 return doubleTapGestureDetector.onTouchEvent(event);
4496 // Register the WebView for a context menu. This is used to see link targets and download images.
4497 registerForContextMenu(nestedScrollWebView);
4499 // Allow the downloading of files.
4500 nestedScrollWebView.setDownloadListener((String downloadUrl, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
4501 // Check if the download should be processed by an external app.
4502 if (downloadWithExternalApp) { // Download with an external app.
4503 // Create a download intent. Not specifying the action type will display the maximum number of options.
4504 Intent downloadIntent = new Intent();
4506 // Set the URI and the MIME type. Specifying `text/html` displays a good number of options.
4507 downloadIntent.setDataAndType(Uri.parse(downloadUrl), "text/html");
4509 // Flag the intent to open in a new task.
4510 downloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4512 // Show the chooser.
4513 startActivity(Intent.createChooser(downloadIntent, getString(R.string.open_with)));
4514 } else { // Download with Android's download manager.
4515 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
4516 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission has not been granted.
4517 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
4519 // Store the variables for future use by `onRequestPermissionsResult()`.
4520 this.downloadUrl = downloadUrl;
4521 downloadContentDisposition = contentDisposition;
4522 downloadContentLength = contentLength;
4524 // Show a dialog if the user has previously denied the permission.
4525 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
4526 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
4527 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
4529 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
4530 downloadLocationPermissionDialogFragment.show(getSupportFragmentManager(), getString(R.string.download_location));
4531 } else { // Show the permission request directly.
4532 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
4533 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
4535 } else { // The storage permission has already been granted.
4536 // Get a handle for the download file alert dialog.
4537 DialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(downloadUrl, contentDisposition, contentLength);
4539 // Show the download file alert dialog.
4540 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
4545 // Update the find on page count.
4546 nestedScrollWebView.setFindListener(new WebView.FindListener() {
4547 // Get a handle for `findOnPageCountTextView`.
4548 final TextView findOnPageCountTextView = findViewById(R.id.find_on_page_count_textview);
4551 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
4552 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
4553 // Set `findOnPageCountTextView` to `0/0`.
4554 findOnPageCountTextView.setText(R.string.zero_of_zero);
4555 } else if (isDoneCounting) { // There are matches.
4556 // `activeMatchOrdinal` is zero-based.
4557 int activeMatch = activeMatchOrdinal + 1;
4559 // Build the match string.
4560 String matchString = activeMatch + "/" + numberOfMatches;
4562 // Set `findOnPageCountTextView`.
4563 findOnPageCountTextView.setText(matchString);
4568 // Update the status of swipe to refresh based on the scroll position of the nested scroll WebView.
4569 // Once the minimum API >= 23 this can be replaced with `nestedScrollWebView.setOnScrollChangeListener()`.
4570 nestedScrollWebView.getViewTreeObserver().addOnScrollChangedListener(() -> {
4571 if (nestedScrollWebView.getSwipeToRefresh()) {
4572 // Only enable swipe to refresh if the WebView is scrolled to the top.
4573 swipeRefreshLayout.setEnabled(nestedScrollWebView.getScrollY() == 0);
4577 // Set the web chrome client.
4578 nestedScrollWebView.setWebChromeClient(new WebChromeClient() {
4579 // Update the progress bar when a page is loading.
4581 public void onProgressChanged(WebView view, int progress) {
4582 // Inject the night mode CSS if night mode is enabled.
4583 if (nestedScrollWebView.getNightMode()) { // Night mode is enabled.
4584 // `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
4585 // used by WordPress. `text-decoration: none` removes all text underlines. `text-shadow: none` removes text shadows, which usually have a hard coded color.
4586 // `border: none` removes all borders, which can also be used to underline text. `a {color: #1565C0}` sets links to be a dark blue.
4587 // `::selection {background: #0D47A1}' sets the text selection highlight color to be a dark blue. `!important` takes precedent over any existing sub-settings.
4588 nestedScrollWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; " +
4589 "style.innerHTML = '* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important;" +
4590 "text-shadow: none !important; border: none !important;} a {color: #1565C0 !important;} ::selection {background: #0D47A1 !important;}'; parent.appendChild(style)})()", value -> {
4591 // Initialize a handler to display `mainWebView`.
4592 Handler displayWebViewHandler = new Handler();
4594 // Setup a runnable to display `mainWebView` after a delay to allow the CSS to be applied.
4595 Runnable displayWebViewRunnable = () -> {
4596 // Only display `mainWebView` if the progress bar is gone. This prevents the display of the `WebView` while it is still loading.
4597 if (progressBar.getVisibility() == View.GONE) {
4598 nestedScrollWebView.setVisibility(View.VISIBLE);
4602 // Display the WebView after 500 milliseconds.
4603 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
4605 } else { // Night mode is disabled.
4606 // Display the nested scroll WebView if night mode is disabled.
4607 // Because of a race condition between `applyDomainSettings` and `onPageStarted`,
4608 // when night mode is set by domain settings the WebView may be hidden even if night mode is not currently enabled.
4609 nestedScrollWebView.setVisibility(View.VISIBLE);
4612 // Update the progress bar.
4613 progressBar.setProgress(progress);
4615 // Set the visibility of the progress bar.
4616 if (progress < 100) {
4617 // Show the progress bar.
4618 progressBar.setVisibility(View.VISIBLE);
4620 // Hide the progress bar.
4621 progressBar.setVisibility(View.GONE);
4623 //Stop the swipe to refresh indicator if it is running
4624 swipeRefreshLayout.setRefreshing(false);
4628 // Set the favorite icon when it changes.
4630 public void onReceivedIcon(WebView view, Bitmap icon) {
4631 // Only update the favorite icon if the website has finished loading.
4632 if (progressBar.getVisibility() == View.GONE) {
4633 // Store the new favorite icon.
4634 nestedScrollWebView.setFavoriteOrDefaultIcon(icon);
4636 // Get the current page position.
4637 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
4639 // Get the current tab.
4640 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
4642 // Check to see if the tab has been populated.
4644 // Get the custom view from the tab.
4645 View tabView = tab.getCustomView();
4647 // Check to see if the custom tab view has been populated.
4648 if (tabView != null) {
4649 // Get the favorite icon image view from the tab.
4650 ImageView tabFavoriteIconImageView = tabView.findViewById(R.id.favorite_icon_imageview);
4652 // Display the favorite icon in the tab.
4653 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
4659 // Save a copy of the title when it changes.
4661 public void onReceivedTitle(WebView view, String title) {
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 // Only populate the title text view if the tab has been fully created.
4670 // Get the custom view from the tab.
4671 View tabView = tab.getCustomView();
4673 // Remove the incorrect warning below that the current tab view might be null.
4674 assert tabView != null;
4676 // Get the title text view from the tab.
4677 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
4679 // Set the title as the tab text.
4680 tabTitleTextView.setText(title);
4684 // Enter full screen video.
4686 public void onShowCustomView(View video, CustomViewCallback callback) {
4687 // Get a handle for the full screen video frame layout.
4688 FrameLayout fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
4690 // Set the full screen video flag.
4691 displayingFullScreenVideo = true;
4693 // Pause the ad if this is the free flavor.
4694 if (BuildConfig.FLAVOR.contentEquals("free")) {
4695 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
4696 AdHelper.pauseAd(findViewById(R.id.adview));
4699 // Hide the keyboard.
4700 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
4702 // Hide the main content relative layout.
4703 mainContentRelativeLayout.setVisibility(View.GONE);
4705 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
4706 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
4708 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
4709 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4711 /* Hide the system bars.
4712 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4713 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4714 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4715 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4717 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
4718 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
4720 // Disable the sliding drawers.
4721 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
4723 // Add the video view to the full screen video frame layout.
4724 fullScreenVideoFrameLayout.addView(video);
4726 // Show the full screen video frame layout.
4727 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
4730 // Exit full screen video.
4732 public void onHideCustomView() {
4733 // Get a handle for the full screen video frame layout.
4734 FrameLayout fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
4736 // Unset the full screen video flag.
4737 displayingFullScreenVideo = false;
4739 // Remove all the views from the full screen video frame layout.
4740 fullScreenVideoFrameLayout.removeAllViews();
4742 // Hide the full screen video frame layout.
4743 fullScreenVideoFrameLayout.setVisibility(View.GONE);
4745 // Enable the sliding drawers.
4746 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
4748 // Show the main content relative layout.
4749 mainContentRelativeLayout.setVisibility(View.VISIBLE);
4751 // Apply the appropriate full screen mode flags.
4752 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
4753 // Hide the app bar if specified.
4755 // Hide the tab linear layout.
4756 tabsLinearLayout.setVisibility(View.GONE);
4758 // Hide the action bar.
4762 // Hide the banner ad in the free flavor.
4763 if (BuildConfig.FLAVOR.contentEquals("free")) {
4764 AdHelper.hideAd(findViewById(R.id.adview));
4767 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
4768 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4770 /* Hide the system bars.
4771 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4772 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4773 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4774 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4776 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
4777 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
4778 } else { // Switch to normal viewing mode.
4779 // Remove the `SYSTEM_UI` flags from the root frame layout.
4780 rootFrameLayout.setSystemUiVisibility(0);
4782 // Add the translucent status flag.
4783 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4786 // Reload the ad for the free flavor if not in full screen mode.
4787 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
4789 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
4795 public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
4796 // Show the file chooser if the device is running API >= 21.
4797 if (Build.VERSION.SDK_INT >= 21) {
4798 // Store the file path callback.
4799 fileChooserCallback = filePathCallback;
4801 // Create an intent to open a chooser based ont the file chooser parameters.
4802 Intent fileChooserIntent = fileChooserParams.createIntent();
4804 // Open the file chooser. Currently only one `startActivityForResult` exists in this activity, so the request code, used to differentiate them, is simply `0`.
4805 startActivityForResult(fileChooserIntent, 0);
4811 nestedScrollWebView.setWebViewClient(new WebViewClient() {
4812 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
4813 // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
4815 public boolean shouldOverrideUrlLoading(WebView view, String url) {
4816 // Sanitize the url.
4817 url = sanitizeUrl(url);
4819 if (url.startsWith("http")) { // Load the URL in Privacy Browser.
4820 // Apply the domain settings for the new URL. This doesn't do anything if the domain has not changed.
4821 boolean userAgentChanged = applyDomainSettings(nestedScrollWebView, url, true, false);
4823 // Check if the user agent has changed.
4824 if (userAgentChanged) {
4825 // Manually load the URL. The changing of the user agent will cause WebView to reload the previous URL.
4826 nestedScrollWebView.loadUrl(url, customHeaders);
4828 // Returning true indicates that Privacy Browser is manually handling the loading of the URL.
4831 // Returning false causes the current WebView to handle the URL and prevents it from adding redirects to the history list.
4834 } else if (url.startsWith("mailto:")) { // Load the email address in an external email program.
4835 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
4836 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
4838 // Parse the url and set it as the data for the intent.
4839 emailIntent.setData(Uri.parse(url));
4841 // Open the email program in a new task instead of as part of Privacy Browser.
4842 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4845 startActivity(emailIntent);
4847 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
4849 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
4850 // Open the dialer and load the phone number, but wait for the user to place the call.
4851 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
4853 // Add the phone number to the intent.
4854 dialIntent.setData(Uri.parse(url));
4856 // Open the dialer in a new task instead of as part of Privacy Browser.
4857 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4860 startActivity(dialIntent);
4862 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
4864 } else { // Load a system chooser to select an app that can handle the URL.
4865 // Open an app that can handle the URL.
4866 Intent genericIntent = new Intent(Intent.ACTION_VIEW);
4868 // Add the URL to the intent.
4869 genericIntent.setData(Uri.parse(url));
4871 // List all apps that can handle the URL instead of just opening the first one.
4872 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
4874 // Open the app in a new task instead of as part of Privacy Browser.
4875 genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4877 // Start the app or display a snackbar if no app is available to handle the URL.
4879 startActivity(genericIntent);
4880 } catch (ActivityNotFoundException exception) {
4881 Snackbar.make(nestedScrollWebView, getString(R.string.unrecognized_url) + " " + url, Snackbar.LENGTH_SHORT).show();
4884 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
4889 // Check requests against the block lists. The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
4891 public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
4892 // Get a handle for the navigation view.
4893 NavigationView navigationView = findViewById(R.id.navigationview);
4895 // Get a handle for the navigation menu.
4896 Menu navigationMenu = navigationView.getMenu();
4898 // Get a handle for the navigation requests menu item. The menu is 0 based.
4899 MenuItem navigationRequestsMenuItem = navigationMenu.getItem(5);
4901 // Create an empty web resource response to be used if the resource request is blocked.
4902 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
4904 // Reset the whitelist results tracker.
4905 String[] whitelistResultStringArray = null;
4907 // Initialize the third party request tracker.
4908 boolean isThirdPartyRequest = false;
4910 // Get the current URL. `.getUrl()` throws an error because operations on the WebView cannot be made from this thread.
4911 String currentBaseDomain = nestedScrollWebView.getCurrentDomainName();
4913 // Store a copy of the current domain for use in later requests.
4914 String currentDomain = currentBaseDomain;
4916 // Nobody is happy when comparing null strings.
4917 if ((currentBaseDomain != null) && (url != null)) {
4918 // Convert the request URL to a URI.
4919 Uri requestUri = Uri.parse(url);
4921 // Get the request host name.
4922 String requestBaseDomain = requestUri.getHost();
4924 // Only check for third-party requests if the current base domain is not empty and the request domain is not null.
4925 if (!currentBaseDomain.isEmpty() && (requestBaseDomain != null)) {
4926 // Determine the current base domain.
4927 while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
4928 // Remove the first subdomain.
4929 currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
4932 // Determine the request base domain.
4933 while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
4934 // Remove the first subdomain.
4935 requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
4938 // Update the third party request tracker.
4939 isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
4943 // Get the current WebView page position.
4944 int webViewPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
4946 // Determine if the WebView is currently displayed.
4947 boolean webViewDisplayed = (webViewPagePosition == tabLayout.getSelectedTabPosition());
4949 // Block third-party requests if enabled.
4950 if (isThirdPartyRequest && nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS)) {
4951 // Add the result to the resource requests.
4952 nestedScrollWebView.addResourceRequest(new String[]{BlockListHelper.REQUEST_THIRD_PARTY, url});
4954 // Increment the blocked requests counters.
4955 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
4956 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS);
4958 // Update the titles of the blocklist menu items if the WebView is currently displayed.
4959 if (webViewDisplayed) {
4960 // Updating the UI must be run from the UI thread.
4961 activity.runOnUiThread(() -> {
4962 // Update the menu item titles.
4963 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
4965 // Update the options menu if it has been populated.
4966 if (optionsMenu != null) {
4967 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
4968 optionsMenu.findItem(R.id.block_all_third_party_requests).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " +
4969 getString(R.string.block_all_third_party_requests));
4974 // Return an empty web resource response.
4975 return emptyWebResourceResponse;
4978 // Check UltraPrivacy if it is enabled.
4979 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY)) {
4980 // Check the URL against UltraPrivacy.
4981 String[] ultraPrivacyResults = blockListHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraPrivacy);
4983 // Process the UltraPrivacy results.
4984 if (ultraPrivacyResults[0].equals(BlockListHelper.REQUEST_BLOCKED)) { // The resource request matched UltraPrivacy's blacklist.
4985 // Add the result to the resource requests.
4986 nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
4987 ultraPrivacyResults[5]});
4989 // Increment the blocked requests counters.
4990 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
4991 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRA_PRIVACY);
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.ultraprivacy).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRA_PRIVACY) + " - " + getString(R.string.ultraprivacy));
5008 // The resource request was blocked. Return an empty web resource response.
5009 return emptyWebResourceResponse;
5010 } else if (ultraPrivacyResults[0].equals(BlockListHelper.REQUEST_ALLOWED)) { // The resource request matched UltraPrivacy's whitelist.
5011 // Add a whitelist entry to the resource requests array.
5012 nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5013 ultraPrivacyResults[5]});
5015 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
5020 // Check EasyList if it is enabled.
5021 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST)) {
5022 // Check the URL against EasyList.
5023 String[] easyListResults = blockListHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyList);
5025 // Process the EasyList results.
5026 if (easyListResults[0].equals(BlockListHelper.REQUEST_BLOCKED)) { // The resource request matched EasyList's blacklist.
5027 // Add the result to the resource requests.
5028 nestedScrollWebView.addResourceRequest(new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]});
5030 // Increment the blocked requests counters.
5031 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5032 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASY_LIST);
5034 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5035 if (webViewDisplayed) {
5036 // Updating the UI must be run from the UI thread.
5037 activity.runOnUiThread(() -> {
5038 // Update the menu item titles.
5039 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5041 // Update the options menu if it has been populated.
5042 if (optionsMenu != null) {
5043 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5044 optionsMenu.findItem(R.id.easylist).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASY_LIST) + " - " + getString(R.string.easylist));
5049 // The resource request was blocked. Return an empty web resource response.
5050 return emptyWebResourceResponse;
5051 } else if (easyListResults[0].equals(BlockListHelper.REQUEST_ALLOWED)) { // The resource request matched EasyList's whitelist.
5052 // Update the whitelist result string array tracker.
5053 whitelistResultStringArray = new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]};
5057 // Check EasyPrivacy if it is enabled.
5058 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY)) {
5059 // Check the URL against EasyPrivacy.
5060 String[] easyPrivacyResults = blockListHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyPrivacy);
5062 // Process the EasyPrivacy results.
5063 if (easyPrivacyResults[0].equals(BlockListHelper.REQUEST_BLOCKED)) { // The resource request matched EasyPrivacy's blacklist.
5064 // Add the result to the resource requests.
5065 nestedScrollWebView.addResourceRequest(new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4],
5066 easyPrivacyResults[5]});
5068 // Increment the blocked requests counters.
5069 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5070 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASY_PRIVACY);
5072 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5073 if (webViewDisplayed) {
5074 // Updating the UI must be run from the UI thread.
5075 activity.runOnUiThread(() -> {
5076 // Update the menu item titles.
5077 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5079 // Update the options menu if it has been populated.
5080 if (optionsMenu != null) {
5081 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5082 optionsMenu.findItem(R.id.easyprivacy).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASY_PRIVACY) + " - " + getString(R.string.easyprivacy));
5087 // The resource request was blocked. Return an empty web resource response.
5088 return emptyWebResourceResponse;
5089 } else if (easyPrivacyResults[0].equals(BlockListHelper.REQUEST_ALLOWED)) { // The resource request matched EasyPrivacy's whitelist.
5090 // Update the whitelist result string array tracker.
5091 whitelistResultStringArray = new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5]};
5095 // Check Fanboy’s Annoyance List if it is enabled.
5096 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST)) {
5097 // Check the URL against Fanboy's Annoyance List.
5098 String[] fanboysAnnoyanceListResults = blockListHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList);
5100 // Process the Fanboy's Annoyance List results.
5101 if (fanboysAnnoyanceListResults[0].equals(BlockListHelper.REQUEST_BLOCKED)) { // The resource request matched Fanboy's Annoyance List's blacklist.
5102 // Add the result to the resource requests.
5103 nestedScrollWebView.addResourceRequest(new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5104 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]});
5106 // Increment the blocked requests counters.
5107 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5108 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST);
5110 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5111 if (webViewDisplayed) {
5112 // Updating the UI must be run from the UI thread.
5113 activity.runOnUiThread(() -> {
5114 // Update the menu item titles.
5115 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5117 // Update the options menu if it has been populated.
5118 if (optionsMenu != null) {
5119 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5120 optionsMenu.findItem(R.id.fanboys_annoyance_list).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " +
5121 getString(R.string.fanboys_annoyance_list));
5126 // The resource request was blocked. Return an empty web resource response.
5127 return emptyWebResourceResponse;
5128 } else if (fanboysAnnoyanceListResults[0].equals(BlockListHelper.REQUEST_ALLOWED)){ // The resource request matched Fanboy's Annoyance List's whitelist.
5129 // Update the whitelist result string array tracker.
5130 whitelistResultStringArray = new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5131 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]};
5133 } else if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST)) { // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
5134 // Check the URL against Fanboy's Annoyance List.
5135 String[] fanboysSocialListResults = blockListHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysSocialList);
5137 // Process the Fanboy's Social Blocking List results.
5138 if (fanboysSocialListResults[0].equals(BlockListHelper.REQUEST_BLOCKED)) { // The resource request matched Fanboy's Social Blocking List's blacklist.
5139 // Add the result to the resource requests.
5140 nestedScrollWebView.addResourceRequest(new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5141 fanboysSocialListResults[4], fanboysSocialListResults[5]});
5143 // Increment the blocked requests counters.
5144 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5145 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST);
5147 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5148 if (webViewDisplayed) {
5149 // Updating the UI must be run from the UI thread.
5150 activity.runOnUiThread(() -> {
5151 // Update the menu item titles.
5152 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5154 // Update the options menu if it has been populated.
5155 if (optionsMenu != null) {
5156 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5157 optionsMenu.findItem(R.id.fanboys_social_blocking_list).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " +
5158 getString(R.string.fanboys_social_blocking_list));
5163 // The resource request was blocked. Return an empty web resource response.
5164 return emptyWebResourceResponse;
5165 } else if (fanboysSocialListResults[0].equals(BlockListHelper.REQUEST_ALLOWED)) { // The resource request matched Fanboy's Social Blocking List's whitelist.
5166 // Update the whitelist result string array tracker.
5167 whitelistResultStringArray = new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5168 fanboysSocialListResults[4], fanboysSocialListResults[5]};
5172 // Add the request to the log because it hasn't been processed by any of the previous checks.
5173 if (whitelistResultStringArray != null) { // The request was processed by a whitelist.
5174 nestedScrollWebView.addResourceRequest(whitelistResultStringArray);
5175 } else { // The request didn't match any blocklist entry. Log it as a default request.
5176 nestedScrollWebView.addResourceRequest(new String[]{BlockListHelper.REQUEST_DEFAULT, url});
5179 // The resource request has not been blocked. `return null` loads the requested resource.
5183 // Handle HTTP authentication requests.
5185 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
5186 // Store the handler.
5187 nestedScrollWebView.setHttpAuthHandler(handler);
5189 // Instantiate an HTTP authentication dialog.
5190 DialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm, nestedScrollWebView.getWebViewFragmentId());
5192 // Show the HTTP authentication dialog.
5193 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
5197 public void onPageStarted(WebView view, String url, Bitmap favicon) {
5198 // Get the preferences.
5199 boolean scrollAppBar = sharedPreferences.getBoolean("scroll_app_bar", true);
5200 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
5202 // Get a handler for the app bar layout.
5203 AppBarLayout appBarLayout = findViewById(R.id.appbar_layout);
5205 // Set the top padding of the swipe refresh layout according to the app bar scrolling preference.
5207 // No padding is needed because it will automatically be placed below the app bar layout due to the scrolling layout behavior.
5208 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5210 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5211 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10, defaultProgressViewEndOffset);
5213 // Get the app bar layout height. This can't be done in `applyAppSettings()` because the app bar is not yet populated.
5214 int appBarHeight = appBarLayout.getHeight();
5216 // The swipe refresh layout must be manually moved below the app bar layout.
5217 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0);
5219 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5220 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight);
5223 // Reset the list of resource requests.
5224 nestedScrollWebView.clearResourceRequests();
5226 // Reset the requests counters.
5227 nestedScrollWebView.resetRequestsCounters();
5229 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
5230 if (nestedScrollWebView.getNightMode()) {
5231 nestedScrollWebView.setVisibility(View.INVISIBLE);
5233 nestedScrollWebView.setVisibility(View.VISIBLE);
5236 // Hide the keyboard.
5237 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
5239 // Check to see if Privacy Browser is waiting on Orbot.
5240 if (!waitingForOrbot) { // Process the URL.
5241 // Get the current page position.
5242 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5244 // Update the URL text bar if the page is currently selected.
5245 if (tabLayout.getSelectedTabPosition() == currentPagePosition) {
5246 // Clear the focus from the URL edit text.
5247 urlEditText.clearFocus();
5249 // Display the formatted URL text.
5250 urlEditText.setText(url);
5252 // Apply text highlighting to `urlTextBox`.
5256 // Reset the list of host IP addresses.
5257 nestedScrollWebView.clearCurrentIpAddresses();
5259 // Get a URI for the current URL.
5260 Uri currentUri = Uri.parse(url);
5262 // Get the IP addresses for the host.
5263 new GetHostIpAddresses(activity, getSupportFragmentManager(), nestedScrollWebView).execute(currentUri.getHost());
5265 // Apply any custom domain settings if the URL was loaded by navigating history.
5266 if (nestedScrollWebView.getNavigatingHistory()) {
5267 // Reset navigating history.
5268 nestedScrollWebView.setNavigatingHistory(false);
5270 // Apply the domain settings.
5271 boolean userAgentChanged = applyDomainSettings(nestedScrollWebView, url, true, false);
5273 // Manually load the URL if the user agent has changed, which will have caused the previous URL to be reloaded.
5274 if (userAgentChanged) {
5279 // Replace Refresh with Stop if the options menu has been created. (The WebView typically begins loading before the menu items are instantiated.)
5280 if (optionsMenu != null) {
5281 // Get a handle for the refresh menu item.
5282 MenuItem refreshMenuItem = optionsMenu.findItem(R.id.refresh);
5285 refreshMenuItem.setTitle(R.string.stop);
5287 // Get the app bar and theme preferences.
5288 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
5290 // If the icon is displayed in the AppBar, set it according to the theme.
5291 if (displayAdditionalAppBarIcons) {
5293 refreshMenuItem.setIcon(R.drawable.close_dark);
5295 refreshMenuItem.setIcon(R.drawable.close_light);
5303 public void onPageFinished(WebView view, String url) {
5304 // Reset the wide view port if it has been turned off by the waiting for Orbot message.
5305 if (!waitingForOrbot) {
5306 // Only use a wide view port if the URL starts with `http`, not for `file://` and `content://`.
5307 nestedScrollWebView.getSettings().setUseWideViewPort(url.startsWith("http"));
5310 // Flush any cookies to persistent storage. The cookie manager has become very lazy about flushing cookies in recent versions.
5311 if (nestedScrollWebView.getAcceptFirstPartyCookies() && Build.VERSION.SDK_INT >= 21) {
5312 CookieManager.getInstance().flush();
5315 // Update the Refresh menu item if the options menu has been created.
5316 if (optionsMenu != null) {
5317 // Get a handle for the refresh menu item.
5318 MenuItem refreshMenuItem = optionsMenu.findItem(R.id.refresh);
5320 // Reset the Refresh title.
5321 refreshMenuItem.setTitle(R.string.refresh);
5323 // Get the app bar and theme preferences.
5324 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
5325 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
5327 // If the icon is displayed in the AppBar, reset it according to the theme.
5328 if (displayAdditionalAppBarIcons) {
5330 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
5332 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
5337 // Clear the cache and history if Incognito Mode is enabled.
5338 if (incognitoModeEnabled) {
5339 // Clear the cache. `true` includes disk files.
5340 nestedScrollWebView.clearCache(true);
5342 // Clear the back/forward history.
5343 nestedScrollWebView.clearHistory();
5345 // Manually delete cache folders.
5347 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
5348 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
5349 String privateDataDirectoryString = getApplicationInfo().dataDir;
5351 // Delete the main cache directory.
5352 Runtime.getRuntime().exec("rm -rf " + privateDataDirectoryString + "/cache");
5354 // Delete the secondary `Service Worker` cache directory.
5355 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
5356 Runtime.getRuntime().exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
5357 } catch (IOException e) {
5358 // Do nothing if an error is thrown.
5362 // Update the URL text box and apply domain settings if not waiting on Orbot.
5363 if (!waitingForOrbot) {
5364 // Get the current page position.
5365 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5367 // Check the current website information against any pinned domain information if the current IP addresses have been loaded.
5368 if ((nestedScrollWebView.hasPinnedSslCertificate() || nestedScrollWebView.hasPinnedIpAddresses()) && nestedScrollWebView.hasCurrentIpAddresses() &&
5369 !nestedScrollWebView.ignorePinnedDomainInformation()) {
5370 CheckPinnedMismatchHelper.checkPinnedMismatch(getSupportFragmentManager(), nestedScrollWebView);
5373 // 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.
5374 String currentUrl = nestedScrollWebView.getUrl();
5376 // Update the URL text bar if the page is currently selected and the user is not currently typing in the URL edit text.
5377 // Crash records show that, in some crazy way, it is possible for the current URL to be blank at this point.
5378 // Probably some sort of race condition when Privacy Browser is being resumed.
5379 if ((tabLayout.getSelectedTabPosition() == currentPagePosition) && !urlEditText.hasFocus() && (currentUrl != null)) {
5380 // Check to see if the URL is `about:blank`.
5381 if (currentUrl.equals("about:blank")) { // The WebView is blank.
5382 // Display the hint in the URL edit text.
5383 urlEditText.setText("");
5385 // Request focus for the URL text box.
5386 urlEditText.requestFocus();
5388 // Display the keyboard.
5389 inputMethodManager.showSoftInput(urlEditText, 0);
5391 // Hide the WebView, which causes the default background color to be displayed according to the theme.
5392 nestedScrollWebView.setVisibility(View.INVISIBLE);
5394 // Apply the domain settings. This clears any settings from the previous domain.
5395 applyDomainSettings(nestedScrollWebView, "", true, false);
5396 } else { // The WebView has loaded a webpage.
5397 // Display the final URL. Getting the URL from the WebView instead of using the one provided by `onPageFinished()` makes websites like YouTube function correctly.
5398 urlEditText.setText(currentUrl);
5400 // Apply text highlighting to the URL.
5405 // Get the current tab.
5406 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
5408 // Only populate the title text view if the tab has been fully created.
5410 // Get the custom view from the tab.
5411 View tabView = tab.getCustomView();
5413 // Remove the incorrect warning below that the current tab view might be null.
5414 assert tabView != null;
5416 // Get the title text view from the tab.
5417 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
5419 // Set the title as the tab text. Sometimes `onReceivedTitle()` is not called, especially when navigating history.
5420 tabTitleTextView.setText(nestedScrollWebView.getTitle());
5425 // Handle SSL Certificate errors.
5427 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
5428 // Get the current website SSL certificate.
5429 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
5431 // Extract the individual pieces of information from the current website SSL certificate.
5432 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
5433 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
5434 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
5435 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
5436 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
5437 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
5438 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
5439 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
5441 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
5442 if (nestedScrollWebView.hasPinnedSslCertificate()) {
5443 // Get the pinned SSL certificate.
5444 ArrayList<Object> pinnedSslCertificateArrayList = nestedScrollWebView.getPinnedSslCertificate();
5446 // Extract the arrays from the array list.
5447 String[] pinnedSslCertificateStringArray = (String[]) pinnedSslCertificateArrayList.get(0);
5448 Date[] pinnedSslCertificateDateArray = (Date[]) pinnedSslCertificateArrayList.get(1);
5450 // Check if the current SSL certificate matches the pinned certificate.
5451 if (currentWebsiteIssuedToCName.equals(pinnedSslCertificateStringArray[0]) && currentWebsiteIssuedToOName.equals(pinnedSslCertificateStringArray[1]) &&
5452 currentWebsiteIssuedToUName.equals(pinnedSslCertificateStringArray[2]) && currentWebsiteIssuedByCName.equals(pinnedSslCertificateStringArray[3]) &&
5453 currentWebsiteIssuedByOName.equals(pinnedSslCertificateStringArray[4]) && currentWebsiteIssuedByUName.equals(pinnedSslCertificateStringArray[5]) &&
5454 currentWebsiteSslStartDate.equals(pinnedSslCertificateDateArray[0]) && currentWebsiteSslEndDate.equals(pinnedSslCertificateDateArray[1])) {
5456 // An SSL certificate is pinned and matches the current domain certificate. Proceed to the website without displaying an error.
5459 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
5460 // Store the SSL error handler.
5461 nestedScrollWebView.setSslErrorHandler(handler);
5463 // Instantiate an SSL certificate error alert dialog.
5464 DialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error, nestedScrollWebView.getWebViewFragmentId());
5466 // Show the SSL certificate error dialog.
5467 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
5472 // Check to see if this is the first page.
5473 if (pageNumber == 0) {
5474 // Set this nested scroll WebView as the current WebView.
5475 currentWebView = nestedScrollWebView;
5477 // Apply the app settings from the shared preferences.
5480 // Load the website if not waiting for Orbot to connect.
5481 if (!waitingForOrbot) {
5482 // Get the intent that started the app.
5483 Intent launchingIntent = getIntent();
5485 // Get the information from the intent.
5486 String launchingIntentAction = launchingIntent.getAction();
5487 Uri launchingIntentUriData = launchingIntent.getData();
5489 // If the intent action is a web search, perform the search.
5490 if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) {
5491 // Create an encoded URL string.
5492 String encodedUrlString;
5494 // Sanitize the search input and convert it to a search.
5496 encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
5497 } catch (UnsupportedEncodingException exception) {
5498 encodedUrlString = "";
5501 // Load the completed search URL.
5502 loadUrl(searchURL + encodedUrlString);
5503 } else if (launchingIntentUriData != null){ // Check to see if the intent contains a new URL.
5504 // Load the URL from the intent.
5505 loadUrl(launchingIntentUriData.toString());
5506 } else { // The is no URL in the intent.
5507 // Select the homepage based on the proxy through Orbot status.
5508 if (proxyThroughOrbot) {
5509 // Load the Tor homepage.
5510 loadUrl(sharedPreferences.getString("tor_homepage", getString(R.string.tor_homepage_default_value)));
5512 // Load the normal homepage.
5513 loadUrl(sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
5517 } else { // This is not the first tab.
5518 // Apply the domain settings.
5519 applyDomainSettings(nestedScrollWebView, url, false, false);
5522 nestedScrollWebView.loadUrl(url, customHeaders);
5524 // Display the keyboard if the URL is blank.
5525 if (url.equals("")) {
5526 inputMethodManager.showSoftInput(urlEditText, 0);