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.WebBackForwardList;
75 import android.webkit.WebChromeClient;
76 import android.webkit.WebResourceResponse;
77 import android.webkit.WebSettings;
78 import android.webkit.WebStorage;
79 import android.webkit.WebView;
80 import android.webkit.WebViewClient;
81 import android.webkit.WebViewDatabase;
82 import android.widget.ArrayAdapter;
83 import android.widget.CursorAdapter;
84 import android.widget.EditText;
85 import android.widget.FrameLayout;
86 import android.widget.ImageView;
87 import android.widget.LinearLayout;
88 import android.widget.ListView;
89 import android.widget.ProgressBar;
90 import android.widget.RadioButton;
91 import android.widget.RelativeLayout;
92 import android.widget.TextView;
94 import androidx.annotation.NonNull;
95 import androidx.appcompat.app.ActionBar;
96 import androidx.appcompat.app.ActionBarDrawerToggle;
97 import androidx.appcompat.app.AppCompatActivity;
98 import androidx.appcompat.widget.Toolbar;
99 import androidx.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.floatingactionbutton.FloatingActionButton;
109 import com.google.android.material.navigation.NavigationView;
110 import com.google.android.material.snackbar.Snackbar;
111 import com.google.android.material.tabs.TabLayout;
113 import com.stoutner.privacybrowser.BuildConfig;
114 import com.stoutner.privacybrowser.R;
115 import com.stoutner.privacybrowser.adapters.WebViewPagerAdapter;
116 import com.stoutner.privacybrowser.asynctasks.GetHostIpAddresses;
117 import com.stoutner.privacybrowser.dialogs.AdConsentDialog;
118 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
119 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
120 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
121 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
122 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
123 import com.stoutner.privacybrowser.dialogs.DownloadLocationPermissionDialog;
124 import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
125 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
126 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
127 import com.stoutner.privacybrowser.dialogs.PinnedMismatchDialog;
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 // TODO. Store up reloads for tabs that are not visible.
158 // TODO. New tabs are white in dark mode.
159 // TODO. Hide the tabs in full screen mode.
160 // TODO. Find on page.
161 // TODO. Use TabLayout.setScrollPosition to scroll to new tabs.
163 // AppCompatActivity from android.support.v7.app.AppCompatActivity must be used to have access to the SupportActionBar until the minimum API is >= 21.
164 public class MainWebViewActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener,
165 DownloadFileDialog.DownloadFileListener, DownloadImageDialog.DownloadImageListener, DownloadLocationPermissionDialog.DownloadLocationPermissionDialogListener, EditBookmarkDialog.EditBookmarkListener,
166 EditBookmarkFolderDialog.EditBookmarkFolderListener, NavigationView.OnNavigationItemSelectedListener, WebViewTabFragment.NewTabListener, PinnedMismatchDialog.PinnedMismatchListener,
167 UrlHistoryDialog.UrlHistoryListener {
169 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`, `onResume()`, and `applyProxyThroughOrbot()`.
170 public static String orbotStatus;
172 // The WebView pager adapter is accessed from `HttpAuthenticationDialog`, `PinnedMismatchDialog`, and `SslCertificateErrorDialog`. It is also used in `onCreate()`, `onResume()`, and `addTab()`.
173 public static WebViewPagerAdapter webViewPagerAdapter;
175 // `reloadOnRestart` is public static so it can be accessed from `SettingsFragment`. It is used in `onRestart()`
176 public static boolean reloadOnRestart;
178 // The load URL on restart variables are public static so they can be accessed from `BookmarksActivity`. They are used in `onRestart()`.
179 public static boolean loadUrlOnRestart;
180 public static String urlToLoadOnRestart;
182 // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onRestart()`.
183 public static boolean restartFromBookmarksActivity;
185 // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`,
186 // `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
187 public static String currentBookmarksFolder;
189 // The user agent constants are public static so they can be accessed from `SettingsFragment`, `DomainsActivity`, and `DomainSettingsFragment`.
190 public final static int UNRECOGNIZED_USER_AGENT = -1;
191 public final static int SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1;
192 public final static int SETTINGS_CUSTOM_USER_AGENT = 12;
193 public final static int DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0;
194 public final static int DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2;
195 public final static int DOMAINS_CUSTOM_USER_AGENT = 13;
199 // The current WebView is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
200 // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, `applyProxyThroughOrbot()`, and `applyDomainSettings()`.
201 private NestedScrollWebView currentWebView;
203 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
204 private final Map<String, String> customHeaders = new HashMap<>();
206 // The search URL is set in `applyProxyThroughOrbot()` and used in `onCreate()`, `onNewIntent()`, `loadURLFromTextBox()`, and `initializeWebView()`.
207 private String searchURL;
209 // The options menu is set in `onCreateOptionsMenu()` and used in `onOptionsItemSelected()`, `updatePrivacyIcons()`, and `initializeWebView()`.
210 private Menu optionsMenu;
212 // The blocklists are populated in `onCreate()` and accessed from `initializeWebView()`.
213 private ArrayList<List<String[]>> easyList;
214 private ArrayList<List<String[]>> easyPrivacy;
215 private ArrayList<List<String[]>> fanboysAnnoyanceList;
216 private ArrayList<List<String[]>> fanboysSocialList;
217 private ArrayList<List<String[]>> ultraPrivacy;
219 // `webViewDefaultUserAgent` is used in `onCreate()` and `onPrepareOptionsMenu()`.
220 private String webViewDefaultUserAgent;
222 // `proxyThroughOrbot` is used in `onRestart()`, `onOptionsItemSelected()`, `applyAppSettings()`, and `applyProxyThroughOrbot()`.
223 private boolean proxyThroughOrbot;
225 // The incognito mode is set in `applyAppSettings()` and used in `initializeWebView()`.
226 private boolean incognitoModeEnabled;
228 // The full screen browsing mode tracker is set it `applyAppSettings()` and used in `initializeWebView()`.
229 private boolean fullScreenBrowsingModeEnabled;
231 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
232 private boolean inFullScreenBrowsingMode;
234 // Hide app bar is used in `applyAppSettings()` and `initializeWebView()`.
235 private boolean hideAppBar;
237 // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
238 private boolean reapplyDomainSettingsOnRestart;
240 // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
241 private boolean reapplyAppSettingsOnRestart;
243 // `displayingFullScreenVideo` is used in `onCreate()` and `onResume()`.
244 private boolean displayingFullScreenVideo;
246 // `orbotStatusBroadcastReceiver` is used in `onCreate()` and `onDestroy()`.
247 private BroadcastReceiver orbotStatusBroadcastReceiver;
249 // `waitingForOrbot` is used in `onCreate()`, `onResume()`, and `applyProxyThroughOrbot()`.
250 private boolean waitingForOrbot;
252 // The action bar drawer toggle is initialized in `onCreate()` and used in `onResume()`.
253 private ActionBarDrawerToggle actionBarDrawerToggle;
255 // The color spans are used in `onCreate()` and `highlightUrlText()`.
256 private ForegroundColorSpan redColorSpan;
257 private ForegroundColorSpan initialGrayColorSpan;
258 private ForegroundColorSpan finalGrayColorSpan;
260 // The drawer header padding variables are used in `onCreate()` and `onConfigurationChanged()`.
261 private int drawerHeaderPaddingLeftAndRight;
262 private int drawerHeaderPaddingTop;
263 private int drawerHeaderPaddingBottom;
265 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onDestroy`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`,
266 // and `loadBookmarksFolder()`.
267 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
269 // `bookmarksCursor` is used in `onDestroy()`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
270 private Cursor bookmarksCursor;
272 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
273 private CursorAdapter bookmarksCursorAdapter;
275 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
276 private String oldFolderNameString;
278 // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
279 private ValueCallback<Uri[]> fileChooserCallback;
281 // The download strings are used in `onCreate()`, `onRequestPermissionResult()` and `initializeWebView()`.
282 private String downloadUrl;
283 private String downloadContentDisposition;
284 private long downloadContentLength;
286 // `downloadImageUrl` is used in `onCreateContextMenu()` and `onRequestPermissionResult()`.
287 private String downloadImageUrl;
289 // The request codes are used in `onCreate()`, `onCreateContextMenu()`, `onCloseDownloadLocationPermissionDialog()`, `onRequestPermissionResult()`, and `initializeWebView()`.
290 private final int DOWNLOAD_FILE_REQUEST_CODE = 1;
291 private final int DOWNLOAD_IMAGE_REQUEST_CODE = 2;
294 // Remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
295 @SuppressLint("ClickableViewAccessibility")
296 protected void onCreate(Bundle savedInstanceState) {
297 // Get a handle for the shared preferences.
298 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
300 // Get the theme and screenshot preferences.
301 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
302 boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
304 // Disable screenshots if not allowed.
305 if (!allowScreenshots) {
306 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
309 // Set the activity theme.
311 setTheme(R.style.PrivacyBrowserDark);
313 setTheme(R.style.PrivacyBrowserLight);
316 // Run the default commands.
317 super.onCreate(savedInstanceState);
319 // Set the content view.
320 setContentView(R.layout.main_framelayout);
322 // Get a handle for the input method.
323 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
325 // Remove the lint warning below that the input method manager might be null.
326 assert inputMethodManager != null;
328 // Get a handle for the toolbar.
329 Toolbar toolbar = findViewById(R.id.toolbar);
331 // Set the action bar. `SupportActionBar` must be used until the minimum API is >= 21.
332 setSupportActionBar(toolbar);
334 // Get a handle for the action bar.
335 ActionBar actionBar = getSupportActionBar();
337 // This is needed to get rid of the Android Studio warning that the action bar might be null.
338 assert actionBar != null;
340 // Add the custom layout, which shows the URL text bar.
341 actionBar.setCustomView(R.layout.url_app_bar);
342 actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
344 // Initialize the foreground color spans for highlighting the URLs. We have to use the deprecated `getColor()` until API >= 23.
345 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
346 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
347 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
349 // Get handles for the URL views.
350 EditText urlEditText = findViewById(R.id.url_edittext);
352 // Remove the formatting from `urlTextBar` when the user is editing the text.
353 urlEditText.setOnFocusChangeListener((View v, boolean hasFocus) -> {
354 if (hasFocus) { // The user is editing the URL text box.
355 // Remove the highlighting.
356 urlEditText.getText().removeSpan(redColorSpan);
357 urlEditText.getText().removeSpan(initialGrayColorSpan);
358 urlEditText.getText().removeSpan(finalGrayColorSpan);
359 } else { // The user has stopped editing the URL text box.
360 // Move to the beginning of the string.
361 urlEditText.setSelection(0);
363 // Reapply the highlighting.
368 // Set the go button on the keyboard to load the URL in `urlTextBox`.
369 urlEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
370 // If the event is a key-down event on the `enter` button, load the URL.
371 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
372 // Load the URL into the mainWebView and consume the event.
373 loadUrlFromTextBox();
375 // If the enter key was pressed, consume the event.
378 // If any other key was pressed, do not consume the event.
383 // Initialize the Orbot status and the waiting for Orbot trackers.
384 orbotStatus = "unknown";
385 waitingForOrbot = false;
387 // Create an Orbot status `BroadcastReceiver`.
388 orbotStatusBroadcastReceiver = new BroadcastReceiver() {
390 public void onReceive(Context context, Intent intent) {
391 // Store the content of the status message in `orbotStatus`.
392 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
394 // If Privacy Browser is waiting on Orbot, load the website now that Orbot is connected.
395 if (orbotStatus.equals("ON") && waitingForOrbot) {
396 // Reset the waiting for Orbot status.
397 waitingForOrbot = false;
399 // Get the intent that started the app.
400 Intent launchingIntent = getIntent();
402 // Get the information from the intent.
403 String launchingIntentAction = launchingIntent.getAction();
404 Uri launchingIntentUriData = launchingIntent.getData();
406 // If the intent action is a web search, perform the search.
407 if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) {
408 // Create an encoded URL string.
409 String encodedUrlString;
411 // Sanitize the search input and convert it to a search.
413 encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
414 } catch (UnsupportedEncodingException exception) {
415 encodedUrlString = "";
418 // Load the completed search URL.
419 loadUrl(searchURL + encodedUrlString);
420 } else if (launchingIntentUriData != null){ // Check to see if the intent contains a new URL.
421 // Load the URL from the intent.
422 loadUrl(launchingIntentUriData.toString());
423 } else { // The is no URL in the intent.
424 // Select the homepage based on the proxy through Orbot status.
425 if (proxyThroughOrbot) {
426 // Load the Tor homepage.
427 loadUrl(sharedPreferences.getString("tor_homepage", getString(R.string.tor_homepage_default_value)));
429 // Load the normal homepage.
430 loadUrl(sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
437 // Register `orbotStatusBroadcastReceiver` on `this` context.
438 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
440 // Instantiate the blocklist helper.
441 BlockListHelper blockListHelper = new BlockListHelper();
443 // Parse the block lists.
444 easyList = blockListHelper.parseBlockList(getAssets(), "blocklists/easylist.txt");
445 easyPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/easyprivacy.txt");
446 fanboysAnnoyanceList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-annoyance.txt");
447 fanboysSocialList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-social.txt");
448 ultraPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/ultraprivacy.txt");
450 // Get handles for views that need to be modified.
451 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
452 NavigationView navigationView = findViewById(R.id.navigationview);
453 TabLayout tabLayout = findViewById(R.id.tablayout);
454 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
455 ViewPager webViewPager = findViewById(R.id.webviewpager);
456 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
457 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
458 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
459 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
460 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
462 // Listen for touches on the navigation menu.
463 navigationView.setNavigationItemSelectedListener(this);
465 // Get handles for the navigation menu and the back and forward menu items. The menu is zero-based.
466 Menu navigationMenu = navigationView.getMenu();
467 MenuItem navigationCloseTabMenuItem = navigationMenu.getItem(0);
468 MenuItem navigationBackMenuItem = navigationMenu.getItem(3);
469 MenuItem navigationForwardMenuItem = navigationMenu.getItem(4);
470 MenuItem navigationHistoryMenuItem = navigationMenu.getItem(5);
471 MenuItem navigationRequestsMenuItem = navigationMenu.getItem(6);
473 // Initialize the web view pager adapter.
474 webViewPagerAdapter = new WebViewPagerAdapter(getSupportFragmentManager());
476 // Set the pager adapter on the web view pager.
477 webViewPager.setAdapter(webViewPagerAdapter);
479 // Store up to 100 tabs in memory.
480 webViewPager.setOffscreenPageLimit(100);
482 // Update the web view pager every time a tab is modified.
483 webViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
485 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
490 public void onPageSelected(int position) {
491 // Set the current WebView.
492 setCurrentWebView(position);
494 // 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.
495 if (tabLayout.getSelectedTabPosition() != position) {
496 // Get a handle for the corresponding tab.
497 TabLayout.Tab correspondingTab = tabLayout.getTabAt(position);
499 // Assert that the corresponding tab is not null.
500 assert correspondingTab != null;
502 // Select the corresponding tab.
503 correspondingTab.select();
508 public void onPageScrollStateChanged(int state) {
513 // Display the View SSL Certificate dialog when the currently selected tab is reselected.
514 tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
516 public void onTabSelected(TabLayout.Tab tab) {
517 // Select the same page in the view pager.
518 webViewPager.setCurrentItem(tab.getPosition());
522 public void onTabUnselected(TabLayout.Tab tab) {
527 public void onTabReselected(TabLayout.Tab tab) {
528 // Instantiate the View SSL Certificate dialog.
529 DialogFragment viewSslCertificateDialogFragment = ViewSslCertificateDialog.displayDialog(currentWebView.getWebViewFragmentId());
531 // Display the View SSL Certificate dialog.
532 viewSslCertificateDialogFragment.show(getSupportFragmentManager(), getString(R.string.view_ssl_certificate));
536 // Add the first tab.
539 // 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.
540 // The deprecated `getResources().getDrawable()` must be used until the minimum API >= 21 and and `getResources().getColor()` must be used until the minimum API >= 23.
542 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
543 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
544 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
545 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
547 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
548 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
549 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
550 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
553 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
554 launchBookmarksActivityFab.setOnClickListener(v -> {
555 // Get a copy of the favorite icon bitmap.
556 Bitmap favoriteIconBitmap = currentWebView.getFavoriteOrDefaultIcon();
558 // Create a favorite icon byte array output stream.
559 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
561 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
562 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
564 // Convert the favorite icon byte array stream to a byte array.
565 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
567 // Create an intent to launch the bookmarks activity.
568 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
570 // Add the extra information to the intent.
571 bookmarksIntent.putExtra("current_url", currentWebView.getUrl());
572 bookmarksIntent.putExtra("current_title", currentWebView.getTitle());
573 bookmarksIntent.putExtra("current_folder", currentBookmarksFolder);
574 bookmarksIntent.putExtra("favorite_icon_byte_array", favoriteIconByteArray);
577 startActivity(bookmarksIntent);
580 // Set the create new bookmark folder FAB to display an alert dialog.
581 createBookmarkFolderFab.setOnClickListener(v -> {
582 // Create a create bookmark folder dialog.
583 DialogFragment createBookmarkFolderDialog = CreateBookmarkFolderDialog.createBookmarkFolder(currentWebView.getFavoriteOrDefaultIcon());
585 // Show the create bookmark folder dialog.
586 createBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.create_folder));
589 // Set the create new bookmark FAB to display an alert dialog.
590 createBookmarkFab.setOnClickListener(view -> {
591 // Instantiate the create bookmark dialog.
592 DialogFragment createBookmarkDialog = CreateBookmarkDialog.createBookmark(currentWebView.getUrl(), currentWebView.getTitle(), currentWebView.getFavoriteOrDefaultIcon());
594 // Display the create bookmark dialog.
595 createBookmarkDialog.show(getSupportFragmentManager(), getString(R.string.create_bookmark));
598 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
599 findOnPageEditText.addTextChangedListener(new TextWatcher() {
601 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
606 public void onTextChanged(CharSequence s, int start, int before, int count) {
611 public void afterTextChanged(Editable s) {
612 // Search for the text in `mainWebView`.
613 currentWebView.findAllAsync(findOnPageEditText.getText().toString());
617 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
618 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
619 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
620 // Hide the soft keyboard.
621 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
623 // Consume the event.
625 } else { // A different key was pressed.
626 // Do not consume the event.
631 // Implement swipe to refresh.
632 swipeRefreshLayout.setOnRefreshListener(() -> currentWebView.reload());
634 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
635 swipeRefreshLayout.setProgressViewOffset(false, swipeRefreshLayout.getProgressViewStartOffset() - 10, swipeRefreshLayout.getProgressViewEndOffset());
637 // Set the swipe to refresh color according to the theme.
639 swipeRefreshLayout.setColorSchemeResources(R.color.blue_800);
640 swipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.gray_850);
642 swipeRefreshLayout.setColorSchemeResources(R.color.blue_500);
645 // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
646 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
647 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
649 // Initialize the bookmarks database helper. The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
650 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
652 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
653 currentBookmarksFolder = "";
655 // Load the home folder, which is `""` in the database.
656 loadBookmarksFolder();
658 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
659 // Convert the id from long to int to match the format of the bookmarks database.
660 int databaseID = (int) id;
662 // Get the bookmark cursor for this ID and move it to the first row.
663 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseID);
664 bookmarkCursor.moveToFirst();
666 // Act upon the bookmark according to the type.
667 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
668 // Store the new folder name in `currentBookmarksFolder`.
669 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
671 // Load the new folder.
672 loadBookmarksFolder();
673 } else { // The selected bookmark is not a folder.
674 // Load the bookmark URL.
675 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
677 // Close the bookmarks drawer.
678 drawerLayout.closeDrawer(GravityCompat.END);
681 // Close the `Cursor`.
682 bookmarkCursor.close();
685 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
686 // Convert the database ID from `long` to `int`.
687 int databaseId = (int) id;
689 // Find out if the selected bookmark is a folder.
690 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
693 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
694 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
696 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
697 DialogFragment editBookmarkFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId, currentWebView.getFavoriteOrDefaultIcon());
698 editBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.edit_folder));
700 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
701 DialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId, currentWebView.getFavoriteOrDefaultIcon());
702 editBookmarkDialog.show(getSupportFragmentManager(), getString(R.string.edit_bookmark));
705 // Consume the event.
709 // Get the status bar pixel size.
710 int statusBarResourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
711 int statusBarPixelSize = getResources().getDimensionPixelSize(statusBarResourceId);
713 // Get the resource density.
714 float screenDensity = getResources().getDisplayMetrics().density;
716 // Calculate the drawer header padding. This is used to move the text in the drawer headers below any cutouts.
717 drawerHeaderPaddingLeftAndRight = (int) (15 * screenDensity);
718 drawerHeaderPaddingTop = statusBarPixelSize + (int) (4 * screenDensity);
719 drawerHeaderPaddingBottom = (int) (8 * screenDensity);
721 // The drawer listener is used to update the navigation menu.`
722 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
724 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
728 public void onDrawerOpened(@NonNull View drawerView) {
732 public void onDrawerClosed(@NonNull View drawerView) {
736 public void onDrawerStateChanged(int newState) {
737 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // A drawer is opening or closing.
738 // Get handles for the drawer headers.
739 TextView navigationHeaderTextView = findViewById(R.id.navigationText);
740 TextView bookmarksHeaderTextView = findViewById(R.id.bookmarks_title_textview);
742 // 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.
743 if (navigationHeaderTextView != null) {
744 navigationHeaderTextView.setPadding(drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingTop, drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingBottom);
747 // 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.
748 if (bookmarksHeaderTextView != null) {
749 bookmarksHeaderTextView.setPadding(drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingTop, drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingBottom);
752 // Update the navigation menu items.
753 navigationCloseTabMenuItem.setEnabled(tabLayout.getTabCount() > 1);
754 navigationBackMenuItem.setEnabled(currentWebView.canGoBack());
755 navigationForwardMenuItem.setEnabled(currentWebView.canGoForward());
756 navigationHistoryMenuItem.setEnabled((currentWebView.canGoBack() || currentWebView.canGoForward()));
757 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
759 // Hide the keyboard (if displayed).
760 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
762 // 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.
763 urlEditText.clearFocus();
764 currentWebView.clearFocus();
769 // Create the hamburger icon at the start of the AppBar.
770 actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
772 // 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).
773 customHeaders.put("X-Requested-With", "");
775 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
776 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
778 // Inflate a bare WebView to get the default user agent. It is not used to render content on the screen.
779 @SuppressLint("InflateParams") View webViewLayout = getLayoutInflater().inflate(R.layout.bare_webview, null, false);
781 // Get a handle for the WebView.
782 WebView bareWebView = webViewLayout.findViewById(R.id.bare_webview);
784 // Store the default user agent.
785 webViewDefaultUserAgent = bareWebView.getSettings().getUserAgentString();
787 // Destroy the bare WebView.
788 bareWebView.destroy();
792 protected void onNewIntent(Intent intent) {
793 // Get the information from the intent.
794 String intentAction = intent.getAction();
795 Uri intentUriData = intent.getData();
797 // Only process the URI if it contains data. If the user pressed the desktop icon after the app was already running the URI will be null.
798 if (intentUriData != null) {
799 // Sets the new intent as the activity intent, which replaces the one that originally started the app.
805 // Create a URL string.
808 // If the intent action is a web search, perform the search.
809 if ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH)) {
810 // Create an encoded URL string.
811 String encodedUrlString;
813 // Sanitize the search input and convert it to a search.
815 encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
816 } catch (UnsupportedEncodingException exception) {
817 encodedUrlString = "";
820 // Add the base search URL.
821 url = searchURL + encodedUrlString;
822 } else { // The intent should contain a URL.
823 // Set the intent data as the URL.
824 url = intentUriData.toString();
830 // Get a handle for the drawer layout.
831 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
833 // Close the navigation drawer if it is open.
834 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
835 drawerLayout.closeDrawer(GravityCompat.START);
838 // Close the bookmarks drawer if it is open.
839 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
840 drawerLayout.closeDrawer(GravityCompat.END);
843 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
844 currentWebView.requestFocus();
849 public void onRestart() {
850 // Run the default commands.
853 // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
854 if (proxyThroughOrbot) {
855 // Request Orbot to start. If Orbot is already running no hard will be caused by this request.
856 Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
858 // Send the intent to the Orbot package.
859 orbotIntent.setPackage("org.torproject.android");
862 sendBroadcast(orbotIntent);
865 // Apply the app settings if returning from the Settings activity.
866 if (reapplyAppSettingsOnRestart) {
867 // Apply the app settings.
870 // Reload the webpage to handle changes to night mode and displaying of images.
871 if (reloadOnRestart) {
872 // Reload the WebViews.
873 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
874 // Get the WebView tab fragment.
875 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
877 // Get the fragment view.
878 View fragmentView = webViewTabFragment.getView();
880 // Only reload the WebViews if they exist.
881 if (fragmentView != null) {
882 // Get the nested scroll WebView from the tab fragment.
883 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
885 // Reload the WebView. This doesn't seem to work if for WebViews that aren't visible.
886 nestedScrollWebView.reload();
890 // Reset `reloadOnRestartBoolean`.
891 reloadOnRestart = false;
894 // Reset the return from settings flag.
895 reapplyAppSettingsOnRestart = false;
898 // TODO apply to all the tabs.
899 // Apply the domain settings if returning from the Domains activity.
900 if (reapplyDomainSettingsOnRestart) {
901 // Reset the current domain name so the domain settings will be reapplied.
902 currentWebView.resetCurrentDomainName();
904 // Reapply the domain settings.
905 applyDomainSettings(currentWebView, currentWebView.getUrl(), false, true); // TODO.
907 // Reset the reapply domain settings on restart tracker.
908 reapplyDomainSettingsOnRestart = false;
911 // Load the URL on restart (used when loading a bookmark.
912 if (loadUrlOnRestart) {
913 // Load the specified URL.
914 loadUrl(urlToLoadOnRestart);
916 // Reset the load on restart tracker.
917 loadUrlOnRestart = false;
920 // Update the bookmarks drawer if returning from the Bookmarks activity.
921 if (restartFromBookmarksActivity) {
922 // Get a handle for the drawer layout.
923 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
925 // Close the bookmarks drawer.
926 drawerLayout.closeDrawer(GravityCompat.END);
928 // Reload the bookmarks drawer.
929 loadBookmarksFolder();
931 // Reset `restartFromBookmarksActivity`.
932 restartFromBookmarksActivity = false;
935 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
936 updatePrivacyIcons(true);
939 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
941 public void onResume() {
942 // Run the default commands.
945 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
946 // Get the WebView tab fragment.
947 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
949 // Get the fragment view.
950 View fragmentView = webViewTabFragment.getView();
952 // Only resume the WebViews if they exist (they won't when the app is first created).
953 if (fragmentView != null) {
954 // Get the nested scroll WebView from the tab fragment.
955 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
957 // Resume the nested scroll WebView JavaScript timers.
958 nestedScrollWebView.resumeTimers();
960 // Resume the nested scroll WebView.
961 nestedScrollWebView.onResume();
965 // Display a message to the user if waiting for Orbot.
966 if (waitingForOrbot && !orbotStatus.equals("ON")) {
967 // Disable the wide view port so that the waiting for Orbot text is displayed correctly.
968 currentWebView.getSettings().setUseWideViewPort(false);
970 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
971 currentWebView.loadData("<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>", "text/html", null);
974 if (displayingFullScreenVideo || inFullScreenBrowsingMode) {
975 // Get a handle for the root frame layouts.
976 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
978 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
979 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
981 /* Hide the system bars.
982 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
983 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
984 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
985 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
987 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
988 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
989 } else if (BuildConfig.FLAVOR.contentEquals("free")) { // Resume the adView for the free flavor.
991 AdHelper.resumeAd(findViewById(R.id.adview));
996 public void onPause() {
997 // Run the default commands.
1000 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
1001 // Get the WebView tab fragment.
1002 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
1004 // Get the fragment view.
1005 View fragmentView = webViewTabFragment.getView();
1007 // Only pause the WebViews if they exist (they won't when the app is first created).
1008 if (fragmentView != null) {
1009 // Get the nested scroll WebView from the tab fragment.
1010 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
1012 // Pause the nested scroll WebView.
1013 nestedScrollWebView.onPause();
1015 // Pause the nested scroll WebView JavaScript timers.
1016 nestedScrollWebView.pauseTimers();
1020 // Pause the ad or it will continue to consume resources in the background on the free flavor.
1021 if (BuildConfig.FLAVOR.contentEquals("free")) {
1023 AdHelper.pauseAd(findViewById(R.id.adview));
1028 public void onDestroy() {
1029 // Unregister the Orbot status broadcast receiver.
1030 this.unregisterReceiver(orbotStatusBroadcastReceiver);
1032 // Close the bookmarks cursor and database.
1033 bookmarksCursor.close();
1034 bookmarksDatabaseHelper.close();
1036 // Run the default commands.
1041 public boolean onCreateOptionsMenu(Menu menu) {
1042 // Inflate the menu. This adds items to the action bar if it is present.
1043 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1045 // Store a handle for the options menu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons()`.
1048 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1049 updatePrivacyIcons(false);
1051 // Get handles for the menu items.
1052 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1053 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1054 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1055 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
1056 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
1057 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1058 MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
1060 // Only display third-party cookies if API >= 21
1061 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1063 // Only display the form data menu items if the API < 26.
1064 toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1065 clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1067 // Disable the clear form data menu item if the API >= 26 so that the status of the main Clear Data is calculated correctly.
1068 clearFormDataMenuItem.setEnabled(Build.VERSION.SDK_INT < 26);
1070 // Only show Ad Consent if this is the free flavor.
1071 adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
1073 // Get the shared preference values.
1074 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1076 // Get the dark theme and app bar preferences..
1077 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
1078 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
1080 // 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.
1081 if (displayAdditionalAppBarIcons) {
1082 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1083 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1084 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
1085 } else { //Do not display the additional icons.
1086 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1087 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1088 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1091 // Replace Refresh with Stop if a URL is already loading.
1092 if (currentWebView != null && currentWebView.getProgress() != 100) {
1094 refreshMenuItem.setTitle(R.string.stop);
1096 // If the icon is displayed in the AppBar, set it according to the theme.
1097 if (displayAdditionalAppBarIcons) {
1099 refreshMenuItem.setIcon(R.drawable.close_dark);
1101 refreshMenuItem.setIcon(R.drawable.close_light);
1110 public boolean onPrepareOptionsMenu(Menu menu) {
1111 // Get handles for the menu items.
1112 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
1113 MenuItem firstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1114 MenuItem thirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1115 MenuItem domStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1116 MenuItem saveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
1117 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
1118 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1119 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1120 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
1121 MenuItem blocklistsMenuItem = menu.findItem(R.id.blocklists);
1122 MenuItem easyListMenuItem = menu.findItem(R.id.easylist);
1123 MenuItem easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
1124 MenuItem fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
1125 MenuItem fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
1126 MenuItem ultraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
1127 MenuItem blockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
1128 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1129 MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
1130 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1131 MenuItem nightModeMenuItem = menu.findItem(R.id.night_mode);
1132 MenuItem proxyThroughOrbotMenuItem = menu.findItem(R.id.proxy_through_orbot);
1134 // Get a handle for the cookie manager.
1135 CookieManager cookieManager = CookieManager.getInstance();
1137 // Initialize the current user agent string and the font size.
1138 String currentUserAgent = getString(R.string.user_agent_privacy_browser);
1141 // 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.
1142 if (currentWebView != null) {
1143 // Set the add or edit domain text.
1144 if (currentWebView.getDomainSettingsApplied()) {
1145 addOrEditDomain.setTitle(R.string.edit_domain_settings);
1147 addOrEditDomain.setTitle(R.string.add_domain_settings);
1150 // Get the current user agent from the WebView.
1151 currentUserAgent = currentWebView.getSettings().getUserAgentString();
1153 // Get the current font size from the
1154 fontSize = currentWebView.getSettings().getTextZoom();
1156 // Set the status of the menu item checkboxes.
1157 domStorageMenuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1158 saveFormDataMenuItem.setChecked(currentWebView.getSettings().getSaveFormData()); // Form data can be removed once the minimum API >= 26.
1159 easyListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST));
1160 easyPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY));
1161 fanboysAnnoyanceListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1162 fanboysSocialBlockingListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1163 ultraPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY));
1164 blockAllThirdPartyRequestsMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1165 swipeToRefreshMenuItem.setChecked(currentWebView.getSwipeToRefresh());
1166 displayImagesMenuItem.setChecked(currentWebView.getSettings().getLoadsImagesAutomatically());
1167 nightModeMenuItem.setChecked(currentWebView.getNightMode());
1169 // Initialize the display names for the blocklists with the number of blocked requests.
1170 blocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
1171 easyListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASY_LIST) + " - " + getString(R.string.easylist));
1172 easyPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASY_PRIVACY) + " - " + getString(R.string.easyprivacy));
1173 fanboysAnnoyanceListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " + getString(R.string.fanboys_annoyance_list));
1174 fanboysSocialBlockingListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " + getString(R.string.fanboys_social_blocking_list));
1175 ultraPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRA_PRIVACY) + " - " + getString(R.string.ultraprivacy));
1176 blockAllThirdPartyRequestsMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " + getString(R.string.block_all_third_party_requests));
1178 // Only modify third-party cookies if the API >= 21.
1179 if (Build.VERSION.SDK_INT >= 21) {
1180 // Set the status of the third-party cookies checkbox.
1181 thirdPartyCookiesMenuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
1183 // Enable third-party cookies if first-party cookies are enabled.
1184 thirdPartyCookiesMenuItem.setEnabled(cookieManager.acceptCookie());
1187 // Enable DOM Storage if JavaScript is enabled.
1188 domStorageMenuItem.setEnabled(currentWebView.getSettings().getJavaScriptEnabled());
1191 // Set the status of the menu item checkboxes.
1192 firstPartyCookiesMenuItem.setChecked(cookieManager.acceptCookie());
1193 proxyThroughOrbotMenuItem.setChecked(proxyThroughOrbot);
1195 // Enable Clear Cookies if there are any.
1196 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1198 // 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`.
1199 String privateDataDirectoryString = getApplicationInfo().dataDir;
1201 // Get a count of the number of files in the Local Storage directory.
1202 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1203 int localStorageDirectoryNumberOfFiles = 0;
1204 if (localStorageDirectory.exists()) {
1205 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1208 // Get a count of the number of files in the IndexedDB directory.
1209 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1210 int indexedDBDirectoryNumberOfFiles = 0;
1211 if (indexedDBDirectory.exists()) {
1212 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1215 // Enable Clear DOM Storage if there is any.
1216 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1218 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
1219 if (Build.VERSION.SDK_INT < 26) {
1220 // Get the WebView database.
1221 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1223 // Enable the clear form data menu item if there is anything to clear.
1224 clearFormDataMenuItem.setEnabled(webViewDatabase.hasFormData());
1227 // Enable Clear Data if any of the submenu items are enabled.
1228 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
1230 // Disable Fanboy's Social Blocking List menu item if Fanboy's Annoyance List is checked.
1231 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListMenuItem.isChecked());
1233 // Select the current user agent menu item. A switch statement cannot be used because the user agents are not compile time constants.
1234 if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) { // Privacy Browser.
1235 menu.findItem(R.id.user_agent_privacy_browser).setChecked(true);
1236 } else if (currentUserAgent.equals(webViewDefaultUserAgent)) { // WebView Default.
1237 menu.findItem(R.id.user_agent_webview_default).setChecked(true);
1238 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) { // Firefox on Android.
1239 menu.findItem(R.id.user_agent_firefox_on_android).setChecked(true);
1240 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) { // Chrome on Android.
1241 menu.findItem(R.id.user_agent_chrome_on_android).setChecked(true);
1242 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) { // Safari on iOS.
1243 menu.findItem(R.id.user_agent_safari_on_ios).setChecked(true);
1244 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) { // Firefox on Linux.
1245 menu.findItem(R.id.user_agent_firefox_on_linux).setChecked(true);
1246 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) { // Chromium on Linux.
1247 menu.findItem(R.id.user_agent_chromium_on_linux).setChecked(true);
1248 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) { // Firefox on Windows.
1249 menu.findItem(R.id.user_agent_firefox_on_windows).setChecked(true);
1250 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) { // Chrome on Windows.
1251 menu.findItem(R.id.user_agent_chrome_on_windows).setChecked(true);
1252 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) { // Edge on Windows.
1253 menu.findItem(R.id.user_agent_edge_on_windows).setChecked(true);
1254 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) { // Internet Explorer on Windows.
1255 menu.findItem(R.id.user_agent_internet_explorer_on_windows).setChecked(true);
1256 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) { // Safari on macOS.
1257 menu.findItem(R.id.user_agent_safari_on_macos).setChecked(true);
1258 } else { // Custom user agent.
1259 menu.findItem(R.id.user_agent_custom).setChecked(true);
1262 // Instantiate the font size title and the selected font size menu item.
1263 String fontSizeTitle;
1264 MenuItem selectedFontSizeMenuItem;
1266 // Prepare the font size title and current size menu item.
1269 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
1270 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1274 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
1275 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1279 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
1280 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1284 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1285 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1289 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
1290 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1294 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
1295 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1299 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
1300 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1304 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
1305 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1309 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1310 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1314 // Set the font size title and select the current size menu item.
1315 fontSizeMenuItem.setTitle(fontSizeTitle);
1316 selectedFontSizeMenuItem.setChecked(true);
1318 // Run all the other default commands.
1319 super.onPrepareOptionsMenu(menu);
1321 // Display the menu.
1326 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1327 @SuppressLint("SetJavaScriptEnabled")
1328 public boolean onOptionsItemSelected(MenuItem menuItem) {
1329 // Reenter full screen browsing mode if it was interrupted by the options menu. <https://redmine.stoutner.com/issues/389>
1330 if (inFullScreenBrowsingMode) {
1331 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
1332 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1334 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
1336 /* Hide the system bars.
1337 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1338 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
1339 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1340 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1342 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
1343 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1346 // Get the selected menu item ID.
1347 int menuItemId = menuItem.getItemId();
1349 // Get a handle for the shared preferences.
1350 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1352 // Get a handle for the cookie manager.
1353 CookieManager cookieManager = CookieManager.getInstance();
1355 // Run the commands that correlate to the selected menu item.
1356 switch (menuItemId) {
1357 case R.id.toggle_javascript:
1358 // Toggle the JavaScript status.
1359 currentWebView.getSettings().setJavaScriptEnabled(!currentWebView.getSettings().getJavaScriptEnabled());
1361 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1362 updatePrivacyIcons(true);
1364 // Display a `Snackbar`.
1365 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScrip is enabled.
1366 Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1367 } else if (cookieManager.acceptCookie()) { // JavaScript is disabled, but first-party cookies are enabled.
1368 Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1369 } else { // Privacy mode.
1370 Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1373 // Reload the current WebView.
1374 currentWebView.reload();
1377 case R.id.add_or_edit_domain:
1378 if (currentWebView.getDomainSettingsApplied()) { // Edit the current domain settings.
1379 // Reapply the domain settings on returning to `MainWebViewActivity`.
1380 reapplyDomainSettingsOnRestart = true;
1382 // TODO. Move these to `putExtra`. The certificate can be stored as strings.
1383 // Store the current SSL certificate and IP addresses in the domains activity.
1384 DomainsActivity.currentSslCertificate = currentWebView.getCertificate();
1385 DomainsActivity.currentIpAddresses = currentWebView.getCurrentIpAddresses();
1387 // Create an intent to launch the domains activity.
1388 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1390 // Add the extra information to the intent.
1391 domainsIntent.putExtra("load_domain", currentWebView.getDomainSettingsDatabaseId());
1392 domainsIntent.putExtra("close_on_back", true);
1393 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1396 startActivity(domainsIntent);
1397 } else { // Add a new domain.
1398 // Apply the new domain settings on returning to `MainWebViewActivity`.
1399 reapplyDomainSettingsOnRestart = true;
1401 // Get the current domain
1402 Uri currentUri = Uri.parse(currentWebView.getUrl());
1403 String currentDomain = currentUri.getHost();
1405 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1406 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1408 // Create the domain and store the database ID.
1409 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1411 // TODO. Move these to `putExtra`. The certificate can be stored as strings.
1412 // Store the current SSL certificate and IP addresses in the domains activity.
1413 DomainsActivity.currentSslCertificate = currentWebView.getCertificate();
1414 DomainsActivity.currentIpAddresses = currentWebView.getCurrentIpAddresses();
1416 // Create an intent to launch the domains activity.
1417 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1419 // Add the extra information to the intent.
1420 domainsIntent.putExtra("load_domain", newDomainDatabaseId);
1421 domainsIntent.putExtra("close_on_back", true);
1422 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1425 startActivity(domainsIntent);
1429 case R.id.toggle_first_party_cookies:
1430 // Switch the first-party cookie status.
1431 cookieManager.setAcceptCookie(!cookieManager.acceptCookie());
1433 // Store the first-party cookie status.
1434 currentWebView.setAcceptFirstPartyCookies(cookieManager.acceptCookie());
1436 // Update the menu checkbox.
1437 menuItem.setChecked(cookieManager.acceptCookie());
1439 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1440 updatePrivacyIcons(true);
1442 // Display a snackbar.
1443 if (cookieManager.acceptCookie()) { // First-party cookies are enabled.
1444 Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1445 } else if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is still enabled.
1446 Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1447 } else { // Privacy mode.
1448 Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1451 // Reload the current WebView.
1452 currentWebView.reload();
1455 case R.id.toggle_third_party_cookies:
1456 if (Build.VERSION.SDK_INT >= 21) {
1457 // Switch the status of thirdPartyCookiesEnabled.
1458 cookieManager.setAcceptThirdPartyCookies(currentWebView, !cookieManager.acceptThirdPartyCookies(currentWebView));
1460 // Update the menu checkbox.
1461 menuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
1463 // Display a snackbar.
1464 if (cookieManager.acceptThirdPartyCookies(currentWebView)) {
1465 Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1467 Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1470 // Reload the current WebView.
1471 currentWebView.reload();
1472 } // Else do nothing because SDK < 21.
1475 case R.id.toggle_dom_storage:
1476 // Toggle the status of domStorageEnabled.
1477 currentWebView.getSettings().setDomStorageEnabled(!currentWebView.getSettings().getDomStorageEnabled());
1479 // Update the menu checkbox.
1480 menuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1482 // Update the privacy icon. `true` refreshes the app bar icons.
1483 updatePrivacyIcons(true);
1485 // Display a snackbar.
1486 if (currentWebView.getSettings().getDomStorageEnabled()) {
1487 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1489 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1492 // Reload the current WebView.
1493 currentWebView.reload();
1496 // Form data can be removed once the minimum API >= 26.
1497 case R.id.toggle_save_form_data:
1498 // Switch the status of saveFormDataEnabled.
1499 currentWebView.getSettings().setSaveFormData(!currentWebView.getSettings().getSaveFormData());
1501 // Update the menu checkbox.
1502 menuItem.setChecked(currentWebView.getSettings().getSaveFormData());
1504 // Display a snackbar.
1505 if (currentWebView.getSettings().getSaveFormData()) {
1506 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1508 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1511 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1512 updatePrivacyIcons(true);
1514 // Reload the current WebView.
1515 currentWebView.reload();
1518 case R.id.clear_cookies:
1519 Snackbar.make(findViewById(R.id.webviewpager), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1520 .setAction(R.string.undo, v -> {
1521 // Do nothing because everything will be handled by `onDismissed()` below.
1523 .addCallback(new Snackbar.Callback() {
1524 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1526 public void onDismissed(Snackbar snackbar, int event) {
1527 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1528 // Delete the cookies, which command varies by SDK.
1529 if (Build.VERSION.SDK_INT < 21) {
1530 cookieManager.removeAllCookie();
1532 cookieManager.removeAllCookies(null);
1540 case R.id.clear_dom_storage:
1541 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1542 .setAction(R.string.undo, v -> {
1543 // Do nothing because everything will be handled by `onDismissed()` below.
1545 .addCallback(new Snackbar.Callback() {
1546 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1548 public void onDismissed(Snackbar snackbar, int event) {
1549 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1550 // Delete the DOM Storage.
1551 WebStorage webStorage = WebStorage.getInstance();
1552 webStorage.deleteAllData();
1554 // Initialize a handler to manually delete the DOM storage files and directories.
1555 Handler deleteDomStorageHandler = new Handler();
1557 // Setup a runnable to manually delete the DOM storage files and directories.
1558 Runnable deleteDomStorageRunnable = () -> {
1560 // Get a handle for the runtime.
1561 Runtime runtime = Runtime.getRuntime();
1563 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
1564 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
1565 String privateDataDirectoryString = getApplicationInfo().dataDir;
1567 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1568 Process deleteLocalStorageProcess = runtime.exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1570 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1571 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1572 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1573 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1574 Process deleteDatabasesProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1576 // Wait for the processes to finish.
1577 deleteLocalStorageProcess.waitFor();
1578 deleteIndexProcess.waitFor();
1579 deleteQuotaManagerProcess.waitFor();
1580 deleteQuotaManagerJournalProcess.waitFor();
1581 deleteDatabasesProcess.waitFor();
1582 } catch (Exception exception) {
1583 // Do nothing if an error is thrown.
1587 // Manually delete the DOM storage files after 200 milliseconds.
1588 deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200);
1595 // Form data can be remove once the minimum API >= 26.
1596 case R.id.clear_form_data:
1597 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1598 .setAction(R.string.undo, v -> {
1599 // Do nothing because everything will be handled by `onDismissed()` below.
1601 .addCallback(new Snackbar.Callback() {
1602 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1604 public void onDismissed(Snackbar snackbar, int event) {
1605 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1606 // Delete the form data.
1607 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1608 mainWebViewDatabase.clearFormData();
1616 // Toggle the EasyList status.
1617 currentWebView.enableBlocklist(NestedScrollWebView.EASY_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST));
1619 // Update the menu checkbox.
1620 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST));
1622 // Reload the current WebView.
1623 currentWebView.reload();
1626 case R.id.easyprivacy:
1627 // Toggle the EasyPrivacy status.
1628 currentWebView.enableBlocklist(NestedScrollWebView.EASY_PRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY));
1630 // Update the menu checkbox.
1631 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY));
1633 // Reload the current WebView.
1634 currentWebView.reload();
1637 case R.id.fanboys_annoyance_list:
1638 // Toggle Fanboy's Annoyance List status.
1639 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1641 // Update the menu checkbox.
1642 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1644 // Update the staus of Fanboy's Social Blocking List.
1645 MenuItem fanboysSocialBlockingListMenuItem = optionsMenu.findItem(R.id.fanboys_social_blocking_list);
1646 fanboysSocialBlockingListMenuItem.setEnabled(!currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1648 // Reload the current WebView.
1649 currentWebView.reload();
1652 case R.id.fanboys_social_blocking_list:
1653 // Toggle Fanboy's Social Blocking List status.
1654 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1656 // Update the menu checkbox.
1657 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1659 // Reload the current WebView.
1660 currentWebView.reload();
1663 case R.id.ultraprivacy:
1664 // Toggle the UltraPrivacy status.
1665 currentWebView.enableBlocklist(NestedScrollWebView.ULTRA_PRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY));
1667 // Update the menu checkbox.
1668 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY));
1670 // Reload the current WebView.
1671 currentWebView.reload();
1674 case R.id.block_all_third_party_requests:
1675 //Toggle the third-party requests blocker status.
1676 currentWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, !currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1678 // Update the menu checkbox.
1679 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1681 // Reload the current WebView.
1682 currentWebView.reload();
1685 case R.id.user_agent_privacy_browser:
1686 // Update the user agent.
1687 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
1689 // Reload the current WebView.
1690 currentWebView.reload();
1693 case R.id.user_agent_webview_default:
1694 // Update the user agent.
1695 currentWebView.getSettings().setUserAgentString("");
1697 // Reload the current WebView.
1698 currentWebView.reload();
1701 case R.id.user_agent_firefox_on_android:
1702 // Update the user agent.
1703 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
1705 // Reload the current WebView.
1706 currentWebView.reload();
1709 case R.id.user_agent_chrome_on_android:
1710 // Update the user agent.
1711 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
1713 // Reload the current WebView.
1714 currentWebView.reload();
1717 case R.id.user_agent_safari_on_ios:
1718 // Update the user agent.
1719 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
1721 // Reload the current WebView.
1722 currentWebView.reload();
1725 case R.id.user_agent_firefox_on_linux:
1726 // Update the user agent.
1727 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
1729 // Reload the current WebView.
1730 currentWebView.reload();
1733 case R.id.user_agent_chromium_on_linux:
1734 // Update the user agent.
1735 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
1737 // Reload the current WebView.
1738 currentWebView.reload();
1741 case R.id.user_agent_firefox_on_windows:
1742 // Update the user agent.
1743 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
1745 // Reload the current WebView.
1746 currentWebView.reload();
1749 case R.id.user_agent_chrome_on_windows:
1750 // Update the user agent.
1751 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
1753 // Reload the current WebView.
1754 currentWebView.reload();
1757 case R.id.user_agent_edge_on_windows:
1758 // Update the user agent.
1759 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
1761 // Reload the current WebView.
1762 currentWebView.reload();
1765 case R.id.user_agent_internet_explorer_on_windows:
1766 // Update the user agent.
1767 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
1769 // Reload the current WebView.
1770 currentWebView.reload();
1773 case R.id.user_agent_safari_on_macos:
1774 // Update the user agent.
1775 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
1777 // Reload the current WebView.
1778 currentWebView.reload();
1781 case R.id.user_agent_custom:
1782 // Update the user agent.
1783 currentWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
1785 // Reload the current WebView.
1786 currentWebView.reload();
1789 case R.id.font_size_twenty_five_percent:
1790 currentWebView.getSettings().setTextZoom(25);
1793 case R.id.font_size_fifty_percent:
1794 currentWebView.getSettings().setTextZoom(50);
1797 case R.id.font_size_seventy_five_percent:
1798 currentWebView.getSettings().setTextZoom(75);
1801 case R.id.font_size_one_hundred_percent:
1802 currentWebView.getSettings().setTextZoom(100);
1805 case R.id.font_size_one_hundred_twenty_five_percent:
1806 currentWebView.getSettings().setTextZoom(125);
1809 case R.id.font_size_one_hundred_fifty_percent:
1810 currentWebView.getSettings().setTextZoom(150);
1813 case R.id.font_size_one_hundred_seventy_five_percent:
1814 currentWebView.getSettings().setTextZoom(175);
1817 case R.id.font_size_two_hundred_percent:
1818 currentWebView.getSettings().setTextZoom(200);
1821 case R.id.swipe_to_refresh:
1822 // Toggle the stored status of swipe to refresh.
1823 currentWebView.setSwipeToRefresh(!currentWebView.getSwipeToRefresh());
1825 // Get a handle for the swipe refresh layout.
1826 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
1828 // Update the swipe refresh layout.
1829 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
1830 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.
1831 // Only enable the swipe refresh layout if the WebView is scrolled to the top.
1832 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
1833 } else { // For API < 23, the swipe refresh layout is always enabled.
1834 // Enable the swipe refresh layout.
1835 swipeRefreshLayout.setEnabled(true);
1837 } else { // Swipe to refresh is disabled.
1838 // Disable the swipe refresh layout.
1839 swipeRefreshLayout.setEnabled(false);
1843 case R.id.display_images:
1844 if (currentWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1845 // Disable loading of images.
1846 currentWebView.getSettings().setLoadsImagesAutomatically(false);
1848 // Reload the website to remove existing images.
1849 currentWebView.reload();
1850 } else { // Images are not currently loaded automatically.
1851 // Enable loading of images. Missing images will be loaded without the need for a reload.
1852 currentWebView.getSettings().setLoadsImagesAutomatically(true);
1856 case R.id.night_mode:
1857 // Toggle night mode.
1858 currentWebView.setNightMode(!currentWebView.getNightMode());
1860 // Enable or disable JavaScript according to night mode, the global preference, and any domain settings.
1861 if (currentWebView.getNightMode()) { // Night mode is enabled, which requires JavaScript.
1862 // Enable JavaScript.
1863 currentWebView.getSettings().setJavaScriptEnabled(true);
1864 } else if (currentWebView.getDomainSettingsApplied()) { // Night mode is disabled and domain settings are applied. Set JavaScript according to the domain settings.
1865 // Apply the JavaScript preference that was stored the last time domain settings were loaded.
1866 currentWebView.getSettings().setJavaScriptEnabled(currentWebView.getDomainSettingsJavaScriptEnabled());
1867 } else { // Night mode is disabled and domain settings are not applied. Set JavaScript according to the global preference.
1868 // Apply the JavaScript preference.
1869 currentWebView.getSettings().setJavaScriptEnabled(sharedPreferences.getBoolean("javascript", false));
1872 // Update the privacy icons.
1873 updatePrivacyIcons(false);
1875 // Reload the website.
1876 currentWebView.reload();
1879 case R.id.find_on_page:
1880 // Get a handle for the views.
1881 Toolbar toolbar = findViewById(R.id.toolbar);
1882 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
1883 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
1885 // Hide the toolbar.
1886 toolbar.setVisibility(View.GONE);
1888 // Show the find on page linear layout.
1889 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1891 // Display the keyboard. The app must wait 200 ms before running the command to work around a bug in Android.
1892 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1893 findOnPageEditText.postDelayed(() -> {
1894 // Set the focus on `findOnPageEditText`.
1895 findOnPageEditText.requestFocus();
1897 // Get a handle for the input method manager.
1898 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1900 // Remove the lint warning below that the input method manager might be null.
1901 assert inputMethodManager != null;
1903 // Display the keyboard. `0` sets no input flags.
1904 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1908 case R.id.view_source:
1909 // Create an intent to launch the view source activity.
1910 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
1912 // Add the variables to the intent.
1913 viewSourceIntent.putExtra("user_agent", currentWebView.getSettings().getUserAgentString());
1914 viewSourceIntent.putExtra("current_url", currentWebView.getUrl());
1917 startActivity(viewSourceIntent);
1920 case R.id.share_url:
1921 // Setup the share string.
1922 String shareString = currentWebView.getTitle() + " – " + currentWebView.getUrl();
1924 // Create the share intent.
1925 Intent shareIntent = new Intent(Intent.ACTION_SEND);
1926 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1927 shareIntent.setType("text/plain");
1930 startActivity(Intent.createChooser(shareIntent, getString(R.string.share_url)));
1934 // Get a print manager instance.
1935 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1937 // Remove the lint error below that print manager might be null.
1938 assert printManager != null;
1940 // Create a print document adapter from the current WebView.
1941 PrintDocumentAdapter printDocumentAdapter = currentWebView.createPrintDocumentAdapter();
1943 // Print the document.
1944 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1947 case R.id.open_with_app:
1948 openWithApp(currentWebView.getUrl());
1951 case R.id.open_with_browser:
1952 openWithBrowser(currentWebView.getUrl());
1955 case R.id.add_to_homescreen:
1956 // Instantiate the create home screen shortcut dialog.
1957 DialogFragment createHomeScreenShortcutDialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView.getTitle(), currentWebView.getUrl(),
1958 currentWebView.getFavoriteOrDefaultIcon());
1960 // Show the create home screen shortcut dialog.
1961 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
1964 case R.id.proxy_through_orbot:
1965 // Toggle the proxy through Orbot variable.
1966 proxyThroughOrbot = !proxyThroughOrbot;
1968 // Apply the proxy through Orbot settings.
1969 applyProxyThroughOrbot(true);
1973 if (menuItem.getTitle().equals(getString(R.string.refresh))) { // The refresh button was pushed.
1974 // Reload the current WebView.
1975 currentWebView.reload();
1976 } else { // The stop button was pushed.
1977 // Stop the loading of the WebView.
1978 currentWebView.stopLoading();
1982 case R.id.ad_consent:
1983 // Display the ad consent dialog.
1984 DialogFragment adConsentDialogFragment = new AdConsentDialog();
1985 adConsentDialogFragment.show(getSupportFragmentManager(), getString(R.string.ad_consent));
1989 // Don't consume the event.
1990 return super.onOptionsItemSelected(menuItem);
1994 // removeAllCookies is deprecated, but it is required for API < 21.
1996 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1997 // Get the menu item ID.
1998 int menuItemId = menuItem.getItemId();
2000 // Get a handle for the shared preferences.
2001 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2003 // Run the commands that correspond to the selected menu item.
2004 switch (menuItemId) {
2005 case R.id.close_tab:
2006 // Get a handle for the tab layout and the view pager.
2007 TabLayout tabLayout = findViewById(R.id.tablayout);
2008 ViewPager webViewPager = findViewById(R.id.webviewpager);
2010 // Get the current tab number.
2011 int currentTabNumber = tabLayout.getSelectedTabPosition();
2013 // Delete the current tab.
2014 tabLayout.removeTabAt(currentTabNumber);
2016 // 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.
2017 if (webViewPagerAdapter.deletePage(currentTabNumber, webViewPager)) {
2018 setCurrentWebView(currentTabNumber);
2022 case R.id.clear_and_exit:
2023 // Close the bookmarks cursor and database.
2024 bookmarksCursor.close();
2025 bookmarksDatabaseHelper.close();
2027 // Get the status of the clear everything preference.
2028 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2030 // Get a handle for the runtime.
2031 Runtime runtime = Runtime.getRuntime();
2033 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
2034 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
2035 String privateDataDirectoryString = getApplicationInfo().dataDir;
2038 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2039 // The command to remove cookies changed slightly in API 21.
2040 if (Build.VERSION.SDK_INT >= 21) {
2041 CookieManager.getInstance().removeAllCookies(null);
2043 CookieManager.getInstance().removeAllCookie();
2046 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2048 // Two commands must be used because `Runtime.exec()` does not like `*`.
2049 Process deleteCookiesProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2050 Process deleteCookiesJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2052 // Wait until the processes have finished.
2053 deleteCookiesProcess.waitFor();
2054 deleteCookiesJournalProcess.waitFor();
2055 } catch (Exception exception) {
2056 // Do nothing if an error is thrown.
2060 // Clear DOM storage.
2061 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2062 // Ask `WebStorage` to clear the DOM storage.
2063 WebStorage webStorage = WebStorage.getInstance();
2064 webStorage.deleteAllData();
2066 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2068 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2069 Process deleteLocalStorageProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2071 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2072 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2073 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2074 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2075 Process deleteDatabaseProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2077 // Wait until the processes have finished.
2078 deleteLocalStorageProcess.waitFor();
2079 deleteIndexProcess.waitFor();
2080 deleteQuotaManagerProcess.waitFor();
2081 deleteQuotaManagerJournalProcess.waitFor();
2082 deleteDatabaseProcess.waitFor();
2083 } catch (Exception exception) {
2084 // Do nothing if an error is thrown.
2088 // Clear form data if the API < 26.
2089 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
2090 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
2091 webViewDatabase.clearFormData();
2093 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2095 // A string array must be used because the database contains a space and `Runtime.exec` will not otherwise escape the string correctly.
2096 Process deleteWebDataProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
2097 Process deleteWebDataJournalProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
2099 // Wait until the processes have finished.
2100 deleteWebDataProcess.waitFor();
2101 deleteWebDataJournalProcess.waitFor();
2102 } catch (Exception exception) {
2103 // Do nothing if an error is thrown.
2108 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2109 // Clear the cache from each WebView.
2110 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
2111 // Get the WebView tab fragment.
2112 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
2114 // Get the fragment view.
2115 View fragmentView = webViewTabFragment.getView();
2117 // Only clear the cache if the WebView exists.
2118 if (fragmentView != null) {
2119 // Get the nested scroll WebView from the tab fragment.
2120 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
2122 // Clear the cache for this WebView.
2123 nestedScrollWebView.clearCache(true);
2127 // Manually delete the cache directories.
2129 // Delete the main cache directory.
2130 Process deleteCacheProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2132 // Delete the secondary `Service Worker` cache directory.
2133 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2134 Process deleteServiceWorkerProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2136 // Wait until the processes have finished.
2137 deleteCacheProcess.waitFor();
2138 deleteServiceWorkerProcess.waitFor();
2139 } catch (Exception exception) {
2140 // Do nothing if an error is thrown.
2144 // Wipe out each WebView.
2145 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
2146 // Get the WebView tab fragment.
2147 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
2149 // Get the fragment view.
2150 View fragmentView = webViewTabFragment.getView();
2152 // Only wipe out the WebView if it exists.
2153 if (fragmentView != null) {
2154 // Get the nested scroll WebView from the tab fragment.
2155 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
2157 // Clear SSL certificate preferences for this WebView.
2158 nestedScrollWebView.clearSslPreferences();
2160 // Clear the back/forward history for this WebView.
2161 nestedScrollWebView.clearHistory();
2163 // Destroy the internal state of `mainWebView`.
2164 nestedScrollWebView.destroy();
2168 // Clear the custom headers.
2169 customHeaders.clear();
2171 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
2172 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
2173 if (clearEverything) {
2175 // Delete the folder.
2176 Process deleteAppWebviewProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
2178 // Wait until the process has finished.
2179 deleteAppWebviewProcess.waitFor();
2180 } catch (Exception exception) {
2181 // Do nothing if an error is thrown.
2185 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
2186 if (Build.VERSION.SDK_INT >= 21) {
2187 finishAndRemoveTask();
2192 // Remove the terminated program from RAM. The status code is `0`.
2197 // Select the homepage based on the proxy through Orbot status.
2198 if (proxyThroughOrbot) {
2199 // Load the Tor homepage.
2200 loadUrl(sharedPreferences.getString("tor_homepage", getString(R.string.tor_homepage_default_value)));
2202 // Load the normal homepage.
2203 loadUrl(sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
2208 if (currentWebView.canGoBack()) {
2209 // Reset the current domain name so that navigation works if third-party requests are blocked.
2210 currentWebView.resetCurrentDomainName();
2212 // Set navigating history so that the domain settings are applied when the new URL is loaded.
2213 currentWebView.setNavigatingHistory(true);
2215 // Load the previous website in the history.
2216 currentWebView.goBack();
2221 if (currentWebView.canGoForward()) {
2222 // Reset the current domain name so that navigation works if third-party requests are blocked.
2223 currentWebView.resetCurrentDomainName();
2225 // Set navigating history so that the domain settings are applied when the new URL is loaded.
2226 currentWebView.setNavigatingHistory(true);
2228 // Load the next website in the history.
2229 currentWebView.goForward();
2234 // Get the `WebBackForwardList`.
2235 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
2237 // Show the URL history dialog and name this instance `R.string.history`.
2238 DialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
2239 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2243 // Populate the resource requests.
2244 RequestsActivity.resourceRequests = currentWebView.getResourceRequests();
2246 // Create an intent to launch the Requests activity.
2247 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2249 // Add the block third-party requests status to the intent.
2250 requestsIntent.putExtra("block_all_third_party_requests", currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
2253 startActivity(requestsIntent);
2256 case R.id.downloads:
2257 // Launch the system Download Manager.
2258 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2260 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2261 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2263 startActivity(downloadManagerIntent);
2267 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2268 reapplyDomainSettingsOnRestart = true;
2270 // TODO. Move these to `putExtra`. The certificate can be stored as strings.
2271 // Store the current SSL certificate and IP addresses in the domains activity.
2272 DomainsActivity.currentSslCertificate = currentWebView.getCertificate();
2273 DomainsActivity.currentIpAddresses = currentWebView.getCurrentIpAddresses();
2275 // Launch the domains activity.
2276 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2278 // Add the extra information to the intent.
2279 domainsIntent.putExtra("current_url", currentWebView.getUrl());
2282 startActivity(domainsIntent);
2286 // Set the flag to reapply app settings on restart when returning from Settings.
2287 reapplyAppSettingsOnRestart = true;
2289 // Set the flag to reapply the domain settings on restart when returning from Settings.
2290 reapplyDomainSettingsOnRestart = true;
2292 // Launch the settings activity.
2293 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2294 startActivity(settingsIntent);
2297 case R.id.import_export:
2298 // Launch the import/export activity.
2299 Intent importExportIntent = new Intent (this, ImportExportActivity.class);
2300 startActivity(importExportIntent);
2304 // Launch the logcat activity.
2305 Intent logcatIntent = new Intent(this, LogcatActivity.class);
2306 startActivity(logcatIntent);
2310 // Launch `GuideActivity`.
2311 Intent guideIntent = new Intent(this, GuideActivity.class);
2312 startActivity(guideIntent);
2316 // Create an intent to launch the about activity.
2317 Intent aboutIntent = new Intent(this, AboutActivity.class);
2319 // Create a string array for the blocklist versions.
2320 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],
2321 ultraPrivacy.get(0).get(0)[0]};
2323 // Add the blocklist versions to the intent.
2324 aboutIntent.putExtra("blocklist_versions", blocklistVersions);
2327 startActivity(aboutIntent);
2331 // Get a handle for the drawer layout.
2332 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
2334 // Close the navigation drawer.
2335 drawerLayout.closeDrawer(GravityCompat.START);
2340 public void onPostCreate(Bundle savedInstanceState) {
2341 // Run the default commands.
2342 super.onPostCreate(savedInstanceState);
2344 // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished. This creates the navigation drawer icon.
2345 actionBarDrawerToggle.syncState();
2349 public void onConfigurationChanged(Configuration newConfig) {
2350 // Run the default commands.
2351 super.onConfigurationChanged(newConfig);
2353 // Get the status bar pixel size.
2354 int statusBarResourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
2355 int statusBarPixelSize = getResources().getDimensionPixelSize(statusBarResourceId);
2357 // Get the resource density.
2358 float screenDensity = getResources().getDisplayMetrics().density;
2360 // Recalculate the drawer header padding.
2361 drawerHeaderPaddingLeftAndRight = (int) (15 * screenDensity);
2362 drawerHeaderPaddingTop = statusBarPixelSize + (int) (4 * screenDensity);
2363 drawerHeaderPaddingBottom = (int) (8 * screenDensity);
2365 // Reload the ad for the free flavor if not in full screen mode.
2366 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2367 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2368 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
2371 // `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:
2372 // https://code.google.com/p/android/issues/detail?id=20493#c8
2373 // ActivityCompat.invalidateOptionsMenu(this);
2377 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2378 // Store the hit test result.
2379 final WebView.HitTestResult hitTestResult = currentWebView.getHitTestResult();
2381 // Create the URL strings.
2382 final String imageUrl;
2383 final String linkUrl;
2385 // Get handles for the system managers.
2386 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2387 FragmentManager fragmentManager = getSupportFragmentManager();
2388 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2390 // Remove the lint errors below that the clipboard manager might be null.
2391 assert clipboardManager != null;
2393 // Process the link according to the type.
2394 switch (hitTestResult.getType()) {
2395 // `SRC_ANCHOR_TYPE` is a link.
2396 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2397 // Get the target URL.
2398 linkUrl = hitTestResult.getExtra();
2400 // Set the target URL as the title of the `ContextMenu`.
2401 menu.setHeaderTitle(linkUrl);
2403 // Add a Load URL entry.
2404 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2413 // Add an Open with App entry.
2414 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2415 openWithApp(linkUrl);
2419 // Add an Open with Browser entry.
2420 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2421 openWithBrowser(linkUrl);
2425 // Add a Copy URL entry.
2426 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2427 // Save the link URL in a `ClipData`.
2428 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2430 // Set the `ClipData` as the clipboard's primary clip.
2431 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2435 // Add a Download URL entry.
2436 menu.add(R.string.download_url).setOnMenuItemClickListener((MenuItem item) -> {
2437 // Check if the download should be processed by an external app.
2438 if (sharedPreferences.getBoolean("download_with_external_app", false)) { // Download with an external app.
2439 openUrlWithExternalApp(linkUrl);
2440 } else { // Download with Android's download manager.
2441 // Check to see if the storage permission has already been granted.
2442 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission needs to be requested.
2443 // Store the variables for future use by `onRequestPermissionsResult()`.
2444 downloadUrl = linkUrl;
2445 downloadContentDisposition = "none";
2446 downloadContentLength = -1;
2448 // Show a dialog if the user has previously denied the permission.
2449 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2450 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
2451 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
2453 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
2454 downloadLocationPermissionDialogFragment.show(fragmentManager, getString(R.string.download_location));
2455 } else { // Show the permission request directly.
2456 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
2457 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2459 } else { // The storage permission has already been granted.
2460 // Get a handle for the download file alert dialog.
2461 DialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(linkUrl, "none", -1);
2463 // Show the download file alert dialog.
2464 downloadFileDialogFragment.show(fragmentManager, getString(R.string.download));
2470 // Add a Cancel entry, which by default closes the context menu.
2471 menu.add(R.string.cancel);
2474 case WebView.HitTestResult.EMAIL_TYPE:
2475 // Get the target URL.
2476 linkUrl = hitTestResult.getExtra();
2478 // Set the target URL as the title of the `ContextMenu`.
2479 menu.setHeaderTitle(linkUrl);
2481 // Add a Write Email entry.
2482 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2483 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2484 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2486 // Parse the url and set it as the data for the `Intent`.
2487 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2489 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2490 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2493 startActivity(emailIntent);
2497 // Add a Copy Email Address entry.
2498 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2499 // Save the email address in a `ClipData`.
2500 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2502 // Set the `ClipData` as the clipboard's primary clip.
2503 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2507 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2508 menu.add(R.string.cancel);
2511 // `IMAGE_TYPE` is an image.
2512 case WebView.HitTestResult.IMAGE_TYPE:
2513 // Get the image URL.
2514 imageUrl = hitTestResult.getExtra();
2516 // Set the image URL as the title of the `ContextMenu`.
2517 menu.setHeaderTitle(imageUrl);
2519 // Add a View Image entry.
2520 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2525 // Add a Download Image entry.
2526 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2527 // Check if the download should be processed by an external app.
2528 if (sharedPreferences.getBoolean("download_with_external_app", false)) { // Download with an external app.
2529 openUrlWithExternalApp(imageUrl);
2530 } else { // Download with Android's download manager.
2531 // Check to see if the storage permission has already been granted.
2532 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission needs to be requested.
2533 // Store the image URL for use by `onRequestPermissionResult()`.
2534 downloadImageUrl = imageUrl;
2536 // Show a dialog if the user has previously denied the permission.
2537 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2538 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2539 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2541 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
2542 downloadLocationPermissionDialogFragment.show(fragmentManager, getString(R.string.download_location));
2543 } else { // Show the permission request directly.
2544 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
2545 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2547 } else { // The storage permission has already been granted.
2548 // Get a handle for the download image alert dialog.
2549 DialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2551 // Show the download image alert dialog.
2552 downloadImageDialogFragment.show(fragmentManager, getString(R.string.download));
2558 // Add a Copy URL entry.
2559 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2560 // Save the image URL in a `ClipData`.
2561 ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2563 // Set the `ClipData` as the clipboard's primary clip.
2564 clipboardManager.setPrimaryClip(srcImageTypeClipData);
2568 // Add an Open with App entry.
2569 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2570 openWithApp(imageUrl);
2574 // Add an Open with Browser entry.
2575 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2576 openWithBrowser(imageUrl);
2580 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2581 menu.add(R.string.cancel);
2585 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2586 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2587 // Get the image URL.
2588 imageUrl = hitTestResult.getExtra();
2590 // Set the image URL as the title of the `ContextMenu`.
2591 menu.setHeaderTitle(imageUrl);
2593 // Add a `View Image` entry.
2594 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2599 // Add a `Download Image` entry.
2600 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2601 // Check if the download should be processed by an external app.
2602 if (sharedPreferences.getBoolean("download_with_external_app", false)) { // Download with an external app.
2603 openUrlWithExternalApp(imageUrl);
2604 } else { // Download with Android's download manager.
2605 // Check to see if the storage permission has already been granted.
2606 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission needs to be requested.
2607 // Store the image URL for use by `onRequestPermissionResult()`.
2608 downloadImageUrl = imageUrl;
2610 // Show a dialog if the user has previously denied the permission.
2611 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2612 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2613 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2615 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
2616 downloadLocationPermissionDialogFragment.show(fragmentManager, getString(R.string.download_location));
2617 } else { // Show the permission request directly.
2618 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
2619 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2621 } else { // The storage permission has already been granted.
2622 // Get a handle for the download image alert dialog.
2623 DialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2625 // Show the download image alert dialog.
2626 downloadImageDialogFragment.show(fragmentManager, getString(R.string.download));
2632 // Add a `Copy URL` entry.
2633 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2634 // Save the image URL in a `ClipData`.
2635 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2637 // Set the `ClipData` as the clipboard's primary clip.
2638 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2642 // Add an Open with App entry.
2643 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2644 openWithApp(imageUrl);
2648 // Add an Open with Browser entry.
2649 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2650 openWithBrowser(imageUrl);
2654 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2655 menu.add(R.string.cancel);
2661 public void onCreateBookmark(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2662 // Get a handle for the bookmarks list view.
2663 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2665 // Get the views from the dialog fragment.
2666 EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
2667 EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
2669 // Extract the strings from the edit texts.
2670 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2671 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2673 // Create a favorite icon byte array output stream.
2674 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2676 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2677 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2679 // Convert the favorite icon byte array stream to a byte array.
2680 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2682 // Display the new bookmark below the current items in the (0 indexed) list.
2683 int newBookmarkDisplayOrder = bookmarksListView.getCount();
2685 // Create the bookmark.
2686 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2688 // Update the bookmarks cursor with the current contents of this folder.
2689 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2691 // Update the list view.
2692 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2694 // Scroll to the new bookmark.
2695 bookmarksListView.setSelection(newBookmarkDisplayOrder);
2699 public void onCreateBookmarkFolder(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2700 // Get a handle for the bookmarks list view.
2701 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2703 // Get handles for the views in the dialog fragment.
2704 EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
2705 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
2706 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
2708 // Get new folder name string.
2709 String folderNameString = createFolderNameEditText.getText().toString();
2711 // Create a folder icon bitmap.
2712 Bitmap folderIconBitmap;
2714 // Set the folder icon bitmap according to the dialog.
2715 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
2716 // Get the default folder icon drawable.
2717 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2719 // Convert the folder icon drawable to a bitmap drawable.
2720 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2722 // Convert the folder icon bitmap drawable to a bitmap.
2723 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2724 } else { // Use the WebView favorite icon.
2725 // Copy the favorite icon bitmap to the folder icon bitmap.
2726 folderIconBitmap = favoriteIconBitmap;
2729 // Create a folder icon byte array output stream.
2730 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2732 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2733 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2735 // Convert the folder icon byte array stream to a byte array.
2736 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2738 // Move all the bookmarks down one in the display order.
2739 for (int i = 0; i < bookmarksListView.getCount(); i++) {
2740 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2741 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2744 // Create the folder, which will be placed at the top of the `ListView`.
2745 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2747 // Update the bookmarks cursor with the current contents of this folder.
2748 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2750 // Update the `ListView`.
2751 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2753 // Scroll to the new folder.
2754 bookmarksListView.setSelection(0);
2758 public void onSaveBookmark(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, Bitmap favoriteIconBitmap) {
2759 // Get handles for the views from `dialogFragment`.
2760 EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
2761 EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
2762 RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
2764 // Store the bookmark strings.
2765 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
2766 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
2768 // Update the bookmark.
2769 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
2770 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
2771 } else { // Update the bookmark using the `WebView` favorite icon.
2772 // Create a favorite icon byte array output stream.
2773 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2775 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2776 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
2778 // Convert the favorite icon byte array stream to a byte array.
2779 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
2781 // Update the bookmark and the favorite icon.
2782 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
2785 // Update the bookmarks cursor with the current contents of this folder.
2786 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2788 // Update the list view.
2789 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2793 public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId, Bitmap favoriteIconBitmap) {
2794 // Get handles for the views from `dialogFragment`.
2795 EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
2796 RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
2797 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
2798 ImageView defaultFolderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
2800 // Get the new folder name.
2801 String newFolderNameString = editFolderNameEditText.getText().toString();
2803 // Check if the favorite icon has changed.
2804 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
2805 // Update the name in the database.
2806 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2807 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
2808 // Create the new folder icon Bitmap.
2809 Bitmap folderIconBitmap;
2811 // Populate the new folder icon bitmap.
2812 if (defaultFolderIconRadioButton.isChecked()) {
2813 // Get the default folder icon drawable.
2814 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2816 // Convert the folder icon drawable to a bitmap drawable.
2817 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2819 // Convert the folder icon bitmap drawable to a bitmap.
2820 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2821 } else { // Use the `WebView` favorite icon.
2822 // Copy the favorite icon bitmap to the folder icon bitmap.
2823 folderIconBitmap = favoriteIconBitmap;
2826 // Create a folder icon byte array output stream.
2827 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2829 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2830 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2832 // Convert the folder icon byte array stream to a byte array.
2833 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2835 // Update the folder icon in the database.
2836 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, newFolderIconByteArray);
2837 } else { // The folder icon and the name have changed.
2838 // Get the new folder icon `Bitmap`.
2839 Bitmap folderIconBitmap;
2840 if (defaultFolderIconRadioButton.isChecked()) {
2841 // Get the default folder icon drawable.
2842 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2844 // Convert the folder icon drawable to a bitmap drawable.
2845 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2847 // Convert the folder icon bitmap drawable to a bitmap.
2848 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2849 } else { // Use the `WebView` favorite icon.
2850 // Copy the favorite icon bitmap to the folder icon bitmap.
2851 folderIconBitmap = favoriteIconBitmap;
2854 // Create a folder icon byte array output stream.
2855 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2857 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2858 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2860 // Convert the folder icon byte array stream to a byte array.
2861 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2863 // Update the folder name and icon in the database.
2864 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, newFolderIconByteArray);
2867 // Update the bookmarks cursor with the current contents of this folder.
2868 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2870 // Update the `ListView`.
2871 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2875 public void onCloseDownloadLocationPermissionDialog(int downloadType) {
2876 switch (downloadType) {
2877 case DownloadLocationPermissionDialog.DOWNLOAD_FILE:
2878 // Request the WRITE_EXTERNAL_STORAGE permission with a file request code.
2879 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2882 case DownloadLocationPermissionDialog.DOWNLOAD_IMAGE:
2883 // Request the WRITE_EXTERNAL_STORAGE permission with an image request code.
2884 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2890 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
2891 // Get a handle for the fragment manager.
2892 FragmentManager fragmentManager = getSupportFragmentManager();
2894 switch (requestCode) {
2895 case DOWNLOAD_FILE_REQUEST_CODE:
2896 // Show the download file alert dialog. When the dialog closes, the correct command will be used based on the permission status.
2897 DialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(downloadUrl, downloadContentDisposition, downloadContentLength);
2899 // On API 23, displaying the fragment must be delayed or the app will crash.
2900 if (Build.VERSION.SDK_INT == 23) {
2901 new Handler().postDelayed(() -> downloadFileDialogFragment.show(fragmentManager, getString(R.string.download)), 500);
2903 downloadFileDialogFragment.show(fragmentManager, getString(R.string.download));
2906 // Reset the download variables.
2908 downloadContentDisposition = "";
2909 downloadContentLength = 0;
2912 case DOWNLOAD_IMAGE_REQUEST_CODE:
2913 // Show the download image alert dialog. When the dialog closes, the correct command will be used based on the permission status.
2914 DialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(downloadImageUrl);
2916 // On API 23, displaying the fragment must be delayed or the app will crash.
2917 if (Build.VERSION.SDK_INT == 23) {
2918 new Handler().postDelayed(() -> downloadImageDialogFragment.show(fragmentManager, getString(R.string.download)), 500);
2920 downloadImageDialogFragment.show(fragmentManager, getString(R.string.download));
2923 // Reset the image URL variable.
2924 downloadImageUrl = "";
2930 public void onDownloadImage(DialogFragment dialogFragment, String imageUrl) {
2931 // Download the image if it has an HTTP or HTTPS URI.
2932 if (imageUrl.startsWith("http")) {
2933 // Get a handle for the system `DOWNLOAD_SERVICE`.
2934 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2936 // Parse `imageUrl`.
2937 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
2939 // Get a handle for the cookie manager.
2940 CookieManager cookieManager = CookieManager.getInstance();
2942 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
2943 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2944 if (cookieManager.acceptCookie()) {
2945 // Get the cookies for `imageUrl`.
2946 String cookies = cookieManager.getCookie(imageUrl);
2948 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2949 downloadRequest.addRequestHeader("Cookie", cookies);
2952 // Get the file name from the dialog fragment.
2953 EditText downloadImageNameEditText = dialogFragment.getDialog().findViewById(R.id.download_image_name);
2954 String imageName = downloadImageNameEditText.getText().toString();
2956 // Specify the download location.
2957 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
2958 // Download to the public download directory.
2959 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, imageName);
2960 } else { // External write permission denied.
2961 // Download to the app's external download directory.
2962 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, imageName);
2965 // Allow `MediaScanner` to index the download if it is a media file.
2966 downloadRequest.allowScanningByMediaScanner();
2968 // Add the URL as the description for the download.
2969 downloadRequest.setDescription(imageUrl);
2971 // Show the download notification after the download is completed.
2972 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2974 // Remove the lint warning below that `downloadManager` might be `null`.
2975 assert downloadManager != null;
2977 // Initiate the download.
2978 downloadManager.enqueue(downloadRequest);
2979 } else { // The image is not an HTTP or HTTPS URI.
2980 Snackbar.make(currentWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
2985 public void onDownloadFile(DialogFragment dialogFragment, String downloadUrl) {
2986 // Download the file if it has an HTTP or HTTPS URI.
2987 if (downloadUrl.startsWith("http")) {
2988 // Get a handle for the system `DOWNLOAD_SERVICE`.
2989 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2991 // Parse `downloadUrl`.
2992 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
2994 // Get a handle for the cookie manager.
2995 CookieManager cookieManager = CookieManager.getInstance();
2997 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
2998 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2999 if (cookieManager.acceptCookie()) {
3000 // Get the cookies for `downloadUrl`.
3001 String cookies = cookieManager.getCookie(downloadUrl);
3003 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
3004 downloadRequest.addRequestHeader("Cookie", cookies);
3007 // Get the file name from the dialog fragment.
3008 EditText downloadFileNameEditText = dialogFragment.getDialog().findViewById(R.id.download_file_name);
3009 String fileName = downloadFileNameEditText.getText().toString();
3011 // Specify the download location.
3012 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
3013 // Download to the public download directory.
3014 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
3015 } else { // External write permission denied.
3016 // Download to the app's external download directory.
3017 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, fileName);
3020 // Allow `MediaScanner` to index the download if it is a media file.
3021 downloadRequest.allowScanningByMediaScanner();
3023 // Add the URL as the description for the download.
3024 downloadRequest.setDescription(downloadUrl);
3026 // Show the download notification after the download is completed.
3027 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3029 // Remove the lint warning below that `downloadManager` might be `null`.
3030 assert downloadManager != null;
3032 // Initiate the download.
3033 downloadManager.enqueue(downloadRequest);
3034 } else { // The download is not an HTTP or HTTPS URI.
3035 Snackbar.make(currentWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
3040 public void onPinnedMismatchBack() { // TODO. Move this logic to the dialog.
3041 if (currentWebView.canGoBack()) { // There is a back page in the history.
3042 // Reset the current domain name so that navigation works if third-party requests are blocked.
3043 currentWebView.resetCurrentDomainName();
3045 // Set navigating history so that the domain settings are applied when the new URL is loaded.
3046 currentWebView.setNavigatingHistory(true);
3049 currentWebView.goBack();
3050 } else { // There are no pages to go back to.
3051 // Load a blank page
3057 public void onPinnedMismatchProceed() { // TODO. Move this logic to the dialog.
3058 // Do not check the pinned information for this domain again until the domain changes.
3059 currentWebView.setIgnorePinnedDomainInformation(true);
3063 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) { // TODO. Move this logic to the dialog.
3064 // Reset the current domain name so that navigation works if third-party requests are blocked.
3065 currentWebView.resetCurrentDomainName();
3067 // Set navigating history so that the domain settings are applied when the new URL is loaded.
3068 currentWebView.setNavigatingHistory(true);
3070 // Load the history entry.
3071 currentWebView.goBackOrForward(moveBackOrForwardSteps);
3075 public void onClearHistory() { // TODO. Move this logic to the dialog.
3076 // Clear the history.
3077 currentWebView.clearHistory();
3080 // Override `onBackPressed` to handle the navigation drawer and and the WebView.
3082 public void onBackPressed() {
3083 // Get a handle for the drawer layout.
3084 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
3086 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
3087 // Close the navigation drawer.
3088 drawerLayout.closeDrawer(GravityCompat.START);
3089 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
3090 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
3091 // close the bookmarks drawer.
3092 drawerLayout.closeDrawer(GravityCompat.END);
3093 } else { // A subfolder is displayed.
3094 // Place the former parent folder in `currentFolder`.
3095 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolderName(currentBookmarksFolder);
3097 // Load the new folder.
3098 loadBookmarksFolder();
3100 } else if (currentWebView.canGoBack()) { // There is at least one item in the current WebView history.
3101 // Reset the current domain name so that navigation works if third-party requests are blocked.
3102 currentWebView.resetCurrentDomainName();
3104 // Set navigating history so that the domain settings are applied when the new URL is loaded.
3105 currentWebView.setNavigatingHistory(true);
3108 currentWebView.goBack();
3109 } else { // There isn't anything to do in Privacy Browser.
3110 // Pass `onBackPressed()` to the system.
3111 super.onBackPressed();
3115 // 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.
3117 public void onActivityResult(int requestCode, int resultCode, Intent data) {
3118 // File uploads only work on API >= 21.
3119 if (Build.VERSION.SDK_INT >= 21) {
3120 // Pass the file to the WebView.
3121 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
3125 private void loadUrlFromTextBox() {
3126 // Get a handle for the URL edit text.
3127 EditText urlEditText = findViewById(R.id.url_edittext);
3129 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
3130 String unformattedUrlString = urlEditText.getText().toString().trim();
3132 // Initialize the formatted URL string.
3135 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
3136 if (unformattedUrlString.startsWith("content://")) { // This is a Content URL.
3137 // Load the entire content URL.
3138 url = unformattedUrlString;
3139 } else if (Patterns.WEB_URL.matcher(unformattedUrlString).matches() || unformattedUrlString.startsWith("http://") || unformattedUrlString.startsWith("https://") ||
3140 unformattedUrlString.startsWith("file://")) { // This is a standard URL.
3141 // Add `https://` at the beginning if there is no protocol. Otherwise the app will segfault.
3142 if (!unformattedUrlString.startsWith("http") && !unformattedUrlString.startsWith("file://") && !unformattedUrlString.startsWith("content://")) {
3143 unformattedUrlString = "https://" + unformattedUrlString;
3146 // Initialize `unformattedUrl`.
3147 URL unformattedUrl = null;
3149 // 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.
3151 unformattedUrl = new URL(unformattedUrlString);
3152 } catch (MalformedURLException e) {
3153 e.printStackTrace();
3156 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
3157 String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
3158 String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
3159 String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
3160 String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
3161 String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
3164 Uri.Builder uri = new Uri.Builder();
3165 uri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
3167 // Decode the URI as a UTF-8 string in.
3169 url = URLDecoder.decode(uri.build().toString(), "UTF-8");
3170 } catch (UnsupportedEncodingException exception) {
3171 // Do nothing. The formatted URL string will remain blank.
3173 } else if (!unformattedUrlString.isEmpty()){ // This is not a URL, but rather a search string.
3174 // Create an encoded URL String.
3175 String encodedUrlString;
3177 // Sanitize the search input.
3179 encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
3180 } catch (UnsupportedEncodingException exception) {
3181 encodedUrlString = "";
3184 // Add the base search URL.
3185 url = searchURL + encodedUrlString;
3188 // 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.
3189 urlEditText.clearFocus();
3195 private void loadUrl(String url) {
3196 // Apply the domain settings.
3197 applyDomainSettings(currentWebView, url, true, false);
3200 currentWebView.loadUrl(url, customHeaders);
3203 public void findPreviousOnPage(View view) {
3204 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
3205 currentWebView.findNext(false);
3208 public void findNextOnPage(View view) {
3209 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
3210 currentWebView.findNext(true);
3213 public void closeFindOnPage(View view) {
3214 // Get a handle for the views.
3215 Toolbar toolbar = findViewById(R.id.toolbar);
3216 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
3217 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
3219 // Delete the contents of `find_on_page_edittext`.
3220 findOnPageEditText.setText(null);
3222 // Clear the highlighted phrases.
3223 currentWebView.clearMatches();
3225 // Hide the find on page linear layout.
3226 findOnPageLinearLayout.setVisibility(View.GONE);
3228 // Show the toolbar.
3229 toolbar.setVisibility(View.VISIBLE);
3231 // Get a handle for the input method manager.
3232 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
3234 // Remove the lint warning below that the input method manager might be null.
3235 assert inputMethodManager != null;
3237 // Hide the keyboard.
3238 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
3241 private void applyAppSettings() {
3242 // Get a handle for the shared preferences.
3243 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3245 // Store the values from the shared preferences in variables.
3246 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3247 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
3248 proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
3249 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3250 hideAppBar = sharedPreferences.getBoolean("hide_app_bar", true);
3252 // Get handles for the views that need to be modified. `getSupportActionBar()` must be used until the minimum API >= 21.
3253 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
3254 ActionBar actionBar = getSupportActionBar();
3256 // Remove the incorrect lint warnings below that the action bar might be null.
3257 assert actionBar != null;
3259 // Apply the proxy through Orbot settings.
3260 applyProxyThroughOrbot(false);
3262 // Set Do Not Track status.
3263 if (doNotTrackEnabled) {
3264 customHeaders.put("DNT", "1");
3266 customHeaders.remove("DNT");
3269 // Set the app bar scrolling for each WebView.
3270 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3271 // Get the WebView tab fragment.
3272 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3274 // Get the fragment view.
3275 View fragmentView = webViewTabFragment.getView();
3277 // Only modify the WebViews if they exist.
3278 if (fragmentView != null) {
3279 // Get the nested scroll WebView from the tab fragment.
3280 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3282 // Set the app bar scrolling.
3283 nestedScrollWebView.setNestedScrollingEnabled(sharedPreferences.getBoolean("scroll_app_bar", true));
3287 // Update the full screen browsing mode settings.
3288 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
3289 // Update the visibility of the app bar, which might have changed in the settings.
3296 // Hide the banner ad in the free flavor.
3297 if (BuildConfig.FLAVOR.contentEquals("free")) {
3298 AdHelper.hideAd(findViewById(R.id.adview));
3301 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
3302 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3304 /* Hide the system bars.
3305 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3306 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
3307 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3308 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3310 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
3311 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3312 } else { // Privacy Browser is not in full screen browsing mode.
3313 // 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.
3314 inFullScreenBrowsingMode = false;
3316 // Show the app bar.
3319 // Show the banner ad in the free flavor.
3320 if (BuildConfig.FLAVOR.contentEquals("free")) {
3321 // Initialize the ads. If this isn't the first run, `loadAd()` will be automatically called instead.
3322 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getSupportFragmentManager(), getString(R.string.google_app_id), getString(R.string.ad_unit_id));
3325 // Remove the `SYSTEM_UI` flags from the root frame layout.
3326 rootFrameLayout.setSystemUiVisibility(0);
3328 // Add the translucent status flag.
3329 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3334 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
3335 @SuppressLint("SetJavaScriptEnabled")
3336 private boolean applyDomainSettings(NestedScrollWebView nestedScrollWebView, String url, boolean resetFavoriteIcon, boolean reloadWebsite) {
3337 // Store a copy of the current user agent to track changes for the return boolean.
3338 String initialUserAgent = nestedScrollWebView.getSettings().getUserAgentString();
3340 // Parse the URL into a URI.
3341 Uri uri = Uri.parse(url);
3343 // Extract the domain from `uri`.
3344 String newHostName = uri.getHost();
3346 // Strings don't like to be null.
3347 if (newHostName == null) {
3351 // 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.
3352 if (!nestedScrollWebView.getCurrentDomainName().equals(newHostName)) {
3353 // Set the new host name as the current domain name.
3354 nestedScrollWebView.setCurrentDomainName(newHostName);
3356 // Reset the ignoring of pinned domain information.
3357 nestedScrollWebView.setIgnorePinnedDomainInformation(false);
3359 // Clear any pinned SSL certificate or IP addresses.
3360 nestedScrollWebView.clearPinnedSslCertificate();
3361 nestedScrollWebView.clearPinnedIpAddresses();
3363 // Reset the favorite icon if specified.
3364 if (resetFavoriteIcon) {
3365 // Initialize the favorite icon.
3366 nestedScrollWebView.initializeFavoriteIcon();
3368 // Get a handle for the tab layout.
3369 TabLayout tabLayout = findViewById(R.id.tablayout);
3371 // Get the current tab.
3372 TabLayout.Tab currentTab = tabLayout.getTabAt(tabLayout.getSelectedTabPosition()); // TODO. We need to get the tab for this WebView, which might not be the current tab.
3374 // Remove the warning below that the current tab might be null.
3375 assert currentTab != null;
3377 // Get the current tab custom view.
3378 View currentTabCustomView = currentTab.getCustomView();
3380 // Remove the warning below that the current tab custom view might be null.
3381 assert currentTabCustomView != null;
3383 // Get the current tab favorite icon image view.
3384 ImageView currentTabFavoriteIconImageView = currentTabCustomView.findViewById(R.id.favorite_icon_imageview);
3386 // Set the default favorite icon as the favorite icon for this tab.
3387 currentTabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(nestedScrollWebView.getFavoriteOrDefaultIcon(), 64, 64, true));
3390 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3391 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3393 // Get a full cursor from `domainsDatabaseHelper`.
3394 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3396 // Initialize `domainSettingsSet`.
3397 Set<String> domainSettingsSet = new HashSet<>();
3399 // Get the domain name column index.
3400 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3402 // Populate `domainSettingsSet`.
3403 for (int i = 0; i < domainNameCursor.getCount(); i++) {
3404 // Move `domainsCursor` to the current row.
3405 domainNameCursor.moveToPosition(i);
3407 // Store the domain name in `domainSettingsSet`.
3408 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3411 // Close `domainNameCursor.
3412 domainNameCursor.close();
3414 // Initialize the domain name in database variable.
3415 String domainNameInDatabase = null;
3417 // Check the hostname against the domain settings set.
3418 if (domainSettingsSet.contains(newHostName)) { // The hostname is contained in the domain settings set.
3419 // Record the domain name in the database.
3420 domainNameInDatabase = newHostName;
3422 // Set the domain settings applied tracker to true.
3423 nestedScrollWebView.setDomainSettingsApplied(true);
3424 } else { // The hostname is not contained in the domain settings set.
3425 // Set the domain settings applied tracker to false.
3426 nestedScrollWebView.setDomainSettingsApplied(false);
3429 // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3430 while (!nestedScrollWebView.getDomainSettingsApplied() && newHostName.contains(".")) { // Stop checking if domain settings are already applied or there are no more `.` in the host name.
3431 if (domainSettingsSet.contains("*." + newHostName)) { // Check the host name prepended by `*.`.
3432 // Set the domain settings applied tracker to true.
3433 nestedScrollWebView.setDomainSettingsApplied(true);
3435 // Store the applied domain names as it appears in the database.
3436 domainNameInDatabase = "*." + newHostName;
3439 // Strip out the lowest subdomain of of the host name.
3440 newHostName = newHostName.substring(newHostName.indexOf(".") + 1);
3444 // Get a handle for the shared preferences.
3445 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3447 // Store the general preference information.
3448 String defaultFontSizeString = sharedPreferences.getString("font_size", getString(R.string.font_size_default_value));
3449 String defaultUserAgentName = sharedPreferences.getString("user_agent", getString(R.string.user_agent_default_value));
3450 boolean defaultSwipeToRefresh = sharedPreferences.getBoolean("swipe_to_refresh", true);
3451 boolean displayWebpageImages = sharedPreferences.getBoolean("display_webpage_images", true);
3452 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
3454 // Get a handle for the cookie manager.
3455 CookieManager cookieManager = CookieManager.getInstance();
3457 // Get handles for the views.
3458 RelativeLayout urlRelativeLayout = findViewById(R.id.url_relativelayout);
3459 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
3461 // Initialize the user agent array adapter and string array.
3462 ArrayAdapter<CharSequence> userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item);
3463 String[] userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
3465 if (nestedScrollWebView.getDomainSettingsApplied()) { // The url has custom domain settings.
3466 // Get a cursor for the current host and move it to the first position.
3467 Cursor currentDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3468 currentDomainSettingsCursor.moveToFirst();
3470 // Get the settings from the cursor.
3471 nestedScrollWebView.setDomainSettingsDatabaseId(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3472 nestedScrollWebView.setDomainSettingsJavaScriptEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3473 nestedScrollWebView.setAcceptFirstPartyCookies(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3474 boolean domainThirdPartyCookiesEnabled = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3475 nestedScrollWebView.getSettings().setDomStorageEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3476 // Form data can be removed once the minimum API >= 26.
3477 boolean saveFormData = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3478 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASY_LIST,
3479 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3480 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASY_PRIVACY,
3481 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3482 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST,
3483 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3484 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST,
3485 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3486 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRA_PRIVACY,
3487 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_ULTRAPRIVACY)) == 1);
3488 nestedScrollWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS,
3489 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
3490 String userAgentName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3491 int fontSize = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3492 int swipeToRefreshInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
3493 int nightModeInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
3494 int displayWebpageImagesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3495 boolean pinnedSslCertificate = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3496 String pinnedSslIssuedToCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3497 String pinnedSslIssuedToOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3498 String pinnedSslIssuedToUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3499 String pinnedSslIssuedByCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3500 String pinnedSslIssuedByOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3501 String pinnedSslIssuedByUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3502 boolean pinnedIpAddresses = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_IP_ADDRESSES)) == 1);
3503 String pinnedHostIpAddresses = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.IP_ADDRESSES));
3505 // Create the pinned SSL date variables.
3506 Date pinnedSslStartDate;
3507 Date pinnedSslEndDate;
3509 // 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.
3510 if (currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
3511 pinnedSslStartDate = null;
3513 pinnedSslStartDate = new Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
3516 // 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.
3517 if (currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
3518 pinnedSslEndDate = null;
3520 pinnedSslEndDate = new Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
3523 // If there is a pinned SSL certificate, store it in the WebView.
3524 if (pinnedSslCertificate) {
3525 nestedScrollWebView.setPinnedSslCertificate(pinnedSslIssuedToCName, pinnedSslIssuedToOName, pinnedSslIssuedToUName, pinnedSslIssuedByCName, pinnedSslIssuedByOName, pinnedSslIssuedByUName,
3526 pinnedSslStartDate, pinnedSslEndDate);
3529 // If there is a pinned IP address, store it in the WebView.
3530 if (pinnedIpAddresses) {
3531 nestedScrollWebView.setPinnedIpAddresses(pinnedHostIpAddresses);
3534 // Set night mode according to the night mode int.
3535 switch (nightModeInt) {
3536 case DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT:
3537 // Set night mode according to the current default.
3538 nestedScrollWebView.setNightMode(sharedPreferences.getBoolean("night_mode", false));
3541 case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
3542 // Enable night mode.
3543 nestedScrollWebView.setNightMode(true);
3546 case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
3547 // Disable night mode.
3548 nestedScrollWebView.setNightMode(false);
3552 // Enable JavaScript if night mode is enabled.
3553 if (nestedScrollWebView.getNightMode()) {
3554 // Enable JavaScript.
3555 nestedScrollWebView.getSettings().setJavaScriptEnabled(true);
3557 // Set JavaScript according to the domain settings.
3558 nestedScrollWebView.getSettings().setJavaScriptEnabled(nestedScrollWebView.getDomainSettingsJavaScriptEnabled());
3561 // Close the current host domain settings cursor.
3562 currentDomainSettingsCursor.close();
3564 // Apply the domain settings.
3565 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptFirstPartyCookies());
3567 // Set third-party cookies status if API >= 21.
3568 if (Build.VERSION.SDK_INT >= 21) {
3569 cookieManager.setAcceptThirdPartyCookies(nestedScrollWebView, domainThirdPartyCookiesEnabled);
3572 // Apply the form data setting if the API < 26.
3573 if (Build.VERSION.SDK_INT < 26) {
3574 nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
3577 // Apply the font size.
3578 if (fontSize == 0) { // Apply the default font size.
3579 nestedScrollWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3580 } else { // Apply the specified font size.
3581 nestedScrollWebView.getSettings().setTextZoom(fontSize);
3584 // 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.
3585 // <https://redmine.stoutner.com/issues/160>
3586 if (nestedScrollWebView.getProgress() == 100) { // A URL is not loading.
3587 // Set the user agent.
3588 if (userAgentName.equals(getString(R.string.system_default_user_agent))) { // Use the system default user agent.
3589 // Get the array position of the default user agent name.
3590 int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3592 // Set the user agent according to the system default.
3593 switch (defaultUserAgentArrayPosition) {
3594 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
3595 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3596 nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
3599 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3600 // Set the user agent to `""`, which uses the default value.
3601 nestedScrollWebView.getSettings().setUserAgentString("");
3604 case SETTINGS_CUSTOM_USER_AGENT:
3605 // Set the default custom user agent.
3606 nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
3610 // Get the user agent string from the user agent data array
3611 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
3613 } else { // Set the user agent according to the stored name.
3614 // Get the array position of the user agent name.
3615 int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
3617 switch (userAgentArrayPosition) {
3618 case UNRECOGNIZED_USER_AGENT: // The user agent name contains a custom user agent.
3619 nestedScrollWebView.getSettings().setUserAgentString(userAgentName);
3622 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3623 // Set the user agent to `""`, which uses the default value.
3624 nestedScrollWebView.getSettings().setUserAgentString("");
3628 // Get the user agent string from the user agent data array.
3629 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3634 // Set swipe to refresh.
3635 switch (swipeToRefreshInt) {
3636 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_SYSTEM_DEFAULT:
3637 // Store the swipe to refresh status in the nested scroll WebView.
3638 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
3640 // 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.
3641 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
3644 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_ENABLED:
3645 // Store the swipe to refresh status in the nested scroll WebView.
3646 nestedScrollWebView.setSwipeToRefresh(true);
3648 // Enable swipe to refresh. This can be removed once the minimum API >= 23 because it is continuously set by an on scroll change listener.
3649 swipeRefreshLayout.setEnabled(true);
3652 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_DISABLED:
3653 // Store the swipe to refresh status in the nested scroll WebView.
3654 nestedScrollWebView.setSwipeToRefresh(false);
3656 // Disable swipe to refresh. This can be removed once the minimum API >= 23 because it is continuously set by an on scroll change listener.
3657 swipeRefreshLayout.setEnabled(false);
3660 // Set the loading of webpage images.
3661 switch (displayWebpageImagesInt) {
3662 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
3663 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
3666 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
3667 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(true);
3670 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
3671 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(false);
3675 // 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.
3677 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
3679 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
3681 } else { // The new URL does not have custom domain settings. Load the defaults.
3682 // Store the values from the shared preferences.
3683 boolean defaultJavaScriptEnabled = sharedPreferences.getBoolean("javascript", false);
3684 nestedScrollWebView.setAcceptFirstPartyCookies(sharedPreferences.getBoolean("first_party_cookies", false));
3685 boolean defaultThirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies", false);
3686 nestedScrollWebView.getSettings().setDomStorageEnabled(sharedPreferences.getBoolean("dom_storage", false));
3687 boolean saveFormData = sharedPreferences.getBoolean("save_form_data", false); // Form data can be removed once the minimum API >= 26.
3688 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASY_LIST, sharedPreferences.getBoolean("easylist", true));
3689 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASY_PRIVACY, sharedPreferences.getBoolean("easyprivacy", true));
3690 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, sharedPreferences.getBoolean("fanboys_annoyance_list", true));
3691 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, sharedPreferences.getBoolean("fanboys_social_blocking_list", true));
3692 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRA_PRIVACY, sharedPreferences.getBoolean("ultraprivacy", true));
3693 nestedScrollWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, sharedPreferences.getBoolean("block_all_third_party_requests", false));
3694 nestedScrollWebView.setNightMode(sharedPreferences.getBoolean("night_mode", false));
3696 // Enable JavaScript if night mode is enabled.
3697 if (nestedScrollWebView.getNightMode()) {
3698 // Enable JavaScript.
3699 nestedScrollWebView.getSettings().setJavaScriptEnabled(true);
3701 // Set JavaScript according to the domain settings.
3702 nestedScrollWebView.getSettings().setJavaScriptEnabled(defaultJavaScriptEnabled);
3705 // Apply the default settings.
3706 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptFirstPartyCookies());
3707 nestedScrollWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3709 // Apply the form data setting if the API < 26.
3710 if (Build.VERSION.SDK_INT < 26) {
3711 nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
3714 // Store the swipe to refresh status in the nested scroll WebView.
3715 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
3717 // Apply swipe to refresh according to the default.
3718 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
3720 // Reset the pinned variables.
3721 nestedScrollWebView.setDomainSettingsDatabaseId(-1);
3723 // Set third-party cookies status if API >= 21.
3724 if (Build.VERSION.SDK_INT >= 21) {
3725 cookieManager.setAcceptThirdPartyCookies(nestedScrollWebView, defaultThirdPartyCookiesEnabled);
3728 // 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.
3729 // <https://redmine.stoutner.com/issues/160>
3730 if (nestedScrollWebView.getProgress() == 100) { // A URL is not loading.
3731 // Get the array position of the user agent name.
3732 int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3734 // Set the user agent.
3735 switch (userAgentArrayPosition) {
3736 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
3737 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3738 nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
3741 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3742 // Set the user agent to `""`, which uses the default value.
3743 nestedScrollWebView.getSettings().setUserAgentString("");
3746 case SETTINGS_CUSTOM_USER_AGENT:
3747 // Set the default custom user agent.
3748 nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
3752 // Get the user agent string from the user agent data array
3753 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3757 // Set the loading of webpage images.
3758 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
3760 // Set a transparent background on URL edit text. The deprecated `getResources().getDrawable()` must be used until the minimum API >= 21.
3761 urlRelativeLayout.setBackground(getResources().getDrawable(R.color.transparent));
3764 // Close the domains database helper.
3765 domainsDatabaseHelper.close();
3767 // Update the privacy icons.
3768 updatePrivacyIcons(true);
3771 // Reload the website if returning from the Domains activity.
3772 if (reloadWebsite) {
3773 nestedScrollWebView.reload();
3776 // Return the user agent changed status.
3777 return !nestedScrollWebView.getSettings().getUserAgentString().equals(initialUserAgent);
3780 private void applyProxyThroughOrbot(boolean reloadWebsite) {
3781 // Get a handle for the shared preferences.
3782 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3784 // Get the search and theme preferences.
3785 String torSearchString = sharedPreferences.getString("tor_search", getString(R.string.tor_search_default_value));
3786 String torSearchCustomUrlString = sharedPreferences.getString("tor_search_custom_url", getString(R.string.tor_search_custom_url_default_value));
3787 String searchString = sharedPreferences.getString("search", getString(R.string.search_default_value));
3788 String searchCustomUrlString = sharedPreferences.getString("search_custom_url", getString(R.string.search_custom_url_default_value));
3789 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
3791 // Get a handle for the action bar. `getSupportActionBar()` must be used until the minimum API >= 21.
3792 ActionBar actionBar = getSupportActionBar();
3794 // Remove the incorrect lint warning later that the action bar might be null.
3795 assert actionBar != null;
3797 // Set the homepage, search, and proxy options.
3798 if (proxyThroughOrbot) { // Set the Tor options.
3799 // Set the search URL.
3800 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
3801 searchURL = torSearchCustomUrlString;
3802 } else { // Use the string from the pre-built list.
3803 searchURL = torSearchString;
3806 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
3807 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
3809 // Set the `appBar` background to indicate proxying through Orbot is enabled.
3811 actionBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
3813 actionBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
3816 // Check to see if Orbot is ready.
3817 if (!orbotStatus.equals("ON")) { // Orbot is not ready.
3818 // Set `waitingForOrbot`.
3819 waitingForOrbot = true;
3821 // Disable the wide view port so that the waiting for Orbot text is displayed correctly.
3822 currentWebView.getSettings().setUseWideViewPort(false);
3824 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
3825 currentWebView.loadData("<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>", "text/html", null);
3826 } else if (reloadWebsite) { // Orbot is ready and the website should be reloaded.
3827 // Reload the website.
3828 currentWebView.reload();
3830 } else { // Set the non-Tor options.
3831 // Set the search URL.
3832 if (searchString.equals("Custom URL")) { // Get the custom URL string.
3833 searchURL = searchCustomUrlString;
3834 } else { // Use the string from the pre-built list.
3835 searchURL = searchString;
3838 // Reset the proxy to default. The host is `""` and the port is `"0"`.
3839 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
3841 // Set the default `appBar` background.
3843 actionBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
3845 actionBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
3848 // Reset `waitingForOrbot.
3849 waitingForOrbot = false;
3851 // Reload the WebViews if requested.
3852 if (reloadWebsite) {
3853 // Reload the WebViews.
3854 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3855 // Get the WebView tab fragment.
3856 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3858 // Get the fragment view.
3859 View fragmentView = webViewTabFragment.getView();
3861 // Only reload the WebViews if they exist.
3862 if (fragmentView != null) {
3863 // Get the nested scroll WebView from the tab fragment.
3864 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3866 // Reload the WebView.
3867 nestedScrollWebView.reload();
3874 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
3875 // Only update the privacy icons if the options menu and the current WebView have already been populated.
3876 if ((optionsMenu != null) && (currentWebView != null)) {
3877 // Get a handle for the shared preferences.
3878 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3880 // Get the theme and screenshot preferences.
3881 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
3883 // Get handles for the menu items.
3884 MenuItem privacyMenuItem = optionsMenu.findItem(R.id.toggle_javascript);
3885 MenuItem firstPartyCookiesMenuItem = optionsMenu.findItem(R.id.toggle_first_party_cookies);
3886 MenuItem domStorageMenuItem = optionsMenu.findItem(R.id.toggle_dom_storage);
3887 MenuItem refreshMenuItem = optionsMenu.findItem(R.id.refresh);
3889 // Update the privacy icon.
3890 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is enabled.
3891 privacyMenuItem.setIcon(R.drawable.javascript_enabled);
3892 } else if (currentWebView.getAcceptFirstPartyCookies()) { // JavaScript is disabled but cookies are enabled.
3893 privacyMenuItem.setIcon(R.drawable.warning);
3894 } else { // All the dangerous features are disabled.
3895 privacyMenuItem.setIcon(R.drawable.privacy_mode);
3898 // Update the first-party cookies icon.
3899 if (currentWebView.getAcceptFirstPartyCookies()) { // First-party cookies are enabled.
3900 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
3901 } else { // First-party cookies are disabled.
3903 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_dark);
3905 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_light);
3909 // Update the DOM storage icon.
3910 if (currentWebView.getSettings().getJavaScriptEnabled() && currentWebView.getSettings().getDomStorageEnabled()) { // Both JavaScript and DOM storage are enabled.
3911 domStorageMenuItem.setIcon(R.drawable.dom_storage_enabled);
3912 } else if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is enabled but DOM storage is disabled.
3914 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
3916 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
3918 } else { // JavaScript is disabled, so DOM storage is ghosted.
3920 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
3922 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
3926 // Update the refresh icon.
3928 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
3930 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
3933 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
3934 if (runInvalidateOptionsMenu) {
3935 invalidateOptionsMenu();
3940 private void openUrlWithExternalApp(String url) {
3941 // Create a download intent. Not specifying the action type will display the maximum number of options.
3942 Intent downloadIntent = new Intent();
3944 // Set the URI and the MIME type. Specifying `text/html` displays a good number of options.
3945 downloadIntent.setDataAndType(Uri.parse(url), "text/html");
3947 // Flag the intent to open in a new task.
3948 downloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3950 // Show the chooser.
3951 startActivity(Intent.createChooser(downloadIntent, getString(R.string.open_with)));
3954 private void highlightUrlText() {
3955 // Get a handle for the URL edit text.
3956 EditText urlEditText = findViewById(R.id.url_edittext);
3958 // Only highlight the URL text if the box is not currently selected.
3959 if (!urlEditText.hasFocus()) {
3960 // Get the URL string.
3961 String urlString = urlEditText.getText().toString();
3963 // Highlight the URL according to the protocol.
3964 if (urlString.startsWith("file://")) { // This is a file URL.
3965 // De-emphasize only the protocol.
3966 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3967 } else if (urlString.startsWith("content://")) {
3968 // De-emphasize only the protocol.
3969 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 10, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3970 } else { // This is a web URL.
3971 // Get the index of the `/` immediately after the domain name.
3972 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
3974 // Create a base URL string.
3977 // Get the base URL.
3978 if (endOfDomainName > 0) { // There is at least one character after the base URL.
3979 // Get the base URL.
3980 baseUrl = urlString.substring(0, endOfDomainName);
3981 } else { // There are no characters after the base URL.
3982 // Set the base URL to be the entire URL string.
3983 baseUrl = urlString;
3986 // Get the index of the last `.` in the domain.
3987 int lastDotIndex = baseUrl.lastIndexOf(".");
3989 // Get the index of the penultimate `.` in the domain.
3990 int penultimateDotIndex = baseUrl.lastIndexOf(".", lastDotIndex - 1);
3992 // Markup the beginning of the URL.
3993 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
3994 urlEditText.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3996 // De-emphasize subdomains.
3997 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
3998 urlEditText.getText().setSpan(initialGrayColorSpan, 7, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4000 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
4001 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
4002 // De-emphasize the protocol and the additional subdomains.
4003 urlEditText.getText().setSpan(initialGrayColorSpan, 0, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4004 } else { // There is only one subdomain in the domain name.
4005 // De-emphasize only the protocol.
4006 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4010 // De-emphasize the text after the domain name.
4011 if (endOfDomainName > 0) {
4012 urlEditText.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4018 private void loadBookmarksFolder() {
4019 // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
4020 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
4022 // Populate the bookmarks cursor adapter. `this` specifies the `Context`. `false` disables `autoRequery`.
4023 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
4025 public View newView(Context context, Cursor cursor, ViewGroup parent) {
4026 // Inflate the individual item layout. `false` does not attach it to the root.
4027 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
4031 public void bindView(View view, Context context, Cursor cursor) {
4032 // Get handles for the views.
4033 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
4034 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
4036 // Get the favorite icon byte array from the cursor.
4037 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
4039 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
4040 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
4042 // Display the bitmap in `bookmarkFavoriteIcon`.
4043 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
4045 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
4046 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
4047 bookmarkNameTextView.setText(bookmarkNameString);
4049 // Make the font bold for folders.
4050 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
4051 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
4052 } else { // Reset the font to default for normal bookmarks.
4053 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
4058 // Get a handle for the bookmarks list view.
4059 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
4061 // Populate the list view with the adapter.
4062 bookmarksListView.setAdapter(bookmarksCursorAdapter);
4064 // Get a handle for the bookmarks title text view.
4065 TextView bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
4067 // Set the bookmarks drawer title.
4068 if (currentBookmarksFolder.isEmpty()) {
4069 bookmarksTitleTextView.setText(R.string.bookmarks);
4071 bookmarksTitleTextView.setText(currentBookmarksFolder);
4075 private void openWithApp(String url) {
4076 // Create the open with intent with `ACTION_VIEW`.
4077 Intent openWithAppIntent = new Intent(Intent.ACTION_VIEW);
4079 // Set the URI but not the MIME type. This should open all available apps.
4080 openWithAppIntent.setData(Uri.parse(url));
4082 // Flag the intent to open in a new task.
4083 openWithAppIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4085 // Show the chooser.
4086 startActivity(openWithAppIntent);
4089 private void openWithBrowser(String url) {
4090 // Create the open with intent with `ACTION_VIEW`.
4091 Intent openWithBrowserIntent = new Intent(Intent.ACTION_VIEW);
4093 // Set the URI and the MIME type. `"text/html"` should load browser options.
4094 openWithBrowserIntent.setDataAndType(Uri.parse(url), "text/html");
4096 // Flag the intent to open in a new task.
4097 openWithBrowserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4099 // Show the chooser.
4100 startActivity(openWithBrowserIntent);
4103 public void addTab(View view) {
4104 // Get a handle for the tab layout and the view pager.
4105 TabLayout tabLayout = findViewById(R.id.tablayout);
4106 ViewPager webViewPager = findViewById(R.id.webviewpager);
4108 // Get the new page number. The page numbers are 0 indexed, so the new page number will match the current count.
4109 int newTabNumber = tabLayout.getTabCount();
4112 tabLayout.addTab(tabLayout.newTab());
4115 TabLayout.Tab newTab = tabLayout.getTabAt(newTabNumber);
4117 // Remove the lint warning below that the current tab might be null.
4118 assert newTab != null;
4120 // Set a custom view on the new tab.
4121 newTab.setCustomView(R.layout.custom_tab_view);
4123 // Add the new WebView page.
4124 webViewPagerAdapter.addPage(newTabNumber, webViewPager);
4127 private void setCurrentWebView(int pageNumber) {
4128 // Get a handle for the shared preferences.
4129 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4131 // Get the theme preference.
4132 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
4134 // Get handles for the URL views.
4135 RelativeLayout urlRelativeLayout = findViewById(R.id.url_relativelayout);
4136 EditText urlEditText = findViewById(R.id.url_edittext);
4137 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
4139 //Stop the swipe to refresh indicator if it is running
4140 swipeRefreshLayout.setRefreshing(false);
4142 // Get the WebView tab fragment.
4143 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(pageNumber);
4145 // Get the fragment view.
4146 View fragmentView = webViewTabFragment.getView();
4148 // Set the current WebView if the fragment view is not null.
4149 if (fragmentView != null) {
4150 // Store the current WebView.
4151 currentWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4153 // Update the status of swipe to refresh.
4154 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
4155 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.
4156 // Enable the swipe refresh layout if the WebView is scrolled all the way to the top.
4157 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
4159 // Enable the swipe refresh layout.
4160 swipeRefreshLayout.setEnabled(true);
4162 } else { // Swipe to refresh is disabled.
4163 // Disable the swipe refresh layout.
4164 swipeRefreshLayout.setEnabled(false);
4167 // Get a handle for the cookie manager.
4168 CookieManager cookieManager = CookieManager.getInstance();
4170 // Set the first-party cookie status.
4171 cookieManager.setAcceptCookie(currentWebView.getAcceptFirstPartyCookies());
4173 // Update the privacy icons. `true` redraws the icons in the app bar.
4174 updatePrivacyIcons(true);
4176 // Clear the focus from the URL text box.
4177 urlEditText.clearFocus();
4179 // Get a handle for the input method manager.
4180 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
4182 // Remove the lint warning below that the input method manager might be null.
4183 assert inputMethodManager != null;
4185 // Hide the soft keyboard.
4186 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
4188 // Display the current URL in the URL text box.
4189 urlEditText.setText(currentWebView.getUrl());
4191 // Highlight the URL text.
4194 // Set the background to indicate the domain settings status.
4195 if (currentWebView.getDomainSettingsApplied()) {
4196 // 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.
4198 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
4200 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
4203 urlRelativeLayout.setBackground(getResources().getDrawable(R.color.transparent));
4209 public void initializeWebView(NestedScrollWebView nestedScrollWebView, int pageNumber, ProgressBar progressBar) {
4210 // Get handles for the activity views.
4211 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
4212 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
4213 RelativeLayout mainContentRelativeLayout = findViewById(R.id.main_content_relativelayout);
4214 ActionBar actionBar = getSupportActionBar();
4215 EditText urlEditText = findViewById(R.id.url_edittext);
4216 TabLayout tabLayout = findViewById(R.id.tablayout);
4217 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
4219 // Remove the incorrect lint warnings below that the some of the views might be null.
4220 assert actionBar != null;
4222 // Get a handle for the activity
4223 Activity activity = this;
4225 // Get a handle for the input method manager.
4226 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
4228 // Instantiate the blocklist helper.
4229 BlockListHelper blockListHelper = new BlockListHelper();
4231 // Remove the lint warning below that the input method manager might be null.
4232 assert inputMethodManager != null;
4234 // Get a handle for the shared preferences.
4235 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4237 // Get the relevant preferences.
4238 boolean downloadWithExternalApp = sharedPreferences.getBoolean("download_with_external_app", false);
4240 // Initialize the favorite icon.
4241 nestedScrollWebView.initializeFavoriteIcon();
4243 // Set the app bar scrolling.
4244 nestedScrollWebView.setNestedScrollingEnabled(sharedPreferences.getBoolean("scroll_app_bar", true));
4246 // Allow pinch to zoom.
4247 nestedScrollWebView.getSettings().setBuiltInZoomControls(true);
4249 // Hide zoom controls.
4250 nestedScrollWebView.getSettings().setDisplayZoomControls(false);
4252 // Don't allow mixed content (HTTP and HTTPS) on the same website.
4253 if (Build.VERSION.SDK_INT >= 21) {
4254 nestedScrollWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW);
4257 // Set the WebView to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
4258 nestedScrollWebView.getSettings().setUseWideViewPort(true);
4260 // Set the WebView to load in overview mode (zoomed out to the maximum width).
4261 nestedScrollWebView.getSettings().setLoadWithOverviewMode(true);
4263 // Explicitly disable geolocation.
4264 nestedScrollWebView.getSettings().setGeolocationEnabled(false);
4266 // Create a double-tap gesture detector to toggle full-screen mode.
4267 GestureDetector doubleTapGestureDetector = new GestureDetector(getApplicationContext(), new GestureDetector.SimpleOnGestureListener() {
4268 // Override `onDoubleTap()`. All other events are handled using the default settings.
4270 public boolean onDoubleTap(MotionEvent event) {
4271 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
4272 // Toggle the full screen browsing mode tracker.
4273 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
4275 // Toggle the full screen browsing mode.
4276 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
4277 // Hide the app bar if specified.
4282 // Hide the banner ad in the free flavor.
4283 if (BuildConfig.FLAVOR.contentEquals("free")) {
4284 AdHelper.hideAd(findViewById(R.id.adview));
4287 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
4288 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4290 /* Hide the system bars.
4291 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4292 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4293 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4294 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4296 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
4297 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
4298 } else { // Switch to normal viewing mode.
4299 // Show the app bar.
4302 // Show the banner ad in the free flavor.
4303 if (BuildConfig.FLAVOR.contentEquals("free")) {
4305 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
4308 // Remove the `SYSTEM_UI` flags from the root frame layout.
4309 rootFrameLayout.setSystemUiVisibility(0);
4311 // Add the translucent status flag.
4312 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4315 // Consume the double-tap.
4317 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
4323 // Pass all touch events on the WebView through the double-tap gesture detector.
4324 nestedScrollWebView.setOnTouchListener((View view, MotionEvent event) -> {
4325 // Call `performClick()` on the view, which is required for accessibility.
4326 view.performClick();
4328 // Send the event to the gesture detector.
4329 return doubleTapGestureDetector.onTouchEvent(event);
4332 // Register the WebView for a context menu. This is used to see link targets and download images.
4333 registerForContextMenu(nestedScrollWebView);
4335 // Allow the downloading of files.
4336 nestedScrollWebView.setDownloadListener((String url, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
4337 // Check if the download should be processed by an external app.
4338 if (downloadWithExternalApp) { // Download with an external app.
4339 // Create a download intent. Not specifying the action type will display the maximum number of options.
4340 Intent downloadIntent = new Intent();
4342 // Set the URI and the MIME type. Specifying `text/html` displays a good number of options.
4343 downloadIntent.setDataAndType(Uri.parse(url), "text/html");
4345 // Flag the intent to open in a new task.
4346 downloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4348 // Show the chooser.
4349 startActivity(Intent.createChooser(downloadIntent, getString(R.string.open_with)));
4350 } else { // Download with Android's download manager.
4351 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
4352 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission has not been granted.
4353 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
4355 // Store the variables for future use by `onRequestPermissionsResult()`.
4357 downloadContentDisposition = contentDisposition;
4358 downloadContentLength = contentLength;
4360 // Show a dialog if the user has previously denied the permission.
4361 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
4362 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
4363 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
4365 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
4366 downloadLocationPermissionDialogFragment.show(getSupportFragmentManager(), getString(R.string.download_location));
4367 } else { // Show the permission request directly.
4368 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
4369 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
4371 } else { // The storage permission has already been granted.
4372 // Get a handle for the download file alert dialog.
4373 DialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
4375 // Show the download file alert dialog.
4376 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
4381 // Update the find on page count.
4382 nestedScrollWebView.setFindListener(new WebView.FindListener() {
4383 // Get a handle for `findOnPageCountTextView`.
4384 final TextView findOnPageCountTextView = findViewById(R.id.find_on_page_count_textview);
4387 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
4388 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
4389 // Set `findOnPageCountTextView` to `0/0`.
4390 findOnPageCountTextView.setText(R.string.zero_of_zero);
4391 } else if (isDoneCounting) { // There are matches.
4392 // `activeMatchOrdinal` is zero-based.
4393 int activeMatch = activeMatchOrdinal + 1;
4395 // Build the match string.
4396 String matchString = activeMatch + "/" + numberOfMatches;
4398 // Set `findOnPageCountTextView`.
4399 findOnPageCountTextView.setText(matchString);
4404 if (Build.VERSION.SDK_INT >= 23) {
4405 nestedScrollWebView.setOnScrollChangeListener((View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) -> {
4406 // Update the status of swipe to refresh if it is enabled.
4407 if (nestedScrollWebView.getSwipeToRefresh()) {
4408 // Only enable swipe to refresh if the WebView is scrolled to the top.
4409 swipeRefreshLayout.setEnabled(scrollY == 0);
4414 // Set the web chrome client.
4415 nestedScrollWebView.setWebChromeClient(new WebChromeClient() {
4416 // Update the progress bar when a page is loading.
4418 public void onProgressChanged(WebView view, int progress) {
4419 // Inject the night mode CSS if night mode is enabled.
4420 if (nestedScrollWebView.getNightMode()) {
4421 // `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
4422 // used by WordPress. `text-decoration: none` removes all text underlines. `text-shadow: none` removes text shadows, which usually have a hard coded color.
4423 // `border: none` removes all borders, which can also be used to underline text. `a {color: #1565C0}` sets links to be a dark blue.
4424 // `::selection {background: #0D47A1}' sets the text selection highlight color to be a dark blue. `!important` takes precedent over any existing sub-settings.
4425 nestedScrollWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; " +
4426 "style.innerHTML = '* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important;" +
4427 "text-shadow: none !important; border: none !important;} a {color: #1565C0 !important;} ::selection {background: #0D47A1 !important;}'; parent.appendChild(style)})()", value -> {
4428 // Initialize a handler to display `mainWebView`.
4429 Handler displayWebViewHandler = new Handler();
4431 // Setup a runnable to display `mainWebView` after a delay to allow the CSS to be applied.
4432 Runnable displayWebViewRunnable = () -> {
4433 // Only display `mainWebView` if the progress bar is gone. This prevents the display of the `WebView` while it is still loading.
4434 if (progressBar.getVisibility() == View.GONE) {
4435 nestedScrollWebView.setVisibility(View.VISIBLE);
4439 // Displaying of `mainWebView` after 500 milliseconds.
4440 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
4444 // Update the progress bar.
4445 progressBar.setProgress(progress);
4447 // Set the visibility of the progress bar.
4448 if (progress < 100) {
4449 // Show the progress bar.
4450 progressBar.setVisibility(View.VISIBLE);
4452 // Hide the progress bar.
4453 progressBar.setVisibility(View.GONE);
4455 // Display the nested scroll WebView if night mode is disabled.
4456 // Because of a race condition between `applyDomainSettings` and `onPageStarted`,
4457 // when night mode is set by domain settings the WebView may be hidden even if night mode is not currently enabled.
4458 if (!nestedScrollWebView.getNightMode()) {
4459 nestedScrollWebView.setVisibility(View.VISIBLE);
4462 //Stop the swipe to refresh indicator if it is running
4463 swipeRefreshLayout.setRefreshing(false);
4467 // Set the favorite icon when it changes.
4469 public void onReceivedIcon(WebView view, Bitmap icon) {
4470 // Only update the favorite icon if the website has finished loading.
4471 if (progressBar.getVisibility() == View.GONE) {
4472 // Store the new favorite icon.
4473 nestedScrollWebView.setFavoriteOrDefaultIcon(icon);
4475 // Get the current page position.
4476 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
4478 // Get the current tab.
4479 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
4481 // Check to see if the tab has been populated.
4483 // Get the custom view from the tab.
4484 View tabView = tab.getCustomView();
4486 // Check to see if the custom tab view has been populated.
4487 if (tabView != null) {
4488 // Get the favorite icon image view from the tab.
4489 ImageView tabFavoriteIconImageView = tabView.findViewById(R.id.favorite_icon_imageview);
4491 // Display the favorite icon in the tab.
4492 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
4498 // Save a copy of the title when it changes.
4500 public void onReceivedTitle(WebView view, String title) {
4501 // Get the current page position.
4502 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
4504 // Get the current tab.
4505 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
4507 // Only populate the title text view if the tab has been fully created.
4509 // Get the custom view from the tab.
4510 View tabView = tab.getCustomView();
4512 // Remove the incorrect warning below that the current tab view might be null.
4513 assert tabView != null;
4515 // Get the title text view from the tab.
4516 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
4518 // Set the title as the tab text.
4519 tabTitleTextView.setText(title);
4523 // Enter full screen video.
4525 public void onShowCustomView(View video, CustomViewCallback callback) {
4526 // Get a handle for the full screen video frame layout.
4527 FrameLayout fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
4529 // Set the full screen video flag.
4530 displayingFullScreenVideo = true;
4532 // Pause the ad if this is the free flavor.
4533 if (BuildConfig.FLAVOR.contentEquals("free")) {
4534 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
4535 AdHelper.pauseAd(findViewById(R.id.adview));
4538 // Hide the keyboard.
4539 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
4541 // Hide the main content relative layout.
4542 mainContentRelativeLayout.setVisibility(View.GONE);
4544 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
4545 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
4547 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
4548 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4550 /* Hide the system bars.
4551 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4552 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4553 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4554 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4556 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
4557 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
4559 // Disable the sliding drawers.
4560 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
4562 // Add the video view to the full screen video frame layout.
4563 fullScreenVideoFrameLayout.addView(video);
4565 // Show the full screen video frame layout.
4566 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
4569 // Exit full screen video.
4571 public void onHideCustomView() {
4572 // Get a handle for the full screen video frame layout.
4573 FrameLayout fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
4575 // Unset the full screen video flag.
4576 displayingFullScreenVideo = false;
4578 // Remove all the views from the full screen video frame layout.
4579 fullScreenVideoFrameLayout.removeAllViews();
4581 // Hide the full screen video frame layout.
4582 fullScreenVideoFrameLayout.setVisibility(View.GONE);
4584 // Enable the sliding drawers.
4585 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
4587 // Show the main content relative layout.
4588 mainContentRelativeLayout.setVisibility(View.VISIBLE);
4590 // Apply the appropriate full screen mode flags.
4591 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
4592 // Hide the app bar if specified.
4597 // Hide the banner ad in the free flavor.
4598 if (BuildConfig.FLAVOR.contentEquals("free")) {
4599 AdHelper.hideAd(findViewById(R.id.adview));
4602 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
4603 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4605 /* Hide the system bars.
4606 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4607 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4608 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4609 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4611 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
4612 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
4613 } else { // Switch to normal viewing mode.
4614 // Remove the `SYSTEM_UI` flags from the root frame layout.
4615 rootFrameLayout.setSystemUiVisibility(0);
4617 // Add the translucent status flag.
4618 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4621 // Reload the ad for the free flavor if not in full screen mode.
4622 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
4624 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
4630 public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
4631 // Show the file chooser if the device is running API >= 21.
4632 if (Build.VERSION.SDK_INT >= 21) {
4633 // Store the file path callback.
4634 fileChooserCallback = filePathCallback;
4636 // Create an intent to open a chooser based ont the file chooser parameters.
4637 Intent fileChooserIntent = fileChooserParams.createIntent();
4639 // Open the file chooser. Currently only one `startActivityForResult` exists in this activity, so the request code, used to differentiate them, is simply `0`.
4640 startActivityForResult(fileChooserIntent, 0);
4646 nestedScrollWebView.setWebViewClient(new WebViewClient() {
4647 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
4648 // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
4650 public boolean shouldOverrideUrlLoading(WebView view, String url) {
4651 if (url.startsWith("http")) { // Load the URL in Privacy Browser.
4652 // Apply the domain settings for the new URL. This doesn't do anything if the domain has not changed.
4653 boolean userAgentChanged = applyDomainSettings(nestedScrollWebView, url, true, false);
4655 // Check if the user agent has changed.
4656 if (userAgentChanged) {
4657 // Manually load the URL. The changing of the user agent will cause WebView to reload the previous URL.
4658 nestedScrollWebView.loadUrl(url, customHeaders);
4660 // Returning true indicates that Privacy Browser is manually handling the loading of the URL.
4663 // Returning false causes the current WebView to handle the URL and prevents it from adding redirects to the history list.
4666 } else if (url.startsWith("mailto:")) { // Load the email address in an external email program.
4667 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
4668 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
4670 // Parse the url and set it as the data for the intent.
4671 emailIntent.setData(Uri.parse(url));
4673 // Open the email program in a new task instead of as part of Privacy Browser.
4674 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4677 startActivity(emailIntent);
4679 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
4681 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
4682 // Open the dialer and load the phone number, but wait for the user to place the call.
4683 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
4685 // Add the phone number to the intent.
4686 dialIntent.setData(Uri.parse(url));
4688 // Open the dialer in a new task instead of as part of Privacy Browser.
4689 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4692 startActivity(dialIntent);
4694 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
4696 } else { // Load a system chooser to select an app that can handle the URL.
4697 // Open an app that can handle the URL.
4698 Intent genericIntent = new Intent(Intent.ACTION_VIEW);
4700 // Add the URL to the intent.
4701 genericIntent.setData(Uri.parse(url));
4703 // List all apps that can handle the URL instead of just opening the first one.
4704 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
4706 // Open the app in a new task instead of as part of Privacy Browser.
4707 genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4709 // Start the app or display a snackbar if no app is available to handle the URL.
4711 startActivity(genericIntent);
4712 } catch (ActivityNotFoundException exception) {
4713 Snackbar.make(nestedScrollWebView, getString(R.string.unrecognized_url) + " " + url, Snackbar.LENGTH_SHORT).show();
4716 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
4721 // Check requests against the block lists. The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
4723 public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
4724 // Get a handle for the navigation view.
4725 NavigationView navigationView = findViewById(R.id.navigationview);
4727 // Get a handle for the navigation menu.
4728 Menu navigationMenu = navigationView.getMenu();
4730 // Get a handle for the navigation requests menu item. The menu is 0 based.
4731 MenuItem navigationRequestsMenuItem = navigationMenu.getItem(6);
4733 // Create an empty web resource response to be used if the resource request is blocked.
4734 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
4736 // Reset the whitelist results tracker.
4737 String[] whitelistResultStringArray = null;
4739 // Initialize the third party request tracker.
4740 boolean isThirdPartyRequest = false;
4742 // Get the current URL. `.getUrl()` throws an error because operations on the WebView cannot be made from this thread.
4743 String currentBaseDomain = nestedScrollWebView.getCurrentDomainName();
4745 // Store a copy of the current domain for use in later requests.
4746 String currentDomain = currentBaseDomain;
4748 // Nobody is happy when comparing null strings.
4749 if ((currentBaseDomain != null) && (url != null)) {
4750 // Convert the request URL to a URI.
4751 Uri requestUri = Uri.parse(url);
4753 // Get the request host name.
4754 String requestBaseDomain = requestUri.getHost();
4756 // Only check for third-party requests if the current base domain is not empty and the request domain is not null.
4757 if (!currentBaseDomain.isEmpty() && (requestBaseDomain != null)) {
4758 // Determine the current base domain.
4759 while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
4760 // Remove the first subdomain.
4761 currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
4764 // Determine the request base domain.
4765 while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
4766 // Remove the first subdomain.
4767 requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
4770 // Update the third party request tracker.
4771 isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
4775 // Get the current WebView page position.
4776 int webViewPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
4778 // Determine if the WebView is currently displayed.
4779 boolean webViewDisplayed = (webViewPagePosition == tabLayout.getSelectedTabPosition());
4781 // Block third-party requests if enabled.
4782 if (isThirdPartyRequest && nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS)) {
4783 // Add the result to the resource requests.
4784 nestedScrollWebView.addResourceRequest(new String[]{BlockListHelper.REQUEST_THIRD_PARTY, url});
4786 // Increment the blocked requests counters.
4787 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
4788 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS);
4790 // Update the titles of the blocklist menu items if the WebView is currently displayed.
4791 if (webViewDisplayed) {
4792 // Updating the UI must be run from the UI thread.
4793 activity.runOnUiThread(() -> {
4794 // Update the menu item titles.
4795 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
4797 // Update the options menu if it has been populated.
4798 if (optionsMenu != null) {
4799 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
4800 optionsMenu.findItem(R.id.block_all_third_party_requests).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " +
4801 getString(R.string.block_all_third_party_requests));
4806 // Return an empty web resource response.
4807 return emptyWebResourceResponse;
4810 // Check UltraPrivacy if it is enabled.
4811 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY)) {
4812 // Check the URL against UltraPrivacy.
4813 String[] ultraPrivacyResults = blockListHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraPrivacy);
4815 // Process the UltraPrivacy results.
4816 if (ultraPrivacyResults[0].equals(BlockListHelper.REQUEST_BLOCKED)) { // The resource request matched UltraPrivacy's blacklist.
4817 // Add the result to the resource requests.
4818 nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
4819 ultraPrivacyResults[5]});
4821 // Increment the blocked requests counters.
4822 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
4823 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRA_PRIVACY);
4825 // Update the titles of the blocklist menu items if the WebView is currently displayed.
4826 if (webViewDisplayed) {
4827 // Updating the UI must be run from the UI thread.
4828 activity.runOnUiThread(() -> {
4829 // Update the menu item titles.
4830 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
4832 // Update the options menu if it has been populated.
4833 if (optionsMenu != null) {
4834 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
4835 optionsMenu.findItem(R.id.ultraprivacy).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRA_PRIVACY) + " - " + getString(R.string.ultraprivacy));
4840 // The resource request was blocked. Return an empty web resource response.
4841 return emptyWebResourceResponse;
4842 } else if (ultraPrivacyResults[0].equals(BlockListHelper.REQUEST_ALLOWED)) { // The resource request matched UltraPrivacy's whitelist.
4843 // Add a whitelist entry to the resource requests array.
4844 nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
4845 ultraPrivacyResults[5]});
4847 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
4852 // Check EasyList if it is enabled.
4853 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST)) {
4854 // Check the URL against EasyList.
4855 String[] easyListResults = blockListHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyList);
4857 // Process the EasyList results.
4858 if (easyListResults[0].equals(BlockListHelper.REQUEST_BLOCKED)) { // The resource request matched EasyList's blacklist.
4859 // Add the result to the resource requests.
4860 nestedScrollWebView.addResourceRequest(new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]});
4862 // Increment the blocked requests counters.
4863 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
4864 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASY_LIST);
4866 // Update the titles of the blocklist menu items if the WebView is currently displayed.
4867 if (webViewDisplayed) {
4868 // Updating the UI must be run from the UI thread.
4869 activity.runOnUiThread(() -> {
4870 // Update the menu item titles.
4871 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
4873 // Update the options menu if it has been populated.
4874 if (optionsMenu != null) {
4875 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
4876 optionsMenu.findItem(R.id.easylist).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASY_LIST) + " - " + getString(R.string.easylist));
4881 // The resource request was blocked. Return an empty web resource response.
4882 return emptyWebResourceResponse;
4883 } else if (easyListResults[0].equals(BlockListHelper.REQUEST_ALLOWED)) { // The resource request matched EasyList's whitelist.
4884 // Update the whitelist result string array tracker.
4885 whitelistResultStringArray = new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]};
4889 // Check EasyPrivacy if it is enabled.
4890 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY)) {
4891 // Check the URL against EasyPrivacy.
4892 String[] easyPrivacyResults = blockListHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyPrivacy);
4894 // Process the EasyPrivacy results.
4895 if (easyPrivacyResults[0].equals(BlockListHelper.REQUEST_BLOCKED)) { // The resource request matched EasyPrivacy's blacklist.
4896 // Add the result to the resource requests.
4897 nestedScrollWebView.addResourceRequest(new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4],
4898 easyPrivacyResults[5]});
4900 // Increment the blocked requests counters.
4901 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
4902 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASY_PRIVACY);
4904 // Update the titles of the blocklist menu items if the WebView is currently displayed.
4905 if (webViewDisplayed) {
4906 // Updating the UI must be run from the UI thread.
4907 activity.runOnUiThread(() -> {
4908 // Update the menu item titles.
4909 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
4911 // Update the options menu if it has been populated.
4912 if (optionsMenu != null) {
4913 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
4914 optionsMenu.findItem(R.id.easyprivacy).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASY_PRIVACY) + " - " + getString(R.string.easyprivacy));
4919 // The resource request was blocked. Return an empty web resource response.
4920 return emptyWebResourceResponse;
4921 } else if (easyPrivacyResults[0].equals(BlockListHelper.REQUEST_ALLOWED)) { // The resource request matched EasyPrivacy's whitelist.
4922 // Update the whitelist result string array tracker.
4923 whitelistResultStringArray = new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5]};
4927 // Check Fanboy’s Annoyance List if it is enabled.
4928 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST)) {
4929 // Check the URL against Fanboy's Annoyance List.
4930 String[] fanboysAnnoyanceListResults = blockListHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList);
4932 // Process the Fanboy's Annoyance List results.
4933 if (fanboysAnnoyanceListResults[0].equals(BlockListHelper.REQUEST_BLOCKED)) { // The resource request matched Fanboy's Annoyance List's blacklist.
4934 // Add the result to the resource requests.
4935 nestedScrollWebView.addResourceRequest(new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
4936 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]});
4938 // Increment the blocked requests counters.
4939 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
4940 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST);
4942 // Update the titles of the blocklist menu items if the WebView is currently displayed.
4943 if (webViewDisplayed) {
4944 // Updating the UI must be run from the UI thread.
4945 activity.runOnUiThread(() -> {
4946 // Update the menu item titles.
4947 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
4949 // Update the options menu if it has been populated.
4950 if (optionsMenu != null) {
4951 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
4952 optionsMenu.findItem(R.id.fanboys_annoyance_list).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " +
4953 getString(R.string.fanboys_annoyance_list));
4958 // The resource request was blocked. Return an empty web resource response.
4959 return emptyWebResourceResponse;
4960 } else if (fanboysAnnoyanceListResults[0].equals(BlockListHelper.REQUEST_ALLOWED)){ // The resource request matched Fanboy's Annoyance List's whitelist.
4961 // Update the whitelist result string array tracker.
4962 whitelistResultStringArray = new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
4963 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]};
4965 } else if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST)) { // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
4966 // Check the URL against Fanboy's Annoyance List.
4967 String[] fanboysSocialListResults = blockListHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysSocialList);
4969 // Process the Fanboy's Social Blocking List results.
4970 if (fanboysSocialListResults[0].equals(BlockListHelper.REQUEST_BLOCKED)) { // The resource request matched Fanboy's Social Blocking List's blacklist.
4971 // Add the result to the resource requests.
4972 nestedScrollWebView.addResourceRequest(new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
4973 fanboysSocialListResults[4], fanboysSocialListResults[5]});
4975 // Increment the blocked requests counters.
4976 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
4977 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST);
4979 // Update the titles of the blocklist menu items if the WebView is currently displayed.
4980 if (webViewDisplayed) {
4981 // Updating the UI must be run from the UI thread.
4982 activity.runOnUiThread(() -> {
4983 // Update the menu item titles.
4984 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
4986 // Update the options menu if it has been populated.
4987 if (optionsMenu != null) {
4988 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
4989 optionsMenu.findItem(R.id.fanboys_social_blocking_list).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " +
4990 getString(R.string.fanboys_social_blocking_list));
4995 // The resource request was blocked. Return an empty web resource response.
4996 return emptyWebResourceResponse;
4997 } else if (fanboysSocialListResults[0].equals(BlockListHelper.REQUEST_ALLOWED)) { // The resource request matched Fanboy's Social Blocking List's whitelist.
4998 // Update the whitelist result string array tracker.
4999 whitelistResultStringArray = new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5000 fanboysSocialListResults[4], fanboysSocialListResults[5]};
5004 // Add the request to the log because it hasn't been processed by any of the previous checks.
5005 if (whitelistResultStringArray != null) { // The request was processed by a whitelist.
5006 nestedScrollWebView.addResourceRequest(whitelistResultStringArray);
5007 } else { // The request didn't match any blocklist entry. Log it as a default request.
5008 nestedScrollWebView.addResourceRequest(new String[]{BlockListHelper.REQUEST_DEFAULT, url});
5011 // The resource request has not been blocked. `return null` loads the requested resource.
5015 // Handle HTTP authentication requests.
5017 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
5018 // Store the handler.
5019 nestedScrollWebView.setHttpAuthHandler(handler);
5021 // Instantiate an HTTP authentication dialog.
5022 DialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm, nestedScrollWebView.getWebViewFragmentId());
5024 // Show the HTTP authentication dialog.
5025 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
5029 public void onPageStarted(WebView view, String url, Bitmap favicon) {
5030 // Get the theme preference.
5031 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
5033 // Reset the list of resource requests.
5034 nestedScrollWebView.clearResourceRequests();
5036 // Reset the requests counters.
5037 nestedScrollWebView.resetRequestsCounters();
5039 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
5040 if (nestedScrollWebView.getNightMode()) {
5041 nestedScrollWebView.setVisibility(View.INVISIBLE);
5044 // Hide the keyboard.
5045 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
5047 // Check to see if Privacy Browser is waiting on Orbot.
5048 if (!waitingForOrbot) { // Process the URL.
5049 // Display the formatted URL text.
5050 urlEditText.setText(url);
5052 // Apply text highlighting to `urlTextBox`.
5055 // Reset the list of host IP addresses.
5056 nestedScrollWebView.clearCurrentIpAddresses();
5058 // Get a URI for the current URL.
5059 Uri currentUri = Uri.parse(url);
5061 // Get the IP addresses for the host.
5062 new GetHostIpAddresses(activity, getSupportFragmentManager(), nestedScrollWebView).execute(currentUri.getHost());
5064 // Apply any custom domain settings if the URL was loaded by navigating history.
5065 if (nestedScrollWebView.getNavigatingHistory()) {
5066 // Reset navigating history.
5067 nestedScrollWebView.setNavigatingHistory(false);
5069 // Apply the domain settings.
5070 boolean userAgentChanged = applyDomainSettings(nestedScrollWebView, url, true, false);
5072 // Manually load the URL if the user agent has changed, which will have caused the previous URL to be reloaded.
5073 if (userAgentChanged) {
5078 // Replace Refresh with Stop if the options menu has been created. (The WebView typically begins loading before the menu items are instantiated.)
5079 if (optionsMenu != null) {
5080 // Get a handle for the refresh menu item.
5081 MenuItem refreshMenuItem = optionsMenu.findItem(R.id.refresh);
5084 refreshMenuItem.setTitle(R.string.stop);
5086 // Get the app bar and theme preferences.
5087 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
5089 // If the icon is displayed in the AppBar, set it according to the theme.
5090 if (displayAdditionalAppBarIcons) {
5092 refreshMenuItem.setIcon(R.drawable.close_dark);
5094 refreshMenuItem.setIcon(R.drawable.close_light);
5102 public void onPageFinished(WebView view, String url) {
5103 // Reset the wide view port if it has been turned off by the waiting for Orbot message.
5104 if (!waitingForOrbot) {
5105 // Only use a wide view port if the URL starts with `http`, not for `file://` and `content://`.
5106 nestedScrollWebView.getSettings().setUseWideViewPort(url.startsWith("http"));
5109 // Flush any cookies to persistent storage. The cookie manager has become very lazy about flushing cookies in recent versions.
5110 if (nestedScrollWebView.getAcceptFirstPartyCookies() && Build.VERSION.SDK_INT >= 21) {
5111 CookieManager.getInstance().flush();
5114 // Update the Refresh menu item if the options menu has been created.
5115 if (optionsMenu != null) {
5116 // Get a handle for the refresh menu item.
5117 MenuItem refreshMenuItem = optionsMenu.findItem(R.id.refresh);
5119 // Reset the Refresh title.
5120 refreshMenuItem.setTitle(R.string.refresh);
5122 // Get the app bar and theme preferences.
5123 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
5124 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
5126 // If the icon is displayed in the AppBar, reset it according to the theme.
5127 if (displayAdditionalAppBarIcons) {
5129 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
5131 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
5136 // Clear the cache and history if Incognito Mode is enabled.
5137 if (incognitoModeEnabled) {
5138 // Clear the cache. `true` includes disk files.
5139 nestedScrollWebView.clearCache(true);
5141 // Clear the back/forward history.
5142 nestedScrollWebView.clearHistory();
5144 // Manually delete cache folders.
5146 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
5147 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
5148 String privateDataDirectoryString = getApplicationInfo().dataDir;
5150 // Delete the main cache directory.
5151 Runtime.getRuntime().exec("rm -rf " + privateDataDirectoryString + "/cache");
5153 // Delete the secondary `Service Worker` cache directory.
5154 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
5155 Runtime.getRuntime().exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
5156 } catch (IOException e) {
5157 // Do nothing if an error is thrown.
5161 // Update the URL text box and apply domain settings if not waiting on Orbot.
5162 if (!waitingForOrbot) {
5163 // Check to see if `WebView` has set `url` to be `about:blank`.
5164 if (url.equals("about:blank")) { // The WebView is blank.
5165 // Display the hint in the URL edit text.
5166 urlEditText.setText("");
5168 // Request focus for `urlTextBox`.
5169 urlEditText.requestFocus();
5171 // Display the keyboard.
5172 inputMethodManager.showSoftInput(urlEditText, 0);
5174 // Hide the WebView, which causes the default background color to be displayed according to the theme.
5175 nestedScrollWebView.setVisibility(View.GONE);
5177 // Apply the domain settings. This clears any settings from the previous domain.
5178 applyDomainSettings(nestedScrollWebView, "", true, false);
5179 } else { // The WebView has loaded a webpage.
5180 // Only update the URL text box if the user is not typing in it.
5181 if (!urlEditText.hasFocus()) {
5182 // Display the final URL. Getting the URL from the WebView instead of using the one provided by `onPageFinished` makes websites like YouTube function correctly.
5183 urlEditText.setText(nestedScrollWebView.getUrl());
5185 // Apply text highlighting to `urlTextBox`.
5190 // Check the current website information against any pinned domain information if the current IP addresses have been loaded.
5191 if ((nestedScrollWebView.hasPinnedSslCertificate() || nestedScrollWebView.hasPinnedIpAddresses()) && nestedScrollWebView.hasCurrentIpAddresses() &&
5192 !nestedScrollWebView.ignorePinnedDomainInformation()) {
5193 CheckPinnedMismatchHelper.checkPinnedMismatch(getSupportFragmentManager(), nestedScrollWebView);
5198 // Handle SSL Certificate errors.
5200 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
5201 // Get the current website SSL certificate.
5202 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
5204 // Extract the individual pieces of information from the current website SSL certificate.
5205 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
5206 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
5207 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
5208 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
5209 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
5210 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
5211 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
5212 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
5214 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
5215 if (nestedScrollWebView.hasPinnedSslCertificate()) {
5216 // Get the pinned SSL certificate.
5217 ArrayList<Object> pinnedSslCertificateArrayList = nestedScrollWebView.getPinnedSslCertificate();
5219 // Extract the arrays from the array list.
5220 String[] pinnedSslCertificateStringArray = (String[]) pinnedSslCertificateArrayList.get(0);
5221 Date[] pinnedSslCertificateDateArray = (Date[]) pinnedSslCertificateArrayList.get(1);
5223 // Check if the current SSL certificate matches the pinned certificate.
5224 if (currentWebsiteIssuedToCName.equals(pinnedSslCertificateStringArray[0]) && currentWebsiteIssuedToOName.equals(pinnedSslCertificateStringArray[1]) &&
5225 currentWebsiteIssuedToUName.equals(pinnedSslCertificateStringArray[2]) && currentWebsiteIssuedByCName.equals(pinnedSslCertificateStringArray[3]) &&
5226 currentWebsiteIssuedByOName.equals(pinnedSslCertificateStringArray[4]) && currentWebsiteIssuedByUName.equals(pinnedSslCertificateStringArray[5]) &&
5227 currentWebsiteSslStartDate.equals(pinnedSslCertificateDateArray[0]) && currentWebsiteSslEndDate.equals(pinnedSslCertificateDateArray[1])) {
5229 // An SSL certificate is pinned and matches the current domain certificate. Proceed to the website without displaying an error.
5232 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
5233 // Store the SSL error handler.
5234 nestedScrollWebView.setSslErrorHandler(handler);
5236 // Instantiate an SSL certificate error alert dialog.
5237 DialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error, nestedScrollWebView.getWebViewFragmentId());
5239 // Show the SSL certificate error dialog.
5240 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
5245 // Check to see if this is the first page.
5246 if (pageNumber == 0) {
5247 // Set this nested scroll WebView as the current WebView.
5248 currentWebView = nestedScrollWebView;
5250 // Apply the app settings from the shared preferences.
5253 // Load the website if not waiting for Orbot to connect.
5254 if (!waitingForOrbot) {
5255 // Get the intent that started the app.
5256 Intent launchingIntent = getIntent();
5258 // Get the information from the intent.
5259 String launchingIntentAction = launchingIntent.getAction();
5260 Uri launchingIntentUriData = launchingIntent.getData();
5262 // If the intent action is a web search, perform the search.
5263 if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) {
5264 // Create an encoded URL string.
5265 String encodedUrlString;
5267 // Sanitize the search input and convert it to a search.
5269 encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
5270 } catch (UnsupportedEncodingException exception) {
5271 encodedUrlString = "";
5274 // Load the completed search URL.
5275 loadUrl(searchURL + encodedUrlString);
5276 } else if (launchingIntentUriData != null){ // Check to see if the intent contains a new URL.
5277 // Load the URL from the intent.
5278 loadUrl(launchingIntentUriData.toString());
5279 } else { // The is no URL in the intent.
5280 // Select the homepage based on the proxy through Orbot status.
5281 if (proxyThroughOrbot) {
5282 // Load the Tor homepage.
5283 loadUrl(sharedPreferences.getString("tor_homepage", getString(R.string.tor_homepage_default_value)));
5285 // Load the normal homepage.
5286 loadUrl(sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));