2 * Copyright © 2015-2019 Soren Stoutner <soren@stoutner.com>.
4 * Download cookie code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
6 * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
8 * Privacy Browser is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
13 * Privacy Browser is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with Privacy Browser. If not, see <http://www.gnu.org/licenses/>.
22 package com.stoutner.privacybrowser.activities;
24 import android.Manifest;
25 import android.annotation.SuppressLint;
26 import android.app.Activity;
27 import android.app.DownloadManager;
28 import android.app.SearchManager;
29 import android.content.ActivityNotFoundException;
30 import android.content.BroadcastReceiver;
31 import android.content.ClipData;
32 import android.content.ClipboardManager;
33 import android.content.Context;
34 import android.content.Intent;
35 import android.content.IntentFilter;
36 import android.content.SharedPreferences;
37 import android.content.pm.PackageManager;
38 import android.content.res.Configuration;
39 import android.database.Cursor;
40 import android.graphics.Bitmap;
41 import android.graphics.BitmapFactory;
42 import android.graphics.Typeface;
43 import android.graphics.drawable.BitmapDrawable;
44 import android.graphics.drawable.Drawable;
45 import android.net.Uri;
46 import android.net.http.SslCertificate;
47 import android.net.http.SslError;
48 import android.os.Build;
49 import android.os.Bundle;
50 import android.os.Environment;
51 import android.os.Handler;
52 import android.preference.PreferenceManager;
53 import android.print.PrintDocumentAdapter;
54 import android.print.PrintManager;
55 import android.text.Editable;
56 import android.text.Spanned;
57 import android.text.TextWatcher;
58 import android.text.style.ForegroundColorSpan;
59 import android.util.Patterns;
60 import android.view.ContextMenu;
61 import android.view.GestureDetector;
62 import android.view.KeyEvent;
63 import android.view.Menu;
64 import android.view.MenuItem;
65 import android.view.MotionEvent;
66 import android.view.View;
67 import android.view.ViewGroup;
68 import android.view.WindowManager;
69 import android.view.inputmethod.InputMethodManager;
70 import android.webkit.CookieManager;
71 import android.webkit.HttpAuthHandler;
72 import android.webkit.SslErrorHandler;
73 import android.webkit.ValueCallback;
74 import android.webkit.WebChromeClient;
75 import android.webkit.WebResourceResponse;
76 import android.webkit.WebSettings;
77 import android.webkit.WebStorage;
78 import android.webkit.WebView;
79 import android.webkit.WebViewClient;
80 import android.webkit.WebViewDatabase;
81 import android.widget.ArrayAdapter;
82 import android.widget.CursorAdapter;
83 import android.widget.EditText;
84 import android.widget.FrameLayout;
85 import android.widget.ImageView;
86 import android.widget.LinearLayout;
87 import android.widget.ListView;
88 import android.widget.ProgressBar;
89 import android.widget.RadioButton;
90 import android.widget.RelativeLayout;
91 import android.widget.TextView;
93 import androidx.annotation.NonNull;
94 import androidx.appcompat.app.ActionBar;
95 import androidx.appcompat.app.ActionBarDrawerToggle;
96 import androidx.appcompat.app.AppCompatActivity;
97 import androidx.appcompat.widget.Toolbar;
98 import androidx.core.app.ActivityCompat;
99 import androidx.core.content.ContextCompat;
100 import androidx.core.view.GravityCompat;
101 import androidx.drawerlayout.widget.DrawerLayout;
102 import androidx.fragment.app.DialogFragment;
103 import androidx.fragment.app.FragmentManager;
104 import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
105 import androidx.viewpager.widget.ViewPager;
107 import com.google.android.material.floatingactionbutton.FloatingActionButton;
108 import com.google.android.material.navigation.NavigationView;
109 import com.google.android.material.snackbar.Snackbar;
110 import com.google.android.material.tabs.TabLayout;
112 import com.stoutner.privacybrowser.BuildConfig;
113 import com.stoutner.privacybrowser.R;
114 import com.stoutner.privacybrowser.adapters.WebViewPagerAdapter;
115 import com.stoutner.privacybrowser.asynctasks.GetHostIpAddresses;
116 import com.stoutner.privacybrowser.dialogs.AdConsentDialog;
117 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
118 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
119 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
120 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
121 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
122 import com.stoutner.privacybrowser.dialogs.DownloadLocationPermissionDialog;
123 import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
124 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
125 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
126 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
127 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
128 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
129 import com.stoutner.privacybrowser.fragments.WebViewTabFragment;
130 import com.stoutner.privacybrowser.helpers.AdHelper;
131 import com.stoutner.privacybrowser.helpers.BlockListHelper;
132 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
133 import com.stoutner.privacybrowser.helpers.CheckPinnedMismatchHelper;
134 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
135 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
136 import com.stoutner.privacybrowser.views.NestedScrollWebView;
138 import java.io.ByteArrayInputStream;
139 import java.io.ByteArrayOutputStream;
141 import java.io.IOException;
142 import java.io.UnsupportedEncodingException;
143 import java.net.MalformedURLException;
145 import java.net.URLDecoder;
146 import java.net.URLEncoder;
147 import java.util.ArrayList;
148 import java.util.Date;
149 import java.util.HashMap;
150 import java.util.HashSet;
151 import java.util.List;
152 import java.util.Map;
153 import java.util.Set;
155 // TODO. New tabs are white in dark mode.
157 // AppCompatActivity from android.support.v7.app.AppCompatActivity must be used to have access to the SupportActionBar until the minimum API is >= 21.
158 public class MainWebViewActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener,
159 DownloadFileDialog.DownloadFileListener, DownloadImageDialog.DownloadImageListener, DownloadLocationPermissionDialog.DownloadLocationPermissionDialogListener, EditBookmarkDialog.EditBookmarkListener,
160 EditBookmarkFolderDialog.EditBookmarkFolderListener, NavigationView.OnNavigationItemSelectedListener, WebViewTabFragment.NewTabListener {
162 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`, `onResume()`, and `applyProxyThroughOrbot()`.
163 public static String orbotStatus;
165 // The WebView pager adapter is accessed from `HttpAuthenticationDialog`, `PinnedMismatchDialog`, and `SslCertificateErrorDialog`. It is also used in `onCreate()`, `onResume()`, and `addTab()`.
166 public static WebViewPagerAdapter webViewPagerAdapter;
168 // The load URL on restart variables are public static so they can be accessed from `BookmarksActivity`. They are used in `onRestart()`.
169 public static boolean loadUrlOnRestart;
170 public static String urlToLoadOnRestart;
172 // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onRestart()`.
173 public static boolean restartFromBookmarksActivity;
175 // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`,
176 // `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
177 public static String currentBookmarksFolder;
179 // The user agent constants are public static so they can be accessed from `SettingsFragment`, `DomainsActivity`, and `DomainSettingsFragment`.
180 public final static int UNRECOGNIZED_USER_AGENT = -1;
181 public final static int SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1;
182 public final static int SETTINGS_CUSTOM_USER_AGENT = 12;
183 public final static int DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0;
184 public final static int DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2;
185 public final static int DOMAINS_CUSTOM_USER_AGENT = 13;
189 // The current WebView is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
190 // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, `applyProxyThroughOrbot()`, and `applyDomainSettings()`.
191 private NestedScrollWebView currentWebView;
193 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
194 private final Map<String, String> customHeaders = new HashMap<>();
196 // The search URL is set in `applyProxyThroughOrbot()` and used in `onCreate()`, `onNewIntent()`, `loadURLFromTextBox()`, and `initializeWebView()`.
197 private String searchURL;
199 // The options menu is set in `onCreateOptionsMenu()` and used in `onOptionsItemSelected()`, `updatePrivacyIcons()`, and `initializeWebView()`.
200 private Menu optionsMenu;
202 // The blocklists are populated in `onCreate()` and accessed from `initializeWebView()`.
203 private ArrayList<List<String[]>> easyList;
204 private ArrayList<List<String[]>> easyPrivacy;
205 private ArrayList<List<String[]>> fanboysAnnoyanceList;
206 private ArrayList<List<String[]>> fanboysSocialList;
207 private ArrayList<List<String[]>> ultraPrivacy;
209 // `webViewDefaultUserAgent` is used in `onCreate()` and `onPrepareOptionsMenu()`.
210 private String webViewDefaultUserAgent;
212 // `proxyThroughOrbot` is used in `onRestart()`, `onOptionsItemSelected()`, `applyAppSettings()`, and `applyProxyThroughOrbot()`.
213 private boolean proxyThroughOrbot;
215 // The incognito mode is set in `applyAppSettings()` and used in `initializeWebView()`.
216 private boolean incognitoModeEnabled;
218 // The full screen browsing mode tracker is set it `applyAppSettings()` and used in `initializeWebView()`.
219 private boolean fullScreenBrowsingModeEnabled;
221 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
222 private boolean inFullScreenBrowsingMode;
224 // The hide app bar tracker is used in `applyAppSettings()` and `initializeWebView()`.
225 private boolean hideAppBar;
227 // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
228 private boolean reapplyDomainSettingsOnRestart;
230 // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
231 private boolean reapplyAppSettingsOnRestart;
233 // `displayingFullScreenVideo` is used in `onCreate()` and `onResume()`.
234 private boolean displayingFullScreenVideo;
236 // `orbotStatusBroadcastReceiver` is used in `onCreate()` and `onDestroy()`.
237 private BroadcastReceiver orbotStatusBroadcastReceiver;
239 // `waitingForOrbot` is used in `onCreate()`, `onResume()`, and `applyProxyThroughOrbot()`.
240 private boolean waitingForOrbot;
242 // The action bar drawer toggle is initialized in `onCreate()` and used in `onResume()`.
243 private ActionBarDrawerToggle actionBarDrawerToggle;
245 // The color spans are used in `onCreate()` and `highlightUrlText()`.
246 private ForegroundColorSpan redColorSpan;
247 private ForegroundColorSpan initialGrayColorSpan;
248 private ForegroundColorSpan finalGrayColorSpan;
250 // The drawer header padding variables are used in `onCreate()` and `onConfigurationChanged()`.
251 private int drawerHeaderPaddingLeftAndRight;
252 private int drawerHeaderPaddingTop;
253 private int drawerHeaderPaddingBottom;
255 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onDestroy`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`,
256 // and `loadBookmarksFolder()`.
257 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
259 // `bookmarksCursor` is used in `onDestroy()`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
260 private Cursor bookmarksCursor;
262 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
263 private CursorAdapter bookmarksCursorAdapter;
265 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
266 private String oldFolderNameString;
268 // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
269 private ValueCallback<Uri[]> fileChooserCallback;
271 // The download strings are used in `onCreate()`, `onRequestPermissionResult()` and `initializeWebView()`.
272 private String downloadUrl;
273 private String downloadContentDisposition;
274 private long downloadContentLength;
276 // `downloadImageUrl` is used in `onCreateContextMenu()` and `onRequestPermissionResult()`.
277 private String downloadImageUrl;
279 // The request codes are used in `onCreate()`, `onCreateContextMenu()`, `onCloseDownloadLocationPermissionDialog()`, `onRequestPermissionResult()`, and `initializeWebView()`.
280 private final int DOWNLOAD_FILE_REQUEST_CODE = 1;
281 private final int DOWNLOAD_IMAGE_REQUEST_CODE = 2;
284 // Remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
285 @SuppressLint("ClickableViewAccessibility")
286 protected void onCreate(Bundle savedInstanceState) {
287 // Get a handle for the shared preferences.
288 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
290 // Get the theme and screenshot preferences.
291 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
292 boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
294 // Disable screenshots if not allowed.
295 if (!allowScreenshots) {
296 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
299 // Set the activity theme.
301 setTheme(R.style.PrivacyBrowserDark);
303 setTheme(R.style.PrivacyBrowserLight);
306 // Run the default commands.
307 super.onCreate(savedInstanceState);
309 // Set the content view.
310 setContentView(R.layout.main_framelayout);
312 // Get a handle for the input method.
313 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
315 // Remove the lint warning below that the input method manager might be null.
316 assert inputMethodManager != null;
318 // Get a handle for the toolbar.
319 Toolbar toolbar = findViewById(R.id.toolbar);
321 // Set the action bar. `SupportActionBar` must be used until the minimum API is >= 21.
322 setSupportActionBar(toolbar);
324 // Get a handle for the action bar.
325 ActionBar actionBar = getSupportActionBar();
327 // This is needed to get rid of the Android Studio warning that the action bar might be null.
328 assert actionBar != null;
330 // Add the custom layout, which shows the URL text bar.
331 actionBar.setCustomView(R.layout.url_app_bar);
332 actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
334 // Initialize the foreground color spans for highlighting the URLs. We have to use the deprecated `getColor()` until API >= 23.
335 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
336 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
337 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
339 // Get handles for the URL views.
340 EditText urlEditText = findViewById(R.id.url_edittext);
342 // Remove the formatting from `urlTextBar` when the user is editing the text.
343 urlEditText.setOnFocusChangeListener((View v, boolean hasFocus) -> {
344 if (hasFocus) { // The user is editing the URL text box.
345 // Remove the highlighting.
346 urlEditText.getText().removeSpan(redColorSpan);
347 urlEditText.getText().removeSpan(initialGrayColorSpan);
348 urlEditText.getText().removeSpan(finalGrayColorSpan);
349 } else { // The user has stopped editing the URL text box.
350 // Move to the beginning of the string.
351 urlEditText.setSelection(0);
353 // Reapply the highlighting.
358 // Set the go button on the keyboard to load the URL in `urlTextBox`.
359 urlEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
360 // If the event is a key-down event on the `enter` button, load the URL.
361 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
362 // Load the URL into the mainWebView and consume the event.
363 loadUrlFromTextBox();
365 // If the enter key was pressed, consume the event.
368 // If any other key was pressed, do not consume the event.
373 // Initialize the Orbot status and the waiting for Orbot trackers.
374 orbotStatus = "unknown";
375 waitingForOrbot = false;
377 // Create an Orbot status `BroadcastReceiver`.
378 orbotStatusBroadcastReceiver = new BroadcastReceiver() {
380 public void onReceive(Context context, Intent intent) {
381 // Store the content of the status message in `orbotStatus`.
382 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
384 // If Privacy Browser is waiting on Orbot, load the website now that Orbot is connected.
385 if (orbotStatus.equals("ON") && waitingForOrbot) {
386 // Reset the waiting for Orbot status.
387 waitingForOrbot = false;
389 // Get the intent that started the app.
390 Intent launchingIntent = getIntent();
392 // Get the information from the intent.
393 String launchingIntentAction = launchingIntent.getAction();
394 Uri launchingIntentUriData = launchingIntent.getData();
396 // If the intent action is a web search, perform the search.
397 if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) {
398 // Create an encoded URL string.
399 String encodedUrlString;
401 // Sanitize the search input and convert it to a search.
403 encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
404 } catch (UnsupportedEncodingException exception) {
405 encodedUrlString = "";
408 // Load the completed search URL.
409 loadUrl(searchURL + encodedUrlString);
410 } else if (launchingIntentUriData != null){ // Check to see if the intent contains a new URL.
411 // Load the URL from the intent.
412 loadUrl(launchingIntentUriData.toString());
413 } else { // The is no URL in the intent.
414 // Select the homepage based on the proxy through Orbot status.
415 if (proxyThroughOrbot) {
416 // Load the Tor homepage.
417 loadUrl(sharedPreferences.getString("tor_homepage", getString(R.string.tor_homepage_default_value)));
419 // Load the normal homepage.
420 loadUrl(sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
427 // Register `orbotStatusBroadcastReceiver` on `this` context.
428 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
430 // Instantiate the blocklist helper.
431 BlockListHelper blockListHelper = new BlockListHelper();
433 // Parse the block lists.
434 easyList = blockListHelper.parseBlockList(getAssets(), "blocklists/easylist.txt");
435 easyPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/easyprivacy.txt");
436 fanboysAnnoyanceList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-annoyance.txt");
437 fanboysSocialList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-social.txt");
438 ultraPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/ultraprivacy.txt");
440 // Get handles for views that need to be modified.
441 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
442 NavigationView navigationView = findViewById(R.id.navigationview);
443 TabLayout tabLayout = findViewById(R.id.tablayout);
444 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
445 ViewPager webViewPager = findViewById(R.id.webviewpager);
446 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
447 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
448 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
449 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
450 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
452 // Listen for touches on the navigation menu.
453 navigationView.setNavigationItemSelectedListener(this);
455 // Get handles for the navigation menu and the back and forward menu items. The menu is zero-based.
456 Menu navigationMenu = navigationView.getMenu();
457 MenuItem navigationCloseTabMenuItem = navigationMenu.getItem(0);
458 MenuItem navigationBackMenuItem = navigationMenu.getItem(3);
459 MenuItem navigationForwardMenuItem = navigationMenu.getItem(4);
460 MenuItem navigationHistoryMenuItem = navigationMenu.getItem(5);
461 MenuItem navigationRequestsMenuItem = navigationMenu.getItem(6);
463 // Initialize the web view pager adapter.
464 webViewPagerAdapter = new WebViewPagerAdapter(getSupportFragmentManager());
466 // Set the pager adapter on the web view pager.
467 webViewPager.setAdapter(webViewPagerAdapter);
469 // Store up to 100 tabs in memory.
470 webViewPager.setOffscreenPageLimit(100);
472 // Update the web view pager every time a tab is modified.
473 webViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
475 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
480 public void onPageSelected(int position) {
481 // Close the find on page bar if it is open.
482 closeFindOnPage(null);
484 // Set the current WebView.
485 setCurrentWebView(position);
487 // Select the corresponding tab if it does not match the currently selected page. This will happen if the page was scrolled via swiping in the view pager or by creating a new tab.
488 if (tabLayout.getSelectedTabPosition() != position) {
489 // Create a handler to select the tab.
490 Handler selectTabHandler = new Handler();
492 // Create a runnable select the new tab.
493 Runnable selectTabRunnable = () -> {
494 // Get a handle for the tab.
495 TabLayout.Tab tab = tabLayout.getTabAt(position);
497 // Assert that the tab is not null.
504 // Select the tab layout after 100 milliseconds, which leaves enough time for a new tab to be created.
505 selectTabHandler.postDelayed(selectTabRunnable, 100);
510 public void onPageScrollStateChanged(int state) {
515 // Display the View SSL Certificate dialog when the currently selected tab is reselected.
516 tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
518 public void onTabSelected(TabLayout.Tab tab) {
519 // Select the same page in the view pager.
520 webViewPager.setCurrentItem(tab.getPosition());
524 public void onTabUnselected(TabLayout.Tab tab) {
529 public void onTabReselected(TabLayout.Tab tab) {
530 // Instantiate the View SSL Certificate dialog.
531 DialogFragment viewSslCertificateDialogFragment = ViewSslCertificateDialog.displayDialog(currentWebView.getWebViewFragmentId());
533 // Display the View SSL Certificate dialog.
534 viewSslCertificateDialogFragment.show(getSupportFragmentManager(), getString(R.string.view_ssl_certificate));
538 // Add the first tab.
541 // 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.
542 // The deprecated `getResources().getDrawable()` must be used until the minimum API >= 21 and and `getResources().getColor()` must be used until the minimum API >= 23.
544 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
545 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
546 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
547 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
549 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
550 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
551 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
552 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
555 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
556 launchBookmarksActivityFab.setOnClickListener(v -> {
557 // Get a copy of the favorite icon bitmap.
558 Bitmap favoriteIconBitmap = currentWebView.getFavoriteOrDefaultIcon();
560 // Create a favorite icon byte array output stream.
561 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
563 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
564 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
566 // Convert the favorite icon byte array stream to a byte array.
567 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
569 // Create an intent to launch the bookmarks activity.
570 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
572 // Add the extra information to the intent.
573 bookmarksIntent.putExtra("current_url", currentWebView.getUrl());
574 bookmarksIntent.putExtra("current_title", currentWebView.getTitle());
575 bookmarksIntent.putExtra("current_folder", currentBookmarksFolder);
576 bookmarksIntent.putExtra("favorite_icon_byte_array", favoriteIconByteArray);
579 startActivity(bookmarksIntent);
582 // Set the create new bookmark folder FAB to display an alert dialog.
583 createBookmarkFolderFab.setOnClickListener(v -> {
584 // Create a create bookmark folder dialog.
585 DialogFragment createBookmarkFolderDialog = CreateBookmarkFolderDialog.createBookmarkFolder(currentWebView.getFavoriteOrDefaultIcon());
587 // Show the create bookmark folder dialog.
588 createBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.create_folder));
591 // Set the create new bookmark FAB to display an alert dialog.
592 createBookmarkFab.setOnClickListener(view -> {
593 // Instantiate the create bookmark dialog.
594 DialogFragment createBookmarkDialog = CreateBookmarkDialog.createBookmark(currentWebView.getUrl(), currentWebView.getTitle(), currentWebView.getFavoriteOrDefaultIcon());
596 // Display the create bookmark dialog.
597 createBookmarkDialog.show(getSupportFragmentManager(), getString(R.string.create_bookmark));
600 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
601 findOnPageEditText.addTextChangedListener(new TextWatcher() {
603 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
608 public void onTextChanged(CharSequence s, int start, int before, int count) {
613 public void afterTextChanged(Editable s) {
614 // Search for the text in `mainWebView`.
615 currentWebView.findAllAsync(findOnPageEditText.getText().toString());
619 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
620 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
621 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
622 // Hide the soft keyboard.
623 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
625 // Consume the event.
627 } else { // A different key was pressed.
628 // Do not consume the event.
633 // Implement swipe to refresh.
634 swipeRefreshLayout.setOnRefreshListener(() -> currentWebView.reload());
636 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
637 swipeRefreshLayout.setProgressViewOffset(false, swipeRefreshLayout.getProgressViewStartOffset() - 10, swipeRefreshLayout.getProgressViewEndOffset());
639 // Set the swipe to refresh color according to the theme.
641 swipeRefreshLayout.setColorSchemeResources(R.color.blue_800);
642 swipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.gray_850);
644 swipeRefreshLayout.setColorSchemeResources(R.color.blue_500);
647 // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
648 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
649 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
651 // Initialize the bookmarks database helper. The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
652 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
654 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
655 currentBookmarksFolder = "";
657 // Load the home folder, which is `""` in the database.
658 loadBookmarksFolder();
660 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
661 // Convert the id from long to int to match the format of the bookmarks database.
662 int databaseID = (int) id;
664 // Get the bookmark cursor for this ID and move it to the first row.
665 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseID);
666 bookmarkCursor.moveToFirst();
668 // Act upon the bookmark according to the type.
669 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
670 // Store the new folder name in `currentBookmarksFolder`.
671 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
673 // Load the new folder.
674 loadBookmarksFolder();
675 } else { // The selected bookmark is not a folder.
676 // Load the bookmark URL.
677 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
679 // Close the bookmarks drawer.
680 drawerLayout.closeDrawer(GravityCompat.END);
683 // Close the `Cursor`.
684 bookmarkCursor.close();
687 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
688 // Convert the database ID from `long` to `int`.
689 int databaseId = (int) id;
691 // Find out if the selected bookmark is a folder.
692 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
695 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
696 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
698 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
699 DialogFragment editBookmarkFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId, currentWebView.getFavoriteOrDefaultIcon());
700 editBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.edit_folder));
702 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
703 DialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId, currentWebView.getFavoriteOrDefaultIcon());
704 editBookmarkDialog.show(getSupportFragmentManager(), getString(R.string.edit_bookmark));
707 // Consume the event.
711 // Get the status bar pixel size.
712 int statusBarResourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
713 int statusBarPixelSize = getResources().getDimensionPixelSize(statusBarResourceId);
715 // Get the resource density.
716 float screenDensity = getResources().getDisplayMetrics().density;
718 // Calculate the drawer header padding. This is used to move the text in the drawer headers below any cutouts.
719 drawerHeaderPaddingLeftAndRight = (int) (15 * screenDensity);
720 drawerHeaderPaddingTop = statusBarPixelSize + (int) (4 * screenDensity);
721 drawerHeaderPaddingBottom = (int) (8 * screenDensity);
723 // The drawer listener is used to update the navigation menu.`
724 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
726 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
730 public void onDrawerOpened(@NonNull View drawerView) {
734 public void onDrawerClosed(@NonNull View drawerView) {
738 public void onDrawerStateChanged(int newState) {
739 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // A drawer is opening or closing.
740 // Get handles for the drawer headers.
741 TextView navigationHeaderTextView = findViewById(R.id.navigationText);
742 TextView bookmarksHeaderTextView = findViewById(R.id.bookmarks_title_textview);
744 // 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.
745 if (navigationHeaderTextView != null) {
746 navigationHeaderTextView.setPadding(drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingTop, drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingBottom);
749 // 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.
750 if (bookmarksHeaderTextView != null) {
751 bookmarksHeaderTextView.setPadding(drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingTop, drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingBottom);
754 // Update the navigation menu items.
755 navigationCloseTabMenuItem.setEnabled(tabLayout.getTabCount() > 1);
756 navigationBackMenuItem.setEnabled(currentWebView.canGoBack());
757 navigationForwardMenuItem.setEnabled(currentWebView.canGoForward());
758 navigationHistoryMenuItem.setEnabled((currentWebView.canGoBack() || currentWebView.canGoForward()));
759 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
761 // Hide the keyboard (if displayed).
762 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
764 // 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.
765 urlEditText.clearFocus();
766 currentWebView.clearFocus();
771 // Create the hamburger icon at the start of the AppBar.
772 actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
774 // 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).
775 customHeaders.put("X-Requested-With", "");
777 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
778 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
780 // Inflate a bare WebView to get the default user agent. It is not used to render content on the screen.
781 @SuppressLint("InflateParams") View webViewLayout = getLayoutInflater().inflate(R.layout.bare_webview, null, false);
783 // Get a handle for the WebView.
784 WebView bareWebView = webViewLayout.findViewById(R.id.bare_webview);
786 // Store the default user agent.
787 webViewDefaultUserAgent = bareWebView.getSettings().getUserAgentString();
789 // Destroy the bare WebView.
790 bareWebView.destroy();
794 protected void onNewIntent(Intent intent) {
795 // Get the information from the intent.
796 String intentAction = intent.getAction();
797 Uri intentUriData = intent.getData();
799 // 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.
800 if (intentUriData != null) {
801 // Sets the new intent as the activity intent, which replaces the one that originally started the app.
807 // Create a URL string.
810 // If the intent action is a web search, perform the search.
811 if ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH)) {
812 // Create an encoded URL string.
813 String encodedUrlString;
815 // Sanitize the search input and convert it to a search.
817 encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
818 } catch (UnsupportedEncodingException exception) {
819 encodedUrlString = "";
822 // Add the base search URL.
823 url = searchURL + encodedUrlString;
824 } else { // The intent should contain a URL.
825 // Set the intent data as the URL.
826 url = intentUriData.toString();
832 // Get a handle for the drawer layout.
833 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
835 // Close the navigation drawer if it is open.
836 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
837 drawerLayout.closeDrawer(GravityCompat.START);
840 // Close the bookmarks drawer if it is open.
841 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
842 drawerLayout.closeDrawer(GravityCompat.END);
845 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
846 currentWebView.requestFocus();
851 public void onRestart() {
852 // Run the default commands.
855 // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
856 if (proxyThroughOrbot) {
857 // Request Orbot to start. If Orbot is already running no hard will be caused by this request.
858 Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
860 // Send the intent to the Orbot package.
861 orbotIntent.setPackage("org.torproject.android");
864 sendBroadcast(orbotIntent);
867 // Apply the app settings if returning from the Settings activity.
868 if (reapplyAppSettingsOnRestart) {
869 // Reset the reapply app settings on restart tracker.
870 reapplyAppSettingsOnRestart = false;
872 // Apply the app settings.
876 // Apply the domain settings if returning from the settings or domains activity.
877 if (reapplyDomainSettingsOnRestart) {
878 // Reset the reapply domain settings on restart tracker.
879 reapplyDomainSettingsOnRestart = false;
881 // Reapply the domain settings for each tab.
882 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
883 // Get the WebView tab fragment.
884 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
886 // Get the fragment view.
887 View fragmentView = webViewTabFragment.getView();
889 // Only reload the WebViews if they exist.
890 if (fragmentView != null) {
891 // Get the nested scroll WebView from the tab fragment.
892 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
894 // Reset the current domain name so the domain settings will be reapplied.
895 nestedScrollWebView.resetCurrentDomainName();
897 // Reapply the domain settings.
898 applyDomainSettings(nestedScrollWebView, nestedScrollWebView.getUrl(), false, true);
903 // Load the URL on restart (used when loading a bookmark).
904 if (loadUrlOnRestart) {
905 // Load the specified URL.
906 loadUrl(urlToLoadOnRestart);
908 // Reset the load on restart tracker.
909 loadUrlOnRestart = false;
912 // Update the bookmarks drawer if returning from the Bookmarks activity.
913 if (restartFromBookmarksActivity) {
914 // Get a handle for the drawer layout.
915 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
917 // Close the bookmarks drawer.
918 drawerLayout.closeDrawer(GravityCompat.END);
920 // Reload the bookmarks drawer.
921 loadBookmarksFolder();
923 // Reset `restartFromBookmarksActivity`.
924 restartFromBookmarksActivity = false;
927 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
928 updatePrivacyIcons(true);
931 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
933 public void onResume() {
934 // Run the default commands.
937 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
938 // Get the WebView tab fragment.
939 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
941 // Get the fragment view.
942 View fragmentView = webViewTabFragment.getView();
944 // Only resume the WebViews if they exist (they won't when the app is first created).
945 if (fragmentView != null) {
946 // Get the nested scroll WebView from the tab fragment.
947 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
949 // Resume the nested scroll WebView JavaScript timers.
950 nestedScrollWebView.resumeTimers();
952 // Resume the nested scroll WebView.
953 nestedScrollWebView.onResume();
957 // Display a message to the user if waiting for Orbot.
958 if (waitingForOrbot && !orbotStatus.equals("ON")) {
959 // Disable the wide view port so that the waiting for Orbot text is displayed correctly.
960 currentWebView.getSettings().setUseWideViewPort(false);
962 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
963 currentWebView.loadData("<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>", "text/html", null);
966 if (displayingFullScreenVideo || inFullScreenBrowsingMode) {
967 // Get a handle for the root frame layouts.
968 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
970 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
971 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
973 /* Hide the system bars.
974 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
975 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
976 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
977 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
979 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
980 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
981 } else if (BuildConfig.FLAVOR.contentEquals("free")) { // Resume the adView for the free flavor.
983 AdHelper.resumeAd(findViewById(R.id.adview));
988 public void onPause() {
989 // Run the default commands.
992 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
993 // Get the WebView tab fragment.
994 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
996 // Get the fragment view.
997 View fragmentView = webViewTabFragment.getView();
999 // Only pause the WebViews if they exist (they won't when the app is first created).
1000 if (fragmentView != null) {
1001 // Get the nested scroll WebView from the tab fragment.
1002 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
1004 // Pause the nested scroll WebView.
1005 nestedScrollWebView.onPause();
1007 // Pause the nested scroll WebView JavaScript timers.
1008 nestedScrollWebView.pauseTimers();
1012 // Pause the ad or it will continue to consume resources in the background on the free flavor.
1013 if (BuildConfig.FLAVOR.contentEquals("free")) {
1015 AdHelper.pauseAd(findViewById(R.id.adview));
1020 public void onDestroy() {
1021 // Unregister the Orbot status broadcast receiver.
1022 this.unregisterReceiver(orbotStatusBroadcastReceiver);
1024 // Close the bookmarks cursor and database.
1025 bookmarksCursor.close();
1026 bookmarksDatabaseHelper.close();
1028 // Run the default commands.
1033 public boolean onCreateOptionsMenu(Menu menu) {
1034 // Inflate the menu. This adds items to the action bar if it is present.
1035 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1037 // Store a handle for the options menu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons()`.
1040 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1041 updatePrivacyIcons(false);
1043 // Get handles for the menu items.
1044 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1045 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1046 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1047 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
1048 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
1049 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1050 MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
1052 // Only display third-party cookies if API >= 21
1053 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1055 // Only display the form data menu items if the API < 26.
1056 toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1057 clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1059 // Disable the clear form data menu item if the API >= 26 so that the status of the main Clear Data is calculated correctly.
1060 clearFormDataMenuItem.setEnabled(Build.VERSION.SDK_INT < 26);
1062 // Only show Ad Consent if this is the free flavor.
1063 adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
1065 // Get the shared preference values.
1066 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1068 // Get the dark theme and app bar preferences..
1069 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
1070 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
1072 // 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.
1073 if (displayAdditionalAppBarIcons) {
1074 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1075 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1076 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
1077 } else { //Do not display the additional icons.
1078 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1079 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1080 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1083 // Replace Refresh with Stop if a URL is already loading.
1084 if (currentWebView != null && currentWebView.getProgress() != 100) {
1086 refreshMenuItem.setTitle(R.string.stop);
1088 // If the icon is displayed in the AppBar, set it according to the theme.
1089 if (displayAdditionalAppBarIcons) {
1091 refreshMenuItem.setIcon(R.drawable.close_dark);
1093 refreshMenuItem.setIcon(R.drawable.close_light);
1102 public boolean onPrepareOptionsMenu(Menu menu) {
1103 // Get handles for the menu items.
1104 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
1105 MenuItem firstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1106 MenuItem thirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1107 MenuItem domStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1108 MenuItem saveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
1109 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
1110 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1111 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1112 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
1113 MenuItem blocklistsMenuItem = menu.findItem(R.id.blocklists);
1114 MenuItem easyListMenuItem = menu.findItem(R.id.easylist);
1115 MenuItem easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
1116 MenuItem fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
1117 MenuItem fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
1118 MenuItem ultraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
1119 MenuItem blockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
1120 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1121 MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
1122 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1123 MenuItem nightModeMenuItem = menu.findItem(R.id.night_mode);
1124 MenuItem proxyThroughOrbotMenuItem = menu.findItem(R.id.proxy_through_orbot);
1126 // Get a handle for the cookie manager.
1127 CookieManager cookieManager = CookieManager.getInstance();
1129 // Initialize the current user agent string and the font size.
1130 String currentUserAgent = getString(R.string.user_agent_privacy_browser);
1133 // 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.
1134 if (currentWebView != null) {
1135 // Set the add or edit domain text.
1136 if (currentWebView.getDomainSettingsApplied()) {
1137 addOrEditDomain.setTitle(R.string.edit_domain_settings);
1139 addOrEditDomain.setTitle(R.string.add_domain_settings);
1142 // Get the current user agent from the WebView.
1143 currentUserAgent = currentWebView.getSettings().getUserAgentString();
1145 // Get the current font size from the
1146 fontSize = currentWebView.getSettings().getTextZoom();
1148 // Set the status of the menu item checkboxes.
1149 domStorageMenuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1150 saveFormDataMenuItem.setChecked(currentWebView.getSettings().getSaveFormData()); // Form data can be removed once the minimum API >= 26.
1151 easyListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST));
1152 easyPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY));
1153 fanboysAnnoyanceListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1154 fanboysSocialBlockingListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1155 ultraPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY));
1156 blockAllThirdPartyRequestsMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1157 swipeToRefreshMenuItem.setChecked(currentWebView.getSwipeToRefresh());
1158 displayImagesMenuItem.setChecked(currentWebView.getSettings().getLoadsImagesAutomatically());
1159 nightModeMenuItem.setChecked(currentWebView.getNightMode());
1161 // Initialize the display names for the blocklists with the number of blocked requests.
1162 blocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
1163 easyListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASY_LIST) + " - " + getString(R.string.easylist));
1164 easyPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASY_PRIVACY) + " - " + getString(R.string.easyprivacy));
1165 fanboysAnnoyanceListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " + getString(R.string.fanboys_annoyance_list));
1166 fanboysSocialBlockingListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " + getString(R.string.fanboys_social_blocking_list));
1167 ultraPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRA_PRIVACY) + " - " + getString(R.string.ultraprivacy));
1168 blockAllThirdPartyRequestsMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " + getString(R.string.block_all_third_party_requests));
1170 // Only modify third-party cookies if the API >= 21.
1171 if (Build.VERSION.SDK_INT >= 21) {
1172 // Set the status of the third-party cookies checkbox.
1173 thirdPartyCookiesMenuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
1175 // Enable third-party cookies if first-party cookies are enabled.
1176 thirdPartyCookiesMenuItem.setEnabled(cookieManager.acceptCookie());
1179 // Enable DOM Storage if JavaScript is enabled.
1180 domStorageMenuItem.setEnabled(currentWebView.getSettings().getJavaScriptEnabled());
1183 // Set the status of the menu item checkboxes.
1184 firstPartyCookiesMenuItem.setChecked(cookieManager.acceptCookie());
1185 proxyThroughOrbotMenuItem.setChecked(proxyThroughOrbot);
1187 // Enable Clear Cookies if there are any.
1188 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1190 // 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`.
1191 String privateDataDirectoryString = getApplicationInfo().dataDir;
1193 // Get a count of the number of files in the Local Storage directory.
1194 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1195 int localStorageDirectoryNumberOfFiles = 0;
1196 if (localStorageDirectory.exists()) {
1197 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1200 // Get a count of the number of files in the IndexedDB directory.
1201 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1202 int indexedDBDirectoryNumberOfFiles = 0;
1203 if (indexedDBDirectory.exists()) {
1204 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1207 // Enable Clear DOM Storage if there is any.
1208 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1210 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
1211 if (Build.VERSION.SDK_INT < 26) {
1212 // Get the WebView database.
1213 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1215 // Enable the clear form data menu item if there is anything to clear.
1216 clearFormDataMenuItem.setEnabled(webViewDatabase.hasFormData());
1219 // Enable Clear Data if any of the submenu items are enabled.
1220 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
1222 // Disable Fanboy's Social Blocking List menu item if Fanboy's Annoyance List is checked.
1223 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListMenuItem.isChecked());
1225 // Select the current user agent menu item. A switch statement cannot be used because the user agents are not compile time constants.
1226 if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) { // Privacy Browser.
1227 menu.findItem(R.id.user_agent_privacy_browser).setChecked(true);
1228 } else if (currentUserAgent.equals(webViewDefaultUserAgent)) { // WebView Default.
1229 menu.findItem(R.id.user_agent_webview_default).setChecked(true);
1230 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) { // Firefox on Android.
1231 menu.findItem(R.id.user_agent_firefox_on_android).setChecked(true);
1232 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) { // Chrome on Android.
1233 menu.findItem(R.id.user_agent_chrome_on_android).setChecked(true);
1234 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) { // Safari on iOS.
1235 menu.findItem(R.id.user_agent_safari_on_ios).setChecked(true);
1236 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) { // Firefox on Linux.
1237 menu.findItem(R.id.user_agent_firefox_on_linux).setChecked(true);
1238 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) { // Chromium on Linux.
1239 menu.findItem(R.id.user_agent_chromium_on_linux).setChecked(true);
1240 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) { // Firefox on Windows.
1241 menu.findItem(R.id.user_agent_firefox_on_windows).setChecked(true);
1242 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) { // Chrome on Windows.
1243 menu.findItem(R.id.user_agent_chrome_on_windows).setChecked(true);
1244 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) { // Edge on Windows.
1245 menu.findItem(R.id.user_agent_edge_on_windows).setChecked(true);
1246 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) { // Internet Explorer on Windows.
1247 menu.findItem(R.id.user_agent_internet_explorer_on_windows).setChecked(true);
1248 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) { // Safari on macOS.
1249 menu.findItem(R.id.user_agent_safari_on_macos).setChecked(true);
1250 } else { // Custom user agent.
1251 menu.findItem(R.id.user_agent_custom).setChecked(true);
1254 // Instantiate the font size title and the selected font size menu item.
1255 String fontSizeTitle;
1256 MenuItem selectedFontSizeMenuItem;
1258 // Prepare the font size title and current size menu item.
1261 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
1262 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1266 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
1267 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1271 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
1272 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1276 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1277 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1281 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
1282 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1286 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
1287 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1291 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
1292 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1296 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
1297 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1301 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1302 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1306 // Set the font size title and select the current size menu item.
1307 fontSizeMenuItem.setTitle(fontSizeTitle);
1308 selectedFontSizeMenuItem.setChecked(true);
1310 // Run all the other default commands.
1311 super.onPrepareOptionsMenu(menu);
1313 // Display the menu.
1318 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1319 @SuppressLint("SetJavaScriptEnabled")
1320 public boolean onOptionsItemSelected(MenuItem menuItem) {
1321 // Reenter full screen browsing mode if it was interrupted by the options menu. <https://redmine.stoutner.com/issues/389>
1322 if (inFullScreenBrowsingMode) {
1323 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
1324 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1326 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
1328 /* Hide the system bars.
1329 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1330 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
1331 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1332 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1334 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
1335 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1338 // Get the selected menu item ID.
1339 int menuItemId = menuItem.getItemId();
1341 // Get a handle for the shared preferences.
1342 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1344 // Get a handle for the cookie manager.
1345 CookieManager cookieManager = CookieManager.getInstance();
1347 // Run the commands that correlate to the selected menu item.
1348 switch (menuItemId) {
1349 case R.id.toggle_javascript:
1350 // Toggle the JavaScript status.
1351 currentWebView.getSettings().setJavaScriptEnabled(!currentWebView.getSettings().getJavaScriptEnabled());
1353 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1354 updatePrivacyIcons(true);
1356 // Display a `Snackbar`.
1357 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScrip is enabled.
1358 Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1359 } else if (cookieManager.acceptCookie()) { // JavaScript is disabled, but first-party cookies are enabled.
1360 Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1361 } else { // Privacy mode.
1362 Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1365 // Reload the current WebView.
1366 currentWebView.reload();
1369 case R.id.add_or_edit_domain:
1370 if (currentWebView.getDomainSettingsApplied()) { // Edit the current domain settings.
1371 // Reapply the domain settings on returning to `MainWebViewActivity`.
1372 reapplyDomainSettingsOnRestart = true;
1374 // Create an intent to launch the domains activity.
1375 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1377 // Add the extra information to the intent.
1378 domainsIntent.putExtra("load_domain", currentWebView.getDomainSettingsDatabaseId());
1379 domainsIntent.putExtra("close_on_back", true);
1380 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1382 // Get the current certificate.
1383 SslCertificate sslCertificate = currentWebView.getCertificate();
1385 // Check to see if the SSL certificate is populated.
1386 if (sslCertificate != null) {
1387 // Extract the certificate to strings.
1388 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1389 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1390 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1391 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1392 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1393 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1394 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1395 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1397 // Add the certificate to the intent.
1398 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1399 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1400 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1401 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1402 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1403 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1404 domainsIntent.putExtra("ssl_start_date", startDateLong);
1405 domainsIntent.putExtra("ssl_end_date", endDateLong);
1408 // Check to see if the current IP addresses have been received.
1409 if (currentWebView.hasCurrentIpAddresses()) {
1410 // Add the current IP addresses to the intent.
1411 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1415 startActivity(domainsIntent);
1416 } else { // Add a new domain.
1417 // Apply the new domain settings on returning to `MainWebViewActivity`.
1418 reapplyDomainSettingsOnRestart = true;
1420 // Get the current domain
1421 Uri currentUri = Uri.parse(currentWebView.getUrl());
1422 String currentDomain = currentUri.getHost();
1424 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1425 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1427 // Create the domain and store the database ID.
1428 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1430 // Create an intent to launch the domains activity.
1431 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1433 // Add the extra information to the intent.
1434 domainsIntent.putExtra("load_domain", newDomainDatabaseId);
1435 domainsIntent.putExtra("close_on_back", true);
1436 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1438 // Get the current certificate.
1439 SslCertificate sslCertificate = currentWebView.getCertificate();
1441 // Check to see if the SSL certificate is populated.
1442 if (sslCertificate != null) {
1443 // Extract the certificate to strings.
1444 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1445 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1446 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1447 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1448 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1449 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1450 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1451 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1453 // Add the certificate to the intent.
1454 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1455 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1456 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1457 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1458 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1459 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1460 domainsIntent.putExtra("ssl_start_date", startDateLong);
1461 domainsIntent.putExtra("ssl_end_date", endDateLong);
1464 // Check to see if the current IP addresses have been received.
1465 if (currentWebView.hasCurrentIpAddresses()) {
1466 // Add the current IP addresses to the intent.
1467 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1471 startActivity(domainsIntent);
1475 case R.id.toggle_first_party_cookies:
1476 // Switch the first-party cookie status.
1477 cookieManager.setAcceptCookie(!cookieManager.acceptCookie());
1479 // Store the first-party cookie status.
1480 currentWebView.setAcceptFirstPartyCookies(cookieManager.acceptCookie());
1482 // Update the menu checkbox.
1483 menuItem.setChecked(cookieManager.acceptCookie());
1485 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1486 updatePrivacyIcons(true);
1488 // Display a snackbar.
1489 if (cookieManager.acceptCookie()) { // First-party cookies are enabled.
1490 Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1491 } else if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is still enabled.
1492 Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1493 } else { // Privacy mode.
1494 Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1497 // Reload the current WebView.
1498 currentWebView.reload();
1501 case R.id.toggle_third_party_cookies:
1502 if (Build.VERSION.SDK_INT >= 21) {
1503 // Switch the status of thirdPartyCookiesEnabled.
1504 cookieManager.setAcceptThirdPartyCookies(currentWebView, !cookieManager.acceptThirdPartyCookies(currentWebView));
1506 // Update the menu checkbox.
1507 menuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
1509 // Display a snackbar.
1510 if (cookieManager.acceptThirdPartyCookies(currentWebView)) {
1511 Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1513 Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1516 // Reload the current WebView.
1517 currentWebView.reload();
1518 } // Else do nothing because SDK < 21.
1521 case R.id.toggle_dom_storage:
1522 // Toggle the status of domStorageEnabled.
1523 currentWebView.getSettings().setDomStorageEnabled(!currentWebView.getSettings().getDomStorageEnabled());
1525 // Update the menu checkbox.
1526 menuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1528 // Update the privacy icon. `true` refreshes the app bar icons.
1529 updatePrivacyIcons(true);
1531 // Display a snackbar.
1532 if (currentWebView.getSettings().getDomStorageEnabled()) {
1533 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1535 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1538 // Reload the current WebView.
1539 currentWebView.reload();
1542 // Form data can be removed once the minimum API >= 26.
1543 case R.id.toggle_save_form_data:
1544 // Switch the status of saveFormDataEnabled.
1545 currentWebView.getSettings().setSaveFormData(!currentWebView.getSettings().getSaveFormData());
1547 // Update the menu checkbox.
1548 menuItem.setChecked(currentWebView.getSettings().getSaveFormData());
1550 // Display a snackbar.
1551 if (currentWebView.getSettings().getSaveFormData()) {
1552 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1554 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1557 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1558 updatePrivacyIcons(true);
1560 // Reload the current WebView.
1561 currentWebView.reload();
1564 case R.id.clear_cookies:
1565 Snackbar.make(findViewById(R.id.webviewpager), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1566 .setAction(R.string.undo, v -> {
1567 // Do nothing because everything will be handled by `onDismissed()` below.
1569 .addCallback(new Snackbar.Callback() {
1570 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1572 public void onDismissed(Snackbar snackbar, int event) {
1573 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1574 // Delete the cookies, which command varies by SDK.
1575 if (Build.VERSION.SDK_INT < 21) {
1576 cookieManager.removeAllCookie();
1578 cookieManager.removeAllCookies(null);
1586 case R.id.clear_dom_storage:
1587 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1588 .setAction(R.string.undo, v -> {
1589 // Do nothing because everything will be handled by `onDismissed()` below.
1591 .addCallback(new Snackbar.Callback() {
1592 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1594 public void onDismissed(Snackbar snackbar, int event) {
1595 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1596 // Delete the DOM Storage.
1597 WebStorage webStorage = WebStorage.getInstance();
1598 webStorage.deleteAllData();
1600 // Initialize a handler to manually delete the DOM storage files and directories.
1601 Handler deleteDomStorageHandler = new Handler();
1603 // Setup a runnable to manually delete the DOM storage files and directories.
1604 Runnable deleteDomStorageRunnable = () -> {
1606 // Get a handle for the runtime.
1607 Runtime runtime = Runtime.getRuntime();
1609 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
1610 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
1611 String privateDataDirectoryString = getApplicationInfo().dataDir;
1613 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1614 Process deleteLocalStorageProcess = runtime.exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1616 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1617 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1618 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1619 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1620 Process deleteDatabasesProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1622 // Wait for the processes to finish.
1623 deleteLocalStorageProcess.waitFor();
1624 deleteIndexProcess.waitFor();
1625 deleteQuotaManagerProcess.waitFor();
1626 deleteQuotaManagerJournalProcess.waitFor();
1627 deleteDatabasesProcess.waitFor();
1628 } catch (Exception exception) {
1629 // Do nothing if an error is thrown.
1633 // Manually delete the DOM storage files after 200 milliseconds.
1634 deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200);
1641 // Form data can be remove once the minimum API >= 26.
1642 case R.id.clear_form_data:
1643 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1644 .setAction(R.string.undo, v -> {
1645 // Do nothing because everything will be handled by `onDismissed()` below.
1647 .addCallback(new Snackbar.Callback() {
1648 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1650 public void onDismissed(Snackbar snackbar, int event) {
1651 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1652 // Delete the form data.
1653 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1654 mainWebViewDatabase.clearFormData();
1662 // Toggle the EasyList status.
1663 currentWebView.enableBlocklist(NestedScrollWebView.EASY_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST));
1665 // Update the menu checkbox.
1666 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST));
1668 // Reload the current WebView.
1669 currentWebView.reload();
1672 case R.id.easyprivacy:
1673 // Toggle the EasyPrivacy status.
1674 currentWebView.enableBlocklist(NestedScrollWebView.EASY_PRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY));
1676 // Update the menu checkbox.
1677 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY));
1679 // Reload the current WebView.
1680 currentWebView.reload();
1683 case R.id.fanboys_annoyance_list:
1684 // Toggle Fanboy's Annoyance List status.
1685 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1687 // Update the menu checkbox.
1688 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1690 // Update the staus of Fanboy's Social Blocking List.
1691 MenuItem fanboysSocialBlockingListMenuItem = optionsMenu.findItem(R.id.fanboys_social_blocking_list);
1692 fanboysSocialBlockingListMenuItem.setEnabled(!currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1694 // Reload the current WebView.
1695 currentWebView.reload();
1698 case R.id.fanboys_social_blocking_list:
1699 // Toggle Fanboy's Social Blocking List status.
1700 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1702 // Update the menu checkbox.
1703 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1705 // Reload the current WebView.
1706 currentWebView.reload();
1709 case R.id.ultraprivacy:
1710 // Toggle the UltraPrivacy status.
1711 currentWebView.enableBlocklist(NestedScrollWebView.ULTRA_PRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY));
1713 // Update the menu checkbox.
1714 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY));
1716 // Reload the current WebView.
1717 currentWebView.reload();
1720 case R.id.block_all_third_party_requests:
1721 //Toggle the third-party requests blocker status.
1722 currentWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, !currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1724 // Update the menu checkbox.
1725 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1727 // Reload the current WebView.
1728 currentWebView.reload();
1731 case R.id.user_agent_privacy_browser:
1732 // Update the user agent.
1733 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
1735 // Reload the current WebView.
1736 currentWebView.reload();
1739 case R.id.user_agent_webview_default:
1740 // Update the user agent.
1741 currentWebView.getSettings().setUserAgentString("");
1743 // Reload the current WebView.
1744 currentWebView.reload();
1747 case R.id.user_agent_firefox_on_android:
1748 // Update the user agent.
1749 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
1751 // Reload the current WebView.
1752 currentWebView.reload();
1755 case R.id.user_agent_chrome_on_android:
1756 // Update the user agent.
1757 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
1759 // Reload the current WebView.
1760 currentWebView.reload();
1763 case R.id.user_agent_safari_on_ios:
1764 // Update the user agent.
1765 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
1767 // Reload the current WebView.
1768 currentWebView.reload();
1771 case R.id.user_agent_firefox_on_linux:
1772 // Update the user agent.
1773 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
1775 // Reload the current WebView.
1776 currentWebView.reload();
1779 case R.id.user_agent_chromium_on_linux:
1780 // Update the user agent.
1781 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
1783 // Reload the current WebView.
1784 currentWebView.reload();
1787 case R.id.user_agent_firefox_on_windows:
1788 // Update the user agent.
1789 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
1791 // Reload the current WebView.
1792 currentWebView.reload();
1795 case R.id.user_agent_chrome_on_windows:
1796 // Update the user agent.
1797 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
1799 // Reload the current WebView.
1800 currentWebView.reload();
1803 case R.id.user_agent_edge_on_windows:
1804 // Update the user agent.
1805 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
1807 // Reload the current WebView.
1808 currentWebView.reload();
1811 case R.id.user_agent_internet_explorer_on_windows:
1812 // Update the user agent.
1813 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
1815 // Reload the current WebView.
1816 currentWebView.reload();
1819 case R.id.user_agent_safari_on_macos:
1820 // Update the user agent.
1821 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
1823 // Reload the current WebView.
1824 currentWebView.reload();
1827 case R.id.user_agent_custom:
1828 // Update the user agent.
1829 currentWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
1831 // Reload the current WebView.
1832 currentWebView.reload();
1835 case R.id.font_size_twenty_five_percent:
1836 currentWebView.getSettings().setTextZoom(25);
1839 case R.id.font_size_fifty_percent:
1840 currentWebView.getSettings().setTextZoom(50);
1843 case R.id.font_size_seventy_five_percent:
1844 currentWebView.getSettings().setTextZoom(75);
1847 case R.id.font_size_one_hundred_percent:
1848 currentWebView.getSettings().setTextZoom(100);
1851 case R.id.font_size_one_hundred_twenty_five_percent:
1852 currentWebView.getSettings().setTextZoom(125);
1855 case R.id.font_size_one_hundred_fifty_percent:
1856 currentWebView.getSettings().setTextZoom(150);
1859 case R.id.font_size_one_hundred_seventy_five_percent:
1860 currentWebView.getSettings().setTextZoom(175);
1863 case R.id.font_size_two_hundred_percent:
1864 currentWebView.getSettings().setTextZoom(200);
1867 case R.id.swipe_to_refresh:
1868 // Toggle the stored status of swipe to refresh.
1869 currentWebView.setSwipeToRefresh(!currentWebView.getSwipeToRefresh());
1871 // Get a handle for the swipe refresh layout.
1872 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
1874 // Update the swipe refresh layout.
1875 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
1876 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.
1877 // Only enable the swipe refresh layout if the WebView is scrolled to the top.
1878 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
1879 } else { // For API < 23, the swipe refresh layout is always enabled.
1880 // Enable the swipe refresh layout.
1881 swipeRefreshLayout.setEnabled(true);
1883 } else { // Swipe to refresh is disabled.
1884 // Disable the swipe refresh layout.
1885 swipeRefreshLayout.setEnabled(false);
1889 case R.id.display_images:
1890 if (currentWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1891 // Disable loading of images.
1892 currentWebView.getSettings().setLoadsImagesAutomatically(false);
1894 // Reload the website to remove existing images.
1895 currentWebView.reload();
1896 } else { // Images are not currently loaded automatically.
1897 // Enable loading of images. Missing images will be loaded without the need for a reload.
1898 currentWebView.getSettings().setLoadsImagesAutomatically(true);
1902 case R.id.night_mode:
1903 // Toggle night mode.
1904 currentWebView.setNightMode(!currentWebView.getNightMode());
1906 // Enable or disable JavaScript according to night mode, the global preference, and any domain settings.
1907 if (currentWebView.getNightMode()) { // Night mode is enabled, which requires JavaScript.
1908 // Enable JavaScript.
1909 currentWebView.getSettings().setJavaScriptEnabled(true);
1910 } else if (currentWebView.getDomainSettingsApplied()) { // Night mode is disabled and domain settings are applied. Set JavaScript according to the domain settings.
1911 // Apply the JavaScript preference that was stored the last time domain settings were loaded.
1912 currentWebView.getSettings().setJavaScriptEnabled(currentWebView.getDomainSettingsJavaScriptEnabled());
1913 } else { // Night mode is disabled and domain settings are not applied. Set JavaScript according to the global preference.
1914 // Apply the JavaScript preference.
1915 currentWebView.getSettings().setJavaScriptEnabled(sharedPreferences.getBoolean("javascript", false));
1918 // Update the privacy icons.
1919 updatePrivacyIcons(false);
1921 // Reload the website.
1922 currentWebView.reload();
1925 case R.id.find_on_page:
1926 // Get a handle for the views.
1927 Toolbar toolbar = findViewById(R.id.toolbar);
1928 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
1929 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
1931 // Set the minimum height of the find on page linear layout to match the toolbar.
1932 findOnPageLinearLayout.setMinimumHeight(toolbar.getHeight());
1934 // Hide the toolbar.
1935 toolbar.setVisibility(View.GONE);
1937 // Show the find on page linear layout.
1938 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1940 // Display the keyboard. The app must wait 200 ms before running the command to work around a bug in Android.
1941 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1942 findOnPageEditText.postDelayed(() -> {
1943 // Set the focus on `findOnPageEditText`.
1944 findOnPageEditText.requestFocus();
1946 // Get a handle for the input method manager.
1947 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1949 // Remove the lint warning below that the input method manager might be null.
1950 assert inputMethodManager != null;
1952 // Display the keyboard. `0` sets no input flags.
1953 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1957 case R.id.view_source:
1958 // Create an intent to launch the view source activity.
1959 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
1961 // Add the variables to the intent.
1962 viewSourceIntent.putExtra("user_agent", currentWebView.getSettings().getUserAgentString());
1963 viewSourceIntent.putExtra("current_url", currentWebView.getUrl());
1966 startActivity(viewSourceIntent);
1969 case R.id.share_url:
1970 // Setup the share string.
1971 String shareString = currentWebView.getTitle() + " – " + currentWebView.getUrl();
1973 // Create the share intent.
1974 Intent shareIntent = new Intent(Intent.ACTION_SEND);
1975 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1976 shareIntent.setType("text/plain");
1979 startActivity(Intent.createChooser(shareIntent, getString(R.string.share_url)));
1983 // Get a print manager instance.
1984 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1986 // Remove the lint error below that print manager might be null.
1987 assert printManager != null;
1989 // Create a print document adapter from the current WebView.
1990 PrintDocumentAdapter printDocumentAdapter = currentWebView.createPrintDocumentAdapter();
1992 // Print the document.
1993 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1996 case R.id.open_with_app:
1997 openWithApp(currentWebView.getUrl());
2000 case R.id.open_with_browser:
2001 openWithBrowser(currentWebView.getUrl());
2004 case R.id.add_to_homescreen:
2005 // Instantiate the create home screen shortcut dialog.
2006 DialogFragment createHomeScreenShortcutDialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView.getTitle(), currentWebView.getUrl(),
2007 currentWebView.getFavoriteOrDefaultIcon());
2009 // Show the create home screen shortcut dialog.
2010 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2013 case R.id.proxy_through_orbot:
2014 // Toggle the proxy through Orbot variable.
2015 proxyThroughOrbot = !proxyThroughOrbot;
2017 // Apply the proxy through Orbot settings.
2018 applyProxyThroughOrbot(true);
2022 if (menuItem.getTitle().equals(getString(R.string.refresh))) { // The refresh button was pushed.
2023 // Reload the current WebView.
2024 currentWebView.reload();
2025 } else { // The stop button was pushed.
2026 // Stop the loading of the WebView.
2027 currentWebView.stopLoading();
2031 case R.id.ad_consent:
2032 // Display the ad consent dialog.
2033 DialogFragment adConsentDialogFragment = new AdConsentDialog();
2034 adConsentDialogFragment.show(getSupportFragmentManager(), getString(R.string.ad_consent));
2038 // Don't consume the event.
2039 return super.onOptionsItemSelected(menuItem);
2043 // removeAllCookies is deprecated, but it is required for API < 21.
2045 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2046 // Get the menu item ID.
2047 int menuItemId = menuItem.getItemId();
2049 // Get a handle for the shared preferences.
2050 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2052 // Run the commands that correspond to the selected menu item.
2053 switch (menuItemId) {
2054 case R.id.close_tab:
2055 // Get a handle for the tab layout and the view pager.
2056 TabLayout tabLayout = findViewById(R.id.tablayout);
2057 ViewPager webViewPager = findViewById(R.id.webviewpager);
2059 // Get the current tab number.
2060 int currentTabNumber = tabLayout.getSelectedTabPosition();
2062 // Delete the current tab.
2063 tabLayout.removeTabAt(currentTabNumber);
2065 // 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.
2066 if (webViewPagerAdapter.deletePage(currentTabNumber, webViewPager)) {
2067 setCurrentWebView(currentTabNumber);
2071 case R.id.clear_and_exit:
2072 // Close the bookmarks cursor and database.
2073 bookmarksCursor.close();
2074 bookmarksDatabaseHelper.close();
2076 // Get the status of the clear everything preference.
2077 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2079 // Get a handle for the runtime.
2080 Runtime runtime = Runtime.getRuntime();
2082 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
2083 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
2084 String privateDataDirectoryString = getApplicationInfo().dataDir;
2087 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2088 // The command to remove cookies changed slightly in API 21.
2089 if (Build.VERSION.SDK_INT >= 21) {
2090 CookieManager.getInstance().removeAllCookies(null);
2092 CookieManager.getInstance().removeAllCookie();
2095 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2097 // Two commands must be used because `Runtime.exec()` does not like `*`.
2098 Process deleteCookiesProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2099 Process deleteCookiesJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2101 // Wait until the processes have finished.
2102 deleteCookiesProcess.waitFor();
2103 deleteCookiesJournalProcess.waitFor();
2104 } catch (Exception exception) {
2105 // Do nothing if an error is thrown.
2109 // Clear DOM storage.
2110 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2111 // Ask `WebStorage` to clear the DOM storage.
2112 WebStorage webStorage = WebStorage.getInstance();
2113 webStorage.deleteAllData();
2115 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2117 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2118 Process deleteLocalStorageProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2120 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2121 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2122 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2123 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2124 Process deleteDatabaseProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2126 // Wait until the processes have finished.
2127 deleteLocalStorageProcess.waitFor();
2128 deleteIndexProcess.waitFor();
2129 deleteQuotaManagerProcess.waitFor();
2130 deleteQuotaManagerJournalProcess.waitFor();
2131 deleteDatabaseProcess.waitFor();
2132 } catch (Exception exception) {
2133 // Do nothing if an error is thrown.
2137 // Clear form data if the API < 26.
2138 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
2139 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
2140 webViewDatabase.clearFormData();
2142 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2144 // A string array must be used because the database contains a space and `Runtime.exec` will not otherwise escape the string correctly.
2145 Process deleteWebDataProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
2146 Process deleteWebDataJournalProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
2148 // Wait until the processes have finished.
2149 deleteWebDataProcess.waitFor();
2150 deleteWebDataJournalProcess.waitFor();
2151 } catch (Exception exception) {
2152 // Do nothing if an error is thrown.
2157 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2158 // Clear the cache from each WebView.
2159 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
2160 // Get the WebView tab fragment.
2161 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
2163 // Get the fragment view.
2164 View fragmentView = webViewTabFragment.getView();
2166 // Only clear the cache if the WebView exists.
2167 if (fragmentView != null) {
2168 // Get the nested scroll WebView from the tab fragment.
2169 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
2171 // Clear the cache for this WebView.
2172 nestedScrollWebView.clearCache(true);
2176 // Manually delete the cache directories.
2178 // Delete the main cache directory.
2179 Process deleteCacheProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2181 // Delete the secondary `Service Worker` cache directory.
2182 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2183 Process deleteServiceWorkerProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2185 // Wait until the processes have finished.
2186 deleteCacheProcess.waitFor();
2187 deleteServiceWorkerProcess.waitFor();
2188 } catch (Exception exception) {
2189 // Do nothing if an error is thrown.
2193 // Wipe out each WebView.
2194 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
2195 // Get the WebView tab fragment.
2196 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
2198 // Get the fragment view.
2199 View fragmentView = webViewTabFragment.getView();
2201 // Only wipe out the WebView if it exists.
2202 if (fragmentView != null) {
2203 // Get the nested scroll WebView from the tab fragment.
2204 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
2206 // Clear SSL certificate preferences for this WebView.
2207 nestedScrollWebView.clearSslPreferences();
2209 // Clear the back/forward history for this WebView.
2210 nestedScrollWebView.clearHistory();
2212 // Destroy the internal state of `mainWebView`.
2213 nestedScrollWebView.destroy();
2217 // Clear the custom headers.
2218 customHeaders.clear();
2220 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
2221 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
2222 if (clearEverything) {
2224 // Delete the folder.
2225 Process deleteAppWebviewProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
2227 // Wait until the process has finished.
2228 deleteAppWebviewProcess.waitFor();
2229 } catch (Exception exception) {
2230 // Do nothing if an error is thrown.
2234 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
2235 if (Build.VERSION.SDK_INT >= 21) {
2236 finishAndRemoveTask();
2241 // Remove the terminated program from RAM. The status code is `0`.
2246 // Select the homepage based on the proxy through Orbot status.
2247 if (proxyThroughOrbot) {
2248 // Load the Tor homepage.
2249 loadUrl(sharedPreferences.getString("tor_homepage", getString(R.string.tor_homepage_default_value)));
2251 // Load the normal homepage.
2252 loadUrl(sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
2257 if (currentWebView.canGoBack()) {
2258 // Reset the current domain name so that navigation works if third-party requests are blocked.
2259 currentWebView.resetCurrentDomainName();
2261 // Set navigating history so that the domain settings are applied when the new URL is loaded.
2262 currentWebView.setNavigatingHistory(true);
2264 // Load the previous website in the history.
2265 currentWebView.goBack();
2270 if (currentWebView.canGoForward()) {
2271 // Reset the current domain name so that navigation works if third-party requests are blocked.
2272 currentWebView.resetCurrentDomainName();
2274 // Set navigating history so that the domain settings are applied when the new URL is loaded.
2275 currentWebView.setNavigatingHistory(true);
2277 // Load the next website in the history.
2278 currentWebView.goForward();
2283 // Instantiate the URL history dialog.
2284 DialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(currentWebView.getWebViewFragmentId());
2286 // Show the URL history dialog.
2287 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2291 // Populate the resource requests.
2292 RequestsActivity.resourceRequests = currentWebView.getResourceRequests();
2294 // Create an intent to launch the Requests activity.
2295 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2297 // Add the block third-party requests status to the intent.
2298 requestsIntent.putExtra("block_all_third_party_requests", currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
2301 startActivity(requestsIntent);
2304 case R.id.downloads:
2305 // Launch the system Download Manager.
2306 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2308 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2309 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2311 startActivity(downloadManagerIntent);
2315 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2316 reapplyDomainSettingsOnRestart = true;
2318 // Launch the domains activity.
2319 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2321 // Add the extra information to the intent.
2322 domainsIntent.putExtra("current_url", currentWebView.getUrl());
2324 // Get the current certificate.
2325 SslCertificate sslCertificate = currentWebView.getCertificate();
2327 // Check to see if the SSL certificate is populated.
2328 if (sslCertificate != null) {
2329 // Extract the certificate to strings.
2330 String issuedToCName = sslCertificate.getIssuedTo().getCName();
2331 String issuedToOName = sslCertificate.getIssuedTo().getOName();
2332 String issuedToUName = sslCertificate.getIssuedTo().getUName();
2333 String issuedByCName = sslCertificate.getIssuedBy().getCName();
2334 String issuedByOName = sslCertificate.getIssuedBy().getOName();
2335 String issuedByUName = sslCertificate.getIssuedBy().getUName();
2336 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
2337 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
2339 // Add the certificate to the intent.
2340 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
2341 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
2342 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
2343 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
2344 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
2345 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
2346 domainsIntent.putExtra("ssl_start_date", startDateLong);
2347 domainsIntent.putExtra("ssl_end_date", endDateLong);
2350 // Check to see if the current IP addresses have been received.
2351 if (currentWebView.hasCurrentIpAddresses()) {
2352 // Add the current IP addresses to the intent.
2353 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
2357 startActivity(domainsIntent);
2361 // Set the flag to reapply app settings on restart when returning from Settings.
2362 reapplyAppSettingsOnRestart = true;
2364 // Set the flag to reapply the domain settings on restart when returning from Settings.
2365 reapplyDomainSettingsOnRestart = true;
2367 // Launch the settings activity.
2368 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2369 startActivity(settingsIntent);
2372 case R.id.import_export:
2373 // Launch the import/export activity.
2374 Intent importExportIntent = new Intent (this, ImportExportActivity.class);
2375 startActivity(importExportIntent);
2379 // Launch the logcat activity.
2380 Intent logcatIntent = new Intent(this, LogcatActivity.class);
2381 startActivity(logcatIntent);
2385 // Launch `GuideActivity`.
2386 Intent guideIntent = new Intent(this, GuideActivity.class);
2387 startActivity(guideIntent);
2391 // Create an intent to launch the about activity.
2392 Intent aboutIntent = new Intent(this, AboutActivity.class);
2394 // Create a string array for the blocklist versions.
2395 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],
2396 ultraPrivacy.get(0).get(0)[0]};
2398 // Add the blocklist versions to the intent.
2399 aboutIntent.putExtra("blocklist_versions", blocklistVersions);
2402 startActivity(aboutIntent);
2406 // Get a handle for the drawer layout.
2407 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
2409 // Close the navigation drawer.
2410 drawerLayout.closeDrawer(GravityCompat.START);
2415 public void onPostCreate(Bundle savedInstanceState) {
2416 // Run the default commands.
2417 super.onPostCreate(savedInstanceState);
2419 // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished. This creates the navigation drawer icon.
2420 actionBarDrawerToggle.syncState();
2424 public void onConfigurationChanged(Configuration newConfig) {
2425 // Run the default commands.
2426 super.onConfigurationChanged(newConfig);
2428 // Get the status bar pixel size.
2429 int statusBarResourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
2430 int statusBarPixelSize = getResources().getDimensionPixelSize(statusBarResourceId);
2432 // Get the resource density.
2433 float screenDensity = getResources().getDisplayMetrics().density;
2435 // Recalculate the drawer header padding.
2436 drawerHeaderPaddingLeftAndRight = (int) (15 * screenDensity);
2437 drawerHeaderPaddingTop = statusBarPixelSize + (int) (4 * screenDensity);
2438 drawerHeaderPaddingBottom = (int) (8 * screenDensity);
2440 // Reload the ad for the free flavor if not in full screen mode.
2441 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2442 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2443 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
2446 // `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:
2447 // https://code.google.com/p/android/issues/detail?id=20493#c8
2448 // ActivityCompat.invalidateOptionsMenu(this);
2452 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2453 // Store the hit test result.
2454 final WebView.HitTestResult hitTestResult = currentWebView.getHitTestResult();
2456 // Create the URL strings.
2457 final String imageUrl;
2458 final String linkUrl;
2460 // Get handles for the system managers.
2461 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2462 FragmentManager fragmentManager = getSupportFragmentManager();
2463 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2465 // Remove the lint errors below that the clipboard manager might be null.
2466 assert clipboardManager != null;
2468 // Process the link according to the type.
2469 switch (hitTestResult.getType()) {
2470 // `SRC_ANCHOR_TYPE` is a link.
2471 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2472 // Get the target URL.
2473 linkUrl = hitTestResult.getExtra();
2475 // Set the target URL as the title of the `ContextMenu`.
2476 menu.setHeaderTitle(linkUrl);
2478 // Add a Load URL entry.
2479 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2488 // Add an Open with App entry.
2489 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2490 openWithApp(linkUrl);
2494 // Add an Open with Browser entry.
2495 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2496 openWithBrowser(linkUrl);
2500 // Add a Copy URL entry.
2501 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2502 // Save the link URL in a `ClipData`.
2503 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2505 // Set the `ClipData` as the clipboard's primary clip.
2506 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2510 // Add a Download URL entry.
2511 menu.add(R.string.download_url).setOnMenuItemClickListener((MenuItem item) -> {
2512 // Check if the download should be processed by an external app.
2513 if (sharedPreferences.getBoolean("download_with_external_app", false)) { // Download with an external app.
2514 openUrlWithExternalApp(linkUrl);
2515 } else { // Download with Android's download manager.
2516 // Check to see if the storage permission has already been granted.
2517 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission needs to be requested.
2518 // Store the variables for future use by `onRequestPermissionsResult()`.
2519 downloadUrl = linkUrl;
2520 downloadContentDisposition = "none";
2521 downloadContentLength = -1;
2523 // Show a dialog if the user has previously denied the permission.
2524 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2525 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
2526 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
2528 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
2529 downloadLocationPermissionDialogFragment.show(fragmentManager, getString(R.string.download_location));
2530 } else { // Show the permission request directly.
2531 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
2532 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2534 } else { // The storage permission has already been granted.
2535 // Get a handle for the download file alert dialog.
2536 DialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(linkUrl, "none", -1);
2538 // Show the download file alert dialog.
2539 downloadFileDialogFragment.show(fragmentManager, getString(R.string.download));
2545 // Add a Cancel entry, which by default closes the context menu.
2546 menu.add(R.string.cancel);
2549 case WebView.HitTestResult.EMAIL_TYPE:
2550 // Get the target URL.
2551 linkUrl = hitTestResult.getExtra();
2553 // Set the target URL as the title of the `ContextMenu`.
2554 menu.setHeaderTitle(linkUrl);
2556 // Add a Write Email entry.
2557 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2558 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2559 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2561 // Parse the url and set it as the data for the `Intent`.
2562 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2564 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2565 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2568 startActivity(emailIntent);
2572 // Add a Copy Email Address entry.
2573 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2574 // Save the email address in a `ClipData`.
2575 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2577 // Set the `ClipData` as the clipboard's primary clip.
2578 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2582 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2583 menu.add(R.string.cancel);
2586 // `IMAGE_TYPE` is an image.
2587 case WebView.HitTestResult.IMAGE_TYPE:
2588 // Get the image URL.
2589 imageUrl = hitTestResult.getExtra();
2591 // Set the image URL as the title of the `ContextMenu`.
2592 menu.setHeaderTitle(imageUrl);
2594 // Add a View Image entry.
2595 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2600 // Add a Download Image entry.
2601 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2602 // Check if the download should be processed by an external app.
2603 if (sharedPreferences.getBoolean("download_with_external_app", false)) { // Download with an external app.
2604 openUrlWithExternalApp(imageUrl);
2605 } else { // Download with Android's download manager.
2606 // Check to see if the storage permission has already been granted.
2607 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission needs to be requested.
2608 // Store the image URL for use by `onRequestPermissionResult()`.
2609 downloadImageUrl = imageUrl;
2611 // Show a dialog if the user has previously denied the permission.
2612 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2613 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2614 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2616 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
2617 downloadLocationPermissionDialogFragment.show(fragmentManager, getString(R.string.download_location));
2618 } else { // Show the permission request directly.
2619 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
2620 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2622 } else { // The storage permission has already been granted.
2623 // Get a handle for the download image alert dialog.
2624 DialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2626 // Show the download image alert dialog.
2627 downloadImageDialogFragment.show(fragmentManager, getString(R.string.download));
2633 // Add a Copy URL entry.
2634 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2635 // Save the image URL in a `ClipData`.
2636 ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2638 // Set the `ClipData` as the clipboard's primary clip.
2639 clipboardManager.setPrimaryClip(srcImageTypeClipData);
2643 // Add an Open with App entry.
2644 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2645 openWithApp(imageUrl);
2649 // Add an Open with Browser entry.
2650 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2651 openWithBrowser(imageUrl);
2655 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2656 menu.add(R.string.cancel);
2660 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2661 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2662 // Get the image URL.
2663 imageUrl = hitTestResult.getExtra();
2665 // Set the image URL as the title of the `ContextMenu`.
2666 menu.setHeaderTitle(imageUrl);
2668 // Add a `View Image` entry.
2669 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2674 // Add a `Download Image` entry.
2675 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2676 // Check if the download should be processed by an external app.
2677 if (sharedPreferences.getBoolean("download_with_external_app", false)) { // Download with an external app.
2678 openUrlWithExternalApp(imageUrl);
2679 } else { // Download with Android's download manager.
2680 // Check to see if the storage permission has already been granted.
2681 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission needs to be requested.
2682 // Store the image URL for use by `onRequestPermissionResult()`.
2683 downloadImageUrl = imageUrl;
2685 // Show a dialog if the user has previously denied the permission.
2686 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2687 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2688 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2690 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
2691 downloadLocationPermissionDialogFragment.show(fragmentManager, getString(R.string.download_location));
2692 } else { // Show the permission request directly.
2693 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
2694 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2696 } else { // The storage permission has already been granted.
2697 // Get a handle for the download image alert dialog.
2698 DialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2700 // Show the download image alert dialog.
2701 downloadImageDialogFragment.show(fragmentManager, getString(R.string.download));
2707 // Add a `Copy URL` entry.
2708 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2709 // Save the image URL in a `ClipData`.
2710 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2712 // Set the `ClipData` as the clipboard's primary clip.
2713 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2717 // Add an Open with App entry.
2718 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2719 openWithApp(imageUrl);
2723 // Add an Open with Browser entry.
2724 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2725 openWithBrowser(imageUrl);
2729 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2730 menu.add(R.string.cancel);
2736 public void onCreateBookmark(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2737 // Get a handle for the bookmarks list view.
2738 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2740 // Get the views from the dialog fragment.
2741 EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
2742 EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
2744 // Extract the strings from the edit texts.
2745 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2746 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2748 // Create a favorite icon byte array output stream.
2749 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2751 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2752 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2754 // Convert the favorite icon byte array stream to a byte array.
2755 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2757 // Display the new bookmark below the current items in the (0 indexed) list.
2758 int newBookmarkDisplayOrder = bookmarksListView.getCount();
2760 // Create the bookmark.
2761 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2763 // Update the bookmarks cursor with the current contents of this folder.
2764 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2766 // Update the list view.
2767 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2769 // Scroll to the new bookmark.
2770 bookmarksListView.setSelection(newBookmarkDisplayOrder);
2774 public void onCreateBookmarkFolder(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2775 // Get a handle for the bookmarks list view.
2776 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2778 // Get handles for the views in the dialog fragment.
2779 EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
2780 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
2781 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
2783 // Get new folder name string.
2784 String folderNameString = createFolderNameEditText.getText().toString();
2786 // Create a folder icon bitmap.
2787 Bitmap folderIconBitmap;
2789 // Set the folder icon bitmap according to the dialog.
2790 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
2791 // Get the default folder icon drawable.
2792 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2794 // Convert the folder icon drawable to a bitmap drawable.
2795 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2797 // Convert the folder icon bitmap drawable to a bitmap.
2798 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2799 } else { // Use the WebView favorite icon.
2800 // Copy the favorite icon bitmap to the folder icon bitmap.
2801 folderIconBitmap = favoriteIconBitmap;
2804 // Create a folder icon byte array output stream.
2805 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2807 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2808 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2810 // Convert the folder icon byte array stream to a byte array.
2811 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2813 // Move all the bookmarks down one in the display order.
2814 for (int i = 0; i < bookmarksListView.getCount(); i++) {
2815 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2816 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2819 // Create the folder, which will be placed at the top of the `ListView`.
2820 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2822 // Update the bookmarks cursor with the current contents of this folder.
2823 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2825 // Update the `ListView`.
2826 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2828 // Scroll to the new folder.
2829 bookmarksListView.setSelection(0);
2833 public void onSaveBookmark(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, Bitmap favoriteIconBitmap) {
2834 // Get handles for the views from `dialogFragment`.
2835 EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
2836 EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
2837 RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
2839 // Store the bookmark strings.
2840 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
2841 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
2843 // Update the bookmark.
2844 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
2845 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
2846 } else { // Update the bookmark using the `WebView` favorite icon.
2847 // Create a favorite icon byte array output stream.
2848 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2850 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2851 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
2853 // Convert the favorite icon byte array stream to a byte array.
2854 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
2856 // Update the bookmark and the favorite icon.
2857 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
2860 // Update the bookmarks cursor with the current contents of this folder.
2861 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2863 // Update the list view.
2864 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2868 public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId, Bitmap favoriteIconBitmap) {
2869 // Get handles for the views from `dialogFragment`.
2870 EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
2871 RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
2872 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
2873 ImageView defaultFolderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
2875 // Get the new folder name.
2876 String newFolderNameString = editFolderNameEditText.getText().toString();
2878 // Check if the favorite icon has changed.
2879 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
2880 // Update the name in the database.
2881 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2882 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
2883 // Create the new folder icon Bitmap.
2884 Bitmap folderIconBitmap;
2886 // Populate the new folder icon bitmap.
2887 if (defaultFolderIconRadioButton.isChecked()) {
2888 // Get the default folder icon drawable.
2889 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2891 // Convert the folder icon drawable to a bitmap drawable.
2892 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2894 // Convert the folder icon bitmap drawable to a bitmap.
2895 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2896 } else { // Use the `WebView` favorite icon.
2897 // Copy the favorite icon bitmap to the folder icon bitmap.
2898 folderIconBitmap = favoriteIconBitmap;
2901 // Create a folder icon byte array output stream.
2902 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2904 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2905 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2907 // Convert the folder icon byte array stream to a byte array.
2908 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2910 // Update the folder icon in the database.
2911 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, newFolderIconByteArray);
2912 } else { // The folder icon and the name have changed.
2913 // Get the new folder icon `Bitmap`.
2914 Bitmap folderIconBitmap;
2915 if (defaultFolderIconRadioButton.isChecked()) {
2916 // Get the default folder icon drawable.
2917 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2919 // Convert the folder icon drawable to a bitmap drawable.
2920 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2922 // Convert the folder icon bitmap drawable to a bitmap.
2923 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2924 } else { // Use the `WebView` favorite icon.
2925 // Copy the favorite icon bitmap to the folder icon bitmap.
2926 folderIconBitmap = favoriteIconBitmap;
2929 // Create a folder icon byte array output stream.
2930 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2932 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2933 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2935 // Convert the folder icon byte array stream to a byte array.
2936 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2938 // Update the folder name and icon in the database.
2939 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, newFolderIconByteArray);
2942 // Update the bookmarks cursor with the current contents of this folder.
2943 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2945 // Update the `ListView`.
2946 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2950 public void onCloseDownloadLocationPermissionDialog(int downloadType) {
2951 switch (downloadType) {
2952 case DownloadLocationPermissionDialog.DOWNLOAD_FILE:
2953 // Request the WRITE_EXTERNAL_STORAGE permission with a file request code.
2954 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2957 case DownloadLocationPermissionDialog.DOWNLOAD_IMAGE:
2958 // Request the WRITE_EXTERNAL_STORAGE permission with an image request code.
2959 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2965 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
2966 // Get a handle for the fragment manager.
2967 FragmentManager fragmentManager = getSupportFragmentManager();
2969 switch (requestCode) {
2970 case DOWNLOAD_FILE_REQUEST_CODE:
2971 // Show the download file alert dialog. When the dialog closes, the correct command will be used based on the permission status.
2972 DialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(downloadUrl, downloadContentDisposition, downloadContentLength);
2974 // On API 23, displaying the fragment must be delayed or the app will crash.
2975 if (Build.VERSION.SDK_INT == 23) {
2976 new Handler().postDelayed(() -> downloadFileDialogFragment.show(fragmentManager, getString(R.string.download)), 500);
2978 downloadFileDialogFragment.show(fragmentManager, getString(R.string.download));
2981 // Reset the download variables.
2983 downloadContentDisposition = "";
2984 downloadContentLength = 0;
2987 case DOWNLOAD_IMAGE_REQUEST_CODE:
2988 // Show the download image alert dialog. When the dialog closes, the correct command will be used based on the permission status.
2989 DialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(downloadImageUrl);
2991 // On API 23, displaying the fragment must be delayed or the app will crash.
2992 if (Build.VERSION.SDK_INT == 23) {
2993 new Handler().postDelayed(() -> downloadImageDialogFragment.show(fragmentManager, getString(R.string.download)), 500);
2995 downloadImageDialogFragment.show(fragmentManager, getString(R.string.download));
2998 // Reset the image URL variable.
2999 downloadImageUrl = "";
3005 public void onDownloadImage(DialogFragment dialogFragment, String imageUrl) {
3006 // Download the image if it has an HTTP or HTTPS URI.
3007 if (imageUrl.startsWith("http")) {
3008 // Get a handle for the system `DOWNLOAD_SERVICE`.
3009 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
3011 // Parse `imageUrl`.
3012 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
3014 // Get a handle for the cookie manager.
3015 CookieManager cookieManager = CookieManager.getInstance();
3017 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
3018 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
3019 if (cookieManager.acceptCookie()) {
3020 // Get the cookies for `imageUrl`.
3021 String cookies = cookieManager.getCookie(imageUrl);
3023 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
3024 downloadRequest.addRequestHeader("Cookie", cookies);
3027 // Get the file name from the dialog fragment.
3028 EditText downloadImageNameEditText = dialogFragment.getDialog().findViewById(R.id.download_image_name);
3029 String imageName = downloadImageNameEditText.getText().toString();
3031 // Specify the download location.
3032 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
3033 // Download to the public download directory.
3034 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, imageName);
3035 } else { // External write permission denied.
3036 // Download to the app's external download directory.
3037 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, imageName);
3040 // Allow `MediaScanner` to index the download if it is a media file.
3041 downloadRequest.allowScanningByMediaScanner();
3043 // Add the URL as the description for the download.
3044 downloadRequest.setDescription(imageUrl);
3046 // Show the download notification after the download is completed.
3047 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3049 // Remove the lint warning below that `downloadManager` might be `null`.
3050 assert downloadManager != null;
3052 // Initiate the download.
3053 downloadManager.enqueue(downloadRequest);
3054 } else { // The image is not an HTTP or HTTPS URI.
3055 Snackbar.make(currentWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
3060 public void onDownloadFile(DialogFragment dialogFragment, String downloadUrl) {
3061 // Download the file if it has an HTTP or HTTPS URI.
3062 if (downloadUrl.startsWith("http")) {
3063 // Get a handle for the system `DOWNLOAD_SERVICE`.
3064 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
3066 // Parse `downloadUrl`.
3067 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
3069 // Get a handle for the cookie manager.
3070 CookieManager cookieManager = CookieManager.getInstance();
3072 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
3073 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
3074 if (cookieManager.acceptCookie()) {
3075 // Get the cookies for `downloadUrl`.
3076 String cookies = cookieManager.getCookie(downloadUrl);
3078 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
3079 downloadRequest.addRequestHeader("Cookie", cookies);
3082 // Get the file name from the dialog fragment.
3083 EditText downloadFileNameEditText = dialogFragment.getDialog().findViewById(R.id.download_file_name);
3084 String fileName = downloadFileNameEditText.getText().toString();
3086 // Specify the download location.
3087 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
3088 // Download to the public download directory.
3089 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
3090 } else { // External write permission denied.
3091 // Download to the app's external download directory.
3092 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, fileName);
3095 // Allow `MediaScanner` to index the download if it is a media file.
3096 downloadRequest.allowScanningByMediaScanner();
3098 // Add the URL as the description for the download.
3099 downloadRequest.setDescription(downloadUrl);
3101 // Show the download notification after the download is completed.
3102 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3104 // Remove the lint warning below that `downloadManager` might be `null`.
3105 assert downloadManager != null;
3107 // Initiate the download.
3108 downloadManager.enqueue(downloadRequest);
3109 } else { // The download is not an HTTP or HTTPS URI.
3110 Snackbar.make(currentWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
3114 // Override `onBackPressed` to handle the navigation drawer and and the WebView.
3116 public void onBackPressed() {
3117 // Get a handle for the drawer layout.
3118 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
3120 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
3121 // Close the navigation drawer.
3122 drawerLayout.closeDrawer(GravityCompat.START);
3123 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
3124 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
3125 // close the bookmarks drawer.
3126 drawerLayout.closeDrawer(GravityCompat.END);
3127 } else { // A subfolder is displayed.
3128 // Place the former parent folder in `currentFolder`.
3129 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolderName(currentBookmarksFolder);
3131 // Load the new folder.
3132 loadBookmarksFolder();
3134 } else if (currentWebView.canGoBack()) { // There is at least one item in the current WebView history.
3135 // Reset the current domain name so that navigation works if third-party requests are blocked.
3136 currentWebView.resetCurrentDomainName();
3138 // Set navigating history so that the domain settings are applied when the new URL is loaded.
3139 currentWebView.setNavigatingHistory(true);
3142 currentWebView.goBack();
3143 } else { // There is nothing else to do.
3144 // Load a blank website.
3149 // 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.
3151 public void onActivityResult(int requestCode, int resultCode, Intent data) {
3152 // File uploads only work on API >= 21.
3153 if (Build.VERSION.SDK_INT >= 21) {
3154 // Pass the file to the WebView.
3155 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
3159 private void loadUrlFromTextBox() {
3160 // Get a handle for the URL edit text.
3161 EditText urlEditText = findViewById(R.id.url_edittext);
3163 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
3164 String unformattedUrlString = urlEditText.getText().toString().trim();
3166 // Initialize the formatted URL string.
3169 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
3170 if (unformattedUrlString.startsWith("content://")) { // This is a Content URL.
3171 // Load the entire content URL.
3172 url = unformattedUrlString;
3173 } else if (Patterns.WEB_URL.matcher(unformattedUrlString).matches() || unformattedUrlString.startsWith("http://") || unformattedUrlString.startsWith("https://") ||
3174 unformattedUrlString.startsWith("file://")) { // This is a standard URL.
3175 // Add `https://` at the beginning if there is no protocol. Otherwise the app will segfault.
3176 if (!unformattedUrlString.startsWith("http") && !unformattedUrlString.startsWith("file://") && !unformattedUrlString.startsWith("content://")) {
3177 unformattedUrlString = "https://" + unformattedUrlString;
3180 // Initialize `unformattedUrl`.
3181 URL unformattedUrl = null;
3183 // 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.
3185 unformattedUrl = new URL(unformattedUrlString);
3186 } catch (MalformedURLException e) {
3187 e.printStackTrace();
3190 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
3191 String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
3192 String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
3193 String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
3194 String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
3195 String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
3198 Uri.Builder uri = new Uri.Builder();
3199 uri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
3201 // Decode the URI as a UTF-8 string in.
3203 url = URLDecoder.decode(uri.build().toString(), "UTF-8");
3204 } catch (UnsupportedEncodingException exception) {
3205 // Do nothing. The formatted URL string will remain blank.
3207 } else if (!unformattedUrlString.isEmpty()){ // This is not a URL, but rather a search string.
3208 // Create an encoded URL String.
3209 String encodedUrlString;
3211 // Sanitize the search input.
3213 encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
3214 } catch (UnsupportedEncodingException exception) {
3215 encodedUrlString = "";
3218 // Add the base search URL.
3219 url = searchURL + encodedUrlString;
3222 // 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.
3223 urlEditText.clearFocus();
3229 private void loadUrl(String url) {
3230 // Apply the domain settings.
3231 applyDomainSettings(currentWebView, url, true, false);
3234 currentWebView.loadUrl(url, customHeaders);
3237 public void findPreviousOnPage(View view) {
3238 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
3239 currentWebView.findNext(false);
3242 public void findNextOnPage(View view) {
3243 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
3244 currentWebView.findNext(true);
3247 public void closeFindOnPage(View view) {
3248 // Get a handle for the views.
3249 Toolbar toolbar = findViewById(R.id.toolbar);
3250 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
3251 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
3253 // Delete the contents of `find_on_page_edittext`.
3254 findOnPageEditText.setText(null);
3256 // Clear the highlighted phrases.
3257 currentWebView.clearMatches();
3259 // Hide the find on page linear layout.
3260 findOnPageLinearLayout.setVisibility(View.GONE);
3262 // Show the toolbar.
3263 toolbar.setVisibility(View.VISIBLE);
3265 // Get a handle for the input method manager.
3266 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
3268 // Remove the lint warning below that the input method manager might be null.
3269 assert inputMethodManager != null;
3271 // Hide the keyboard.
3272 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
3275 private void applyAppSettings() {
3276 // Get a handle for the shared preferences.
3277 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3279 // Store the values from the shared preferences in variables.
3280 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3281 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
3282 proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
3283 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3284 hideAppBar = sharedPreferences.getBoolean("hide_app_bar", true);
3286 // Get handles for the views that need to be modified.
3287 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
3288 ActionBar actionBar = getSupportActionBar();
3289 LinearLayout tabsLinearLayout = findViewById(R.id.tabs_linearlayout);
3291 // Remove the incorrect lint warning below that the action bar might be null.
3292 assert actionBar != null;
3294 // Apply the proxy through Orbot settings.
3295 applyProxyThroughOrbot(false);
3297 // Set Do Not Track status.
3298 if (doNotTrackEnabled) {
3299 customHeaders.put("DNT", "1");
3301 customHeaders.remove("DNT");
3304 // Set the app bar scrolling for each WebView.
3305 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3306 // Get the WebView tab fragment.
3307 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3309 // Get the fragment view.
3310 View fragmentView = webViewTabFragment.getView();
3312 // Only modify the WebViews if they exist.
3313 if (fragmentView != null) {
3314 // Get the nested scroll WebView from the tab fragment.
3315 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3317 // Set the app bar scrolling.
3318 nestedScrollWebView.setNestedScrollingEnabled(sharedPreferences.getBoolean("scroll_app_bar", true));
3322 // Update the full screen browsing mode settings.
3323 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
3324 // Update the visibility of the app bar, which might have changed in the settings.
3326 // Hide the tab linear layout.
3327 tabsLinearLayout.setVisibility(View.GONE);
3329 // Hide the action bar.
3332 // Show the tab linear layout.
3333 tabsLinearLayout.setVisibility(View.VISIBLE);
3335 // Show the action bar.
3339 // Hide the banner ad in the free flavor.
3340 if (BuildConfig.FLAVOR.contentEquals("free")) {
3341 AdHelper.hideAd(findViewById(R.id.adview));
3344 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
3345 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3347 /* Hide the system bars.
3348 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3349 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
3350 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3351 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3353 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
3354 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3355 } else { // Privacy Browser is not in full screen browsing mode.
3356 // 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.
3357 inFullScreenBrowsingMode = false;
3359 // Show the tab linear layout.
3360 tabsLinearLayout.setVisibility(View.VISIBLE);
3362 // Show the action bar.
3365 // Show the banner ad in the free flavor.
3366 if (BuildConfig.FLAVOR.contentEquals("free")) {
3367 // Initialize the ads. If this isn't the first run, `loadAd()` will be automatically called instead.
3368 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getSupportFragmentManager(), getString(R.string.google_app_id), getString(R.string.ad_unit_id));
3371 // Remove the `SYSTEM_UI` flags from the root frame layout.
3372 rootFrameLayout.setSystemUiVisibility(0);
3374 // Add the translucent status flag.
3375 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3380 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
3381 @SuppressLint("SetJavaScriptEnabled")
3382 private boolean applyDomainSettings(NestedScrollWebView nestedScrollWebView, String url, boolean resetTab, boolean reloadWebsite) {
3383 // Store a copy of the current user agent to track changes for the return boolean.
3384 String initialUserAgent = nestedScrollWebView.getSettings().getUserAgentString();
3386 // Parse the URL into a URI.
3387 Uri uri = Uri.parse(url);
3389 // Extract the domain from `uri`.
3390 String newHostName = uri.getHost();
3392 // Strings don't like to be null.
3393 if (newHostName == null) {
3397 // 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.
3398 if (!nestedScrollWebView.getCurrentDomainName().equals(newHostName)) {
3399 // Set the new host name as the current domain name.
3400 nestedScrollWebView.setCurrentDomainName(newHostName);
3402 // Reset the ignoring of pinned domain information.
3403 nestedScrollWebView.setIgnorePinnedDomainInformation(false);
3405 // Clear any pinned SSL certificate or IP addresses.
3406 nestedScrollWebView.clearPinnedSslCertificate();
3407 nestedScrollWebView.clearPinnedIpAddresses();
3409 // Reset the favorite icon if specified.
3411 // Initialize the favorite icon.
3412 nestedScrollWebView.initializeFavoriteIcon();
3414 // Get the current page position.
3415 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
3417 // Get a handle for the tab layout.
3418 TabLayout tabLayout = findViewById(R.id.tablayout);
3420 // Get the corresponding tab.
3421 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
3423 // Remove the warning below that the tab might be null.
3426 // Get the tab custom view.
3427 View tabCustomView = tab.getCustomView();
3429 // Remove the warning below that the tab custom view might be null.
3430 assert tabCustomView != null;
3432 // Get the tab views.
3433 ImageView tabFavoriteIconImageView = tabCustomView.findViewById(R.id.favorite_icon_imageview);
3434 TextView tabTitleTextView = tabCustomView.findViewById(R.id.title_textview);
3436 // Set the default favorite icon as the favorite icon for this tab.
3437 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(nestedScrollWebView.getFavoriteOrDefaultIcon(), 64, 64, true));
3439 // Set the loading title text.
3440 tabTitleTextView.setText(R.string.loading);
3443 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3444 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3446 // Get a full cursor from `domainsDatabaseHelper`.
3447 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3449 // Initialize `domainSettingsSet`.
3450 Set<String> domainSettingsSet = new HashSet<>();
3452 // Get the domain name column index.
3453 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3455 // Populate `domainSettingsSet`.
3456 for (int i = 0; i < domainNameCursor.getCount(); i++) {
3457 // Move `domainsCursor` to the current row.
3458 domainNameCursor.moveToPosition(i);
3460 // Store the domain name in `domainSettingsSet`.
3461 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3464 // Close `domainNameCursor.
3465 domainNameCursor.close();
3467 // Initialize the domain name in database variable.
3468 String domainNameInDatabase = null;
3470 // Check the hostname against the domain settings set.
3471 if (domainSettingsSet.contains(newHostName)) { // The hostname is contained in the domain settings set.
3472 // Record the domain name in the database.
3473 domainNameInDatabase = newHostName;
3475 // Set the domain settings applied tracker to true.
3476 nestedScrollWebView.setDomainSettingsApplied(true);
3477 } else { // The hostname is not contained in the domain settings set.
3478 // Set the domain settings applied tracker to false.
3479 nestedScrollWebView.setDomainSettingsApplied(false);
3482 // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3483 while (!nestedScrollWebView.getDomainSettingsApplied() && newHostName.contains(".")) { // Stop checking if domain settings are already applied or there are no more `.` in the host name.
3484 if (domainSettingsSet.contains("*." + newHostName)) { // Check the host name prepended by `*.`.
3485 // Set the domain settings applied tracker to true.
3486 nestedScrollWebView.setDomainSettingsApplied(true);
3488 // Store the applied domain names as it appears in the database.
3489 domainNameInDatabase = "*." + newHostName;
3492 // Strip out the lowest subdomain of of the host name.
3493 newHostName = newHostName.substring(newHostName.indexOf(".") + 1);
3497 // Get a handle for the shared preferences.
3498 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3500 // Store the general preference information.
3501 String defaultFontSizeString = sharedPreferences.getString("font_size", getString(R.string.font_size_default_value));
3502 String defaultUserAgentName = sharedPreferences.getString("user_agent", getString(R.string.user_agent_default_value));
3503 boolean defaultSwipeToRefresh = sharedPreferences.getBoolean("swipe_to_refresh", true);
3504 boolean displayWebpageImages = sharedPreferences.getBoolean("display_webpage_images", true);
3505 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
3507 // Get a handle for the cookie manager.
3508 CookieManager cookieManager = CookieManager.getInstance();
3510 // Get handles for the views.
3511 RelativeLayout urlRelativeLayout = findViewById(R.id.url_relativelayout);
3512 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
3514 // Initialize the user agent array adapter and string array.
3515 ArrayAdapter<CharSequence> userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item);
3516 String[] userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
3518 if (nestedScrollWebView.getDomainSettingsApplied()) { // The url has custom domain settings.
3519 // Get a cursor for the current host and move it to the first position.
3520 Cursor currentDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3521 currentDomainSettingsCursor.moveToFirst();
3523 // Get the settings from the cursor.
3524 nestedScrollWebView.setDomainSettingsDatabaseId(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3525 nestedScrollWebView.setDomainSettingsJavaScriptEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3526 nestedScrollWebView.setAcceptFirstPartyCookies(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3527 boolean domainThirdPartyCookiesEnabled = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3528 nestedScrollWebView.getSettings().setDomStorageEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3529 // Form data can be removed once the minimum API >= 26.
3530 boolean saveFormData = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3531 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASY_LIST,
3532 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3533 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASY_PRIVACY,
3534 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3535 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST,
3536 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3537 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST,
3538 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3539 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRA_PRIVACY,
3540 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_ULTRAPRIVACY)) == 1);
3541 nestedScrollWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS,
3542 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
3543 String userAgentName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3544 int fontSize = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3545 int swipeToRefreshInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
3546 int nightModeInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
3547 int displayWebpageImagesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3548 boolean pinnedSslCertificate = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3549 String pinnedSslIssuedToCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3550 String pinnedSslIssuedToOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3551 String pinnedSslIssuedToUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3552 String pinnedSslIssuedByCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3553 String pinnedSslIssuedByOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3554 String pinnedSslIssuedByUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3555 boolean pinnedIpAddresses = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_IP_ADDRESSES)) == 1);
3556 String pinnedHostIpAddresses = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.IP_ADDRESSES));
3558 // Create the pinned SSL date variables.
3559 Date pinnedSslStartDate;
3560 Date pinnedSslEndDate;
3562 // 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.
3563 if (currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
3564 pinnedSslStartDate = null;
3566 pinnedSslStartDate = new Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
3569 // 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.
3570 if (currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
3571 pinnedSslEndDate = null;
3573 pinnedSslEndDate = new Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
3576 // If there is a pinned SSL certificate, store it in the WebView.
3577 if (pinnedSslCertificate) {
3578 nestedScrollWebView.setPinnedSslCertificate(pinnedSslIssuedToCName, pinnedSslIssuedToOName, pinnedSslIssuedToUName, pinnedSslIssuedByCName, pinnedSslIssuedByOName, pinnedSslIssuedByUName,
3579 pinnedSslStartDate, pinnedSslEndDate);
3582 // If there is a pinned IP address, store it in the WebView.
3583 if (pinnedIpAddresses) {
3584 nestedScrollWebView.setPinnedIpAddresses(pinnedHostIpAddresses);
3587 // Set night mode according to the night mode int.
3588 switch (nightModeInt) {
3589 case DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT:
3590 // Set night mode according to the current default.
3591 nestedScrollWebView.setNightMode(sharedPreferences.getBoolean("night_mode", false));
3594 case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
3595 // Enable night mode.
3596 nestedScrollWebView.setNightMode(true);
3599 case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
3600 // Disable night mode.
3601 nestedScrollWebView.setNightMode(false);
3605 // Enable JavaScript if night mode is enabled.
3606 if (nestedScrollWebView.getNightMode()) {
3607 // Enable JavaScript.
3608 nestedScrollWebView.getSettings().setJavaScriptEnabled(true);
3610 // Set JavaScript according to the domain settings.
3611 nestedScrollWebView.getSettings().setJavaScriptEnabled(nestedScrollWebView.getDomainSettingsJavaScriptEnabled());
3614 // Close the current host domain settings cursor.
3615 currentDomainSettingsCursor.close();
3617 // Apply the domain settings.
3618 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptFirstPartyCookies());
3620 // Set third-party cookies status if API >= 21.
3621 if (Build.VERSION.SDK_INT >= 21) {
3622 cookieManager.setAcceptThirdPartyCookies(nestedScrollWebView, domainThirdPartyCookiesEnabled);
3625 // Apply the form data setting if the API < 26.
3626 if (Build.VERSION.SDK_INT < 26) {
3627 nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
3630 // Apply the font size.
3631 if (fontSize == 0) { // Apply the default font size.
3632 nestedScrollWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3633 } else { // Apply the specified font size.
3634 nestedScrollWebView.getSettings().setTextZoom(fontSize);
3637 // 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.
3638 // <https://redmine.stoutner.com/issues/160>
3639 if (nestedScrollWebView.getProgress() == 100) { // A URL is not loading.
3640 // Set the user agent.
3641 if (userAgentName.equals(getString(R.string.system_default_user_agent))) { // Use the system default user agent.
3642 // Get the array position of the default user agent name.
3643 int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3645 // Set the user agent according to the system default.
3646 switch (defaultUserAgentArrayPosition) {
3647 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
3648 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3649 nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
3652 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3653 // Set the user agent to `""`, which uses the default value.
3654 nestedScrollWebView.getSettings().setUserAgentString("");
3657 case SETTINGS_CUSTOM_USER_AGENT:
3658 // Set the default custom user agent.
3659 nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
3663 // Get the user agent string from the user agent data array
3664 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
3666 } else { // Set the user agent according to the stored name.
3667 // Get the array position of the user agent name.
3668 int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
3670 switch (userAgentArrayPosition) {
3671 case UNRECOGNIZED_USER_AGENT: // The user agent name contains a custom user agent.
3672 nestedScrollWebView.getSettings().setUserAgentString(userAgentName);
3675 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3676 // Set the user agent to `""`, which uses the default value.
3677 nestedScrollWebView.getSettings().setUserAgentString("");
3681 // Get the user agent string from the user agent data array.
3682 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3687 // Set swipe to refresh.
3688 switch (swipeToRefreshInt) {
3689 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_SYSTEM_DEFAULT:
3690 // Store the swipe to refresh status in the nested scroll WebView.
3691 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
3693 // 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.
3694 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
3697 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_ENABLED:
3698 // Store the swipe to refresh status in the nested scroll WebView.
3699 nestedScrollWebView.setSwipeToRefresh(true);
3701 // Enable swipe to refresh. This can be removed once the minimum API >= 23 because it is continuously set by an on scroll change listener.
3702 swipeRefreshLayout.setEnabled(true);
3705 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_DISABLED:
3706 // Store the swipe to refresh status in the nested scroll WebView.
3707 nestedScrollWebView.setSwipeToRefresh(false);
3709 // Disable swipe to refresh. This can be removed once the minimum API >= 23 because it is continuously set by an on scroll change listener.
3710 swipeRefreshLayout.setEnabled(false);
3713 // Set the loading of webpage images.
3714 switch (displayWebpageImagesInt) {
3715 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
3716 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
3719 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
3720 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(true);
3723 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
3724 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(false);
3728 // 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.
3730 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
3732 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
3734 } else { // The new URL does not have custom domain settings. Load the defaults.
3735 // Store the values from the shared preferences.
3736 boolean defaultJavaScriptEnabled = sharedPreferences.getBoolean("javascript", false);
3737 nestedScrollWebView.setAcceptFirstPartyCookies(sharedPreferences.getBoolean("first_party_cookies", false));
3738 boolean defaultThirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies", false);
3739 nestedScrollWebView.getSettings().setDomStorageEnabled(sharedPreferences.getBoolean("dom_storage", false));
3740 boolean saveFormData = sharedPreferences.getBoolean("save_form_data", false); // Form data can be removed once the minimum API >= 26.
3741 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASY_LIST, sharedPreferences.getBoolean("easylist", true));
3742 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASY_PRIVACY, sharedPreferences.getBoolean("easyprivacy", true));
3743 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, sharedPreferences.getBoolean("fanboys_annoyance_list", true));
3744 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, sharedPreferences.getBoolean("fanboys_social_blocking_list", true));
3745 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRA_PRIVACY, sharedPreferences.getBoolean("ultraprivacy", true));
3746 nestedScrollWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, sharedPreferences.getBoolean("block_all_third_party_requests", false));
3747 nestedScrollWebView.setNightMode(sharedPreferences.getBoolean("night_mode", false));
3749 // Enable JavaScript if night mode is enabled.
3750 if (nestedScrollWebView.getNightMode()) {
3751 // Enable JavaScript.
3752 nestedScrollWebView.getSettings().setJavaScriptEnabled(true);
3754 // Set JavaScript according to the domain settings.
3755 nestedScrollWebView.getSettings().setJavaScriptEnabled(defaultJavaScriptEnabled);
3758 // Apply the default settings.
3759 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptFirstPartyCookies());
3760 nestedScrollWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3762 // Apply the form data setting if the API < 26.
3763 if (Build.VERSION.SDK_INT < 26) {
3764 nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
3767 // Store the swipe to refresh status in the nested scroll WebView.
3768 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
3770 // Apply swipe to refresh according to the default.
3771 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
3773 // Reset the pinned variables.
3774 nestedScrollWebView.setDomainSettingsDatabaseId(-1);
3776 // Set third-party cookies status if API >= 21.
3777 if (Build.VERSION.SDK_INT >= 21) {
3778 cookieManager.setAcceptThirdPartyCookies(nestedScrollWebView, defaultThirdPartyCookiesEnabled);
3781 // 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.
3782 // <https://redmine.stoutner.com/issues/160>
3783 if (nestedScrollWebView.getProgress() == 100) { // A URL is not loading.
3784 // Get the array position of the user agent name.
3785 int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3787 // Set the user agent.
3788 switch (userAgentArrayPosition) {
3789 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
3790 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3791 nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
3794 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3795 // Set the user agent to `""`, which uses the default value.
3796 nestedScrollWebView.getSettings().setUserAgentString("");
3799 case SETTINGS_CUSTOM_USER_AGENT:
3800 // Set the default custom user agent.
3801 nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
3805 // Get the user agent string from the user agent data array
3806 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3810 // Set the loading of webpage images.
3811 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
3813 // Set a transparent background on URL edit text. The deprecated `getResources().getDrawable()` must be used until the minimum API >= 21.
3814 urlRelativeLayout.setBackground(getResources().getDrawable(R.color.transparent));
3817 // Close the domains database helper.
3818 domainsDatabaseHelper.close();
3820 // Update the privacy icons.
3821 updatePrivacyIcons(true);
3824 // Reload the website if returning from the Domains activity.
3825 if (reloadWebsite) {
3826 nestedScrollWebView.reload();
3829 // Return the user agent changed status.
3830 return !nestedScrollWebView.getSettings().getUserAgentString().equals(initialUserAgent);
3833 private void applyProxyThroughOrbot(boolean reloadWebsite) {
3834 // Get a handle for the shared preferences.
3835 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3837 // Get the search and theme preferences.
3838 String torSearchString = sharedPreferences.getString("tor_search", getString(R.string.tor_search_default_value));
3839 String torSearchCustomUrlString = sharedPreferences.getString("tor_search_custom_url", getString(R.string.tor_search_custom_url_default_value));
3840 String searchString = sharedPreferences.getString("search", getString(R.string.search_default_value));
3841 String searchCustomUrlString = sharedPreferences.getString("search_custom_url", getString(R.string.search_custom_url_default_value));
3842 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
3844 // Get a handle for the action bar. `getSupportActionBar()` must be used until the minimum API >= 21.
3845 ActionBar actionBar = getSupportActionBar();
3847 // Remove the incorrect lint warning later that the action bar might be null.
3848 assert actionBar != null;
3850 // Set the homepage, search, and proxy options.
3851 if (proxyThroughOrbot) { // Set the Tor options.
3852 // Set the search URL.
3853 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
3854 searchURL = torSearchCustomUrlString;
3855 } else { // Use the string from the pre-built list.
3856 searchURL = torSearchString;
3859 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
3860 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
3862 // Set the `appBar` background to indicate proxying through Orbot is enabled.
3864 actionBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
3866 actionBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
3869 // Check to see if Orbot is ready.
3870 if (!orbotStatus.equals("ON")) { // Orbot is not ready.
3871 // Set `waitingForOrbot`.
3872 waitingForOrbot = true;
3874 // Disable the wide view port so that the waiting for Orbot text is displayed correctly.
3875 currentWebView.getSettings().setUseWideViewPort(false);
3877 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
3878 currentWebView.loadData("<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>", "text/html", null);
3879 } else if (reloadWebsite) { // Orbot is ready and the website should be reloaded.
3880 // Reload the website.
3881 currentWebView.reload();
3883 } else { // Set the non-Tor options.
3884 // Set the search URL.
3885 if (searchString.equals("Custom URL")) { // Get the custom URL string.
3886 searchURL = searchCustomUrlString;
3887 } else { // Use the string from the pre-built list.
3888 searchURL = searchString;
3891 // Reset the proxy to default. The host is `""` and the port is `"0"`.
3892 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
3894 // Set the default `appBar` background.
3896 actionBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
3898 actionBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
3901 // Reset `waitingForOrbot.
3902 waitingForOrbot = false;
3904 // Reload the WebViews if requested.
3905 if (reloadWebsite) {
3906 // Reload the WebViews.
3907 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3908 // Get the WebView tab fragment.
3909 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3911 // Get the fragment view.
3912 View fragmentView = webViewTabFragment.getView();
3914 // Only reload the WebViews if they exist.
3915 if (fragmentView != null) {
3916 // Get the nested scroll WebView from the tab fragment.
3917 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3919 // Reload the WebView.
3920 nestedScrollWebView.reload();
3927 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
3928 // Only update the privacy icons if the options menu and the current WebView have already been populated.
3929 if ((optionsMenu != null) && (currentWebView != null)) {
3930 // Get a handle for the shared preferences.
3931 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3933 // Get the theme and screenshot preferences.
3934 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
3936 // Get handles for the menu items.
3937 MenuItem privacyMenuItem = optionsMenu.findItem(R.id.toggle_javascript);
3938 MenuItem firstPartyCookiesMenuItem = optionsMenu.findItem(R.id.toggle_first_party_cookies);
3939 MenuItem domStorageMenuItem = optionsMenu.findItem(R.id.toggle_dom_storage);
3940 MenuItem refreshMenuItem = optionsMenu.findItem(R.id.refresh);
3942 // Update the privacy icon.
3943 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is enabled.
3944 privacyMenuItem.setIcon(R.drawable.javascript_enabled);
3945 } else if (currentWebView.getAcceptFirstPartyCookies()) { // JavaScript is disabled but cookies are enabled.
3946 privacyMenuItem.setIcon(R.drawable.warning);
3947 } else { // All the dangerous features are disabled.
3948 privacyMenuItem.setIcon(R.drawable.privacy_mode);
3951 // Update the first-party cookies icon.
3952 if (currentWebView.getAcceptFirstPartyCookies()) { // First-party cookies are enabled.
3953 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
3954 } else { // First-party cookies are disabled.
3956 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_dark);
3958 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_light);
3962 // Update the DOM storage icon.
3963 if (currentWebView.getSettings().getJavaScriptEnabled() && currentWebView.getSettings().getDomStorageEnabled()) { // Both JavaScript and DOM storage are enabled.
3964 domStorageMenuItem.setIcon(R.drawable.dom_storage_enabled);
3965 } else if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is enabled but DOM storage is disabled.
3967 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
3969 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
3971 } else { // JavaScript is disabled, so DOM storage is ghosted.
3973 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
3975 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
3979 // Update the refresh icon.
3981 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
3983 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
3986 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
3987 if (runInvalidateOptionsMenu) {
3988 invalidateOptionsMenu();
3993 private void openUrlWithExternalApp(String url) {
3994 // Create a download intent. Not specifying the action type will display the maximum number of options.
3995 Intent downloadIntent = new Intent();
3997 // Set the URI and the MIME type. Specifying `text/html` displays a good number of options.
3998 downloadIntent.setDataAndType(Uri.parse(url), "text/html");
4000 // Flag the intent to open in a new task.
4001 downloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4003 // Show the chooser.
4004 startActivity(Intent.createChooser(downloadIntent, getString(R.string.open_with)));
4007 private void highlightUrlText() {
4008 // Get a handle for the URL edit text.
4009 EditText urlEditText = findViewById(R.id.url_edittext);
4011 // Only highlight the URL text if the box is not currently selected.
4012 if (!urlEditText.hasFocus()) {
4013 // Get the URL string.
4014 String urlString = urlEditText.getText().toString();
4016 // Highlight the URL according to the protocol.
4017 if (urlString.startsWith("file://")) { // This is a file URL.
4018 // De-emphasize only the protocol.
4019 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4020 } else if (urlString.startsWith("content://")) {
4021 // De-emphasize only the protocol.
4022 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 10, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4023 } else { // This is a web URL.
4024 // Get the index of the `/` immediately after the domain name.
4025 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
4027 // Create a base URL string.
4030 // Get the base URL.
4031 if (endOfDomainName > 0) { // There is at least one character after the base URL.
4032 // Get the base URL.
4033 baseUrl = urlString.substring(0, endOfDomainName);
4034 } else { // There are no characters after the base URL.
4035 // Set the base URL to be the entire URL string.
4036 baseUrl = urlString;
4039 // Get the index of the last `.` in the domain.
4040 int lastDotIndex = baseUrl.lastIndexOf(".");
4042 // Get the index of the penultimate `.` in the domain.
4043 int penultimateDotIndex = baseUrl.lastIndexOf(".", lastDotIndex - 1);
4045 // Markup the beginning of the URL.
4046 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
4047 urlEditText.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4049 // De-emphasize subdomains.
4050 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
4051 urlEditText.getText().setSpan(initialGrayColorSpan, 7, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4053 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
4054 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
4055 // De-emphasize the protocol and the additional subdomains.
4056 urlEditText.getText().setSpan(initialGrayColorSpan, 0, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4057 } else { // There is only one subdomain in the domain name.
4058 // De-emphasize only the protocol.
4059 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4063 // De-emphasize the text after the domain name.
4064 if (endOfDomainName > 0) {
4065 urlEditText.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4071 private void loadBookmarksFolder() {
4072 // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
4073 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
4075 // Populate the bookmarks cursor adapter. `this` specifies the `Context`. `false` disables `autoRequery`.
4076 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
4078 public View newView(Context context, Cursor cursor, ViewGroup parent) {
4079 // Inflate the individual item layout. `false` does not attach it to the root.
4080 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
4084 public void bindView(View view, Context context, Cursor cursor) {
4085 // Get handles for the views.
4086 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
4087 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
4089 // Get the favorite icon byte array from the cursor.
4090 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
4092 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
4093 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
4095 // Display the bitmap in `bookmarkFavoriteIcon`.
4096 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
4098 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
4099 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
4100 bookmarkNameTextView.setText(bookmarkNameString);
4102 // Make the font bold for folders.
4103 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
4104 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
4105 } else { // Reset the font to default for normal bookmarks.
4106 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
4111 // Get a handle for the bookmarks list view.
4112 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
4114 // Populate the list view with the adapter.
4115 bookmarksListView.setAdapter(bookmarksCursorAdapter);
4117 // Get a handle for the bookmarks title text view.
4118 TextView bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
4120 // Set the bookmarks drawer title.
4121 if (currentBookmarksFolder.isEmpty()) {
4122 bookmarksTitleTextView.setText(R.string.bookmarks);
4124 bookmarksTitleTextView.setText(currentBookmarksFolder);
4128 private void openWithApp(String url) {
4129 // Create the open with intent with `ACTION_VIEW`.
4130 Intent openWithAppIntent = new Intent(Intent.ACTION_VIEW);
4132 // Set the URI but not the MIME type. This should open all available apps.
4133 openWithAppIntent.setData(Uri.parse(url));
4135 // Flag the intent to open in a new task.
4136 openWithAppIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4138 // Show the chooser.
4139 startActivity(openWithAppIntent);
4142 private void openWithBrowser(String url) {
4143 // Create the open with intent with `ACTION_VIEW`.
4144 Intent openWithBrowserIntent = new Intent(Intent.ACTION_VIEW);
4146 // Set the URI and the MIME type. `"text/html"` should load browser options.
4147 openWithBrowserIntent.setDataAndType(Uri.parse(url), "text/html");
4149 // Flag the intent to open in a new task.
4150 openWithBrowserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4152 // Show the chooser.
4153 startActivity(openWithBrowserIntent);
4156 public void addTab(View view) {
4157 // Get a handle for the tab layout and the view pager.
4158 TabLayout tabLayout = findViewById(R.id.tablayout);
4159 ViewPager webViewPager = findViewById(R.id.webviewpager);
4161 // Get the new page number. The page numbers are 0 indexed, so the new page number will match the current count.
4162 int newTabNumber = tabLayout.getTabCount();
4165 tabLayout.addTab(tabLayout.newTab());
4168 TabLayout.Tab newTab = tabLayout.getTabAt(newTabNumber);
4170 // Remove the lint warning below that the current tab might be null.
4171 assert newTab != null;
4173 // Set a custom view on the new tab.
4174 newTab.setCustomView(R.layout.tab_custom_view);
4176 // Add the new WebView page.
4177 webViewPagerAdapter.addPage(newTabNumber, webViewPager);
4180 private void setCurrentWebView(int pageNumber) {
4181 // Get a handle for the shared preferences.
4182 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4184 // Get the theme preference.
4185 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
4187 // Get handles for the URL views.
4188 RelativeLayout urlRelativeLayout = findViewById(R.id.url_relativelayout);
4189 EditText urlEditText = findViewById(R.id.url_edittext);
4190 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
4192 //Stop the swipe to refresh indicator if it is running
4193 swipeRefreshLayout.setRefreshing(false);
4195 // Get the WebView tab fragment.
4196 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(pageNumber);
4198 // Get the fragment view.
4199 View fragmentView = webViewTabFragment.getView();
4201 // Set the current WebView if the fragment view is not null.
4202 if (fragmentView != null) {
4203 // Store the current WebView.
4204 currentWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4206 // Update the status of swipe to refresh.
4207 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
4208 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.
4209 // Enable the swipe refresh layout if the WebView is scrolled all the way to the top.
4210 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
4212 // Enable the swipe refresh layout.
4213 swipeRefreshLayout.setEnabled(true);
4215 } else { // Swipe to refresh is disabled.
4216 // Disable the swipe refresh layout.
4217 swipeRefreshLayout.setEnabled(false);
4220 // Get a handle for the cookie manager.
4221 CookieManager cookieManager = CookieManager.getInstance();
4223 // Set the first-party cookie status.
4224 cookieManager.setAcceptCookie(currentWebView.getAcceptFirstPartyCookies());
4226 // Update the privacy icons. `true` redraws the icons in the app bar.
4227 updatePrivacyIcons(true);
4229 // Clear the focus from the URL text box.
4230 urlEditText.clearFocus();
4232 // Get a handle for the input method manager.
4233 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
4235 // Remove the lint warning below that the input method manager might be null.
4236 assert inputMethodManager != null;
4238 // Hide the soft keyboard.
4239 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
4241 // Display the current URL in the URL text box.
4242 urlEditText.setText(currentWebView.getUrl());
4244 // Highlight the URL text.
4247 // Set the background to indicate the domain settings status.
4248 if (currentWebView.getDomainSettingsApplied()) {
4249 // 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.
4251 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
4253 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
4256 urlRelativeLayout.setBackground(getResources().getDrawable(R.color.transparent));
4262 public void initializeWebView(NestedScrollWebView nestedScrollWebView, int pageNumber, ProgressBar progressBar) {
4263 // Get handles for the activity views.
4264 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
4265 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
4266 RelativeLayout mainContentRelativeLayout = findViewById(R.id.main_content_relativelayout);
4267 ActionBar actionBar = getSupportActionBar();
4268 LinearLayout tabsLinearLayout = findViewById(R.id.tabs_linearlayout);
4269 EditText urlEditText = findViewById(R.id.url_edittext);
4270 TabLayout tabLayout = findViewById(R.id.tablayout);
4271 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
4273 // Remove the incorrect lint warning below that the action bar might be null.
4274 assert actionBar != null;
4276 // Get a handle for the activity
4277 Activity activity = this;
4279 // Get a handle for the input method manager.
4280 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
4282 // Instantiate the blocklist helper.
4283 BlockListHelper blockListHelper = new BlockListHelper();
4285 // Remove the lint warning below that the input method manager might be null.
4286 assert inputMethodManager != null;
4288 // Get a handle for the shared preferences.
4289 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4291 // Get the relevant preferences.
4292 boolean downloadWithExternalApp = sharedPreferences.getBoolean("download_with_external_app", false);
4294 // Initialize the favorite icon.
4295 nestedScrollWebView.initializeFavoriteIcon();
4297 // Set the app bar scrolling.
4298 nestedScrollWebView.setNestedScrollingEnabled(sharedPreferences.getBoolean("scroll_app_bar", true));
4300 // Allow pinch to zoom.
4301 nestedScrollWebView.getSettings().setBuiltInZoomControls(true);
4303 // Hide zoom controls.
4304 nestedScrollWebView.getSettings().setDisplayZoomControls(false);
4306 // Don't allow mixed content (HTTP and HTTPS) on the same website.
4307 if (Build.VERSION.SDK_INT >= 21) {
4308 nestedScrollWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW);
4311 // Set the WebView to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
4312 nestedScrollWebView.getSettings().setUseWideViewPort(true);
4314 // Set the WebView to load in overview mode (zoomed out to the maximum width).
4315 nestedScrollWebView.getSettings().setLoadWithOverviewMode(true);
4317 // Explicitly disable geolocation.
4318 nestedScrollWebView.getSettings().setGeolocationEnabled(false);
4320 // Create a double-tap gesture detector to toggle full-screen mode.
4321 GestureDetector doubleTapGestureDetector = new GestureDetector(getApplicationContext(), new GestureDetector.SimpleOnGestureListener() {
4322 // Override `onDoubleTap()`. All other events are handled using the default settings.
4324 public boolean onDoubleTap(MotionEvent event) {
4325 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
4326 // Toggle the full screen browsing mode tracker.
4327 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
4329 // Toggle the full screen browsing mode.
4330 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
4331 // Hide the app bar if specified.
4333 // Close the find on page bar if it is visible.
4334 closeFindOnPage(null);
4336 // Hide the tab linear layout.
4337 tabsLinearLayout.setVisibility(View.GONE);
4339 // Hide the action bar.
4343 // Hide the banner ad in the free flavor.
4344 if (BuildConfig.FLAVOR.contentEquals("free")) {
4345 AdHelper.hideAd(findViewById(R.id.adview));
4348 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
4349 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4351 /* Hide the system bars.
4352 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4353 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4354 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4355 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4357 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
4358 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
4359 } else { // Switch to normal viewing mode.
4360 // Show the tab linear layout.
4361 tabsLinearLayout.setVisibility(View.VISIBLE);
4363 // Show the action bar.
4366 // Show the banner ad in the free flavor.
4367 if (BuildConfig.FLAVOR.contentEquals("free")) {
4369 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
4372 // Remove the `SYSTEM_UI` flags from the root frame layout.
4373 rootFrameLayout.setSystemUiVisibility(0);
4375 // Add the translucent status flag.
4376 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4379 // Consume the double-tap.
4381 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
4387 // Pass all touch events on the WebView through the double-tap gesture detector.
4388 nestedScrollWebView.setOnTouchListener((View view, MotionEvent event) -> {
4389 // Call `performClick()` on the view, which is required for accessibility.
4390 view.performClick();
4392 // Send the event to the gesture detector.
4393 return doubleTapGestureDetector.onTouchEvent(event);
4396 // Register the WebView for a context menu. This is used to see link targets and download images.
4397 registerForContextMenu(nestedScrollWebView);
4399 // Allow the downloading of files.
4400 nestedScrollWebView.setDownloadListener((String url, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
4401 // Check if the download should be processed by an external app.
4402 if (downloadWithExternalApp) { // Download with an external app.
4403 // Create a download intent. Not specifying the action type will display the maximum number of options.
4404 Intent downloadIntent = new Intent();
4406 // Set the URI and the MIME type. Specifying `text/html` displays a good number of options.
4407 downloadIntent.setDataAndType(Uri.parse(url), "text/html");
4409 // Flag the intent to open in a new task.
4410 downloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4412 // Show the chooser.
4413 startActivity(Intent.createChooser(downloadIntent, getString(R.string.open_with)));
4414 } else { // Download with Android's download manager.
4415 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
4416 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission has not been granted.
4417 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
4419 // Store the variables for future use by `onRequestPermissionsResult()`.
4421 downloadContentDisposition = contentDisposition;
4422 downloadContentLength = contentLength;
4424 // Show a dialog if the user has previously denied the permission.
4425 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
4426 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
4427 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
4429 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
4430 downloadLocationPermissionDialogFragment.show(getSupportFragmentManager(), getString(R.string.download_location));
4431 } else { // Show the permission request directly.
4432 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
4433 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
4435 } else { // The storage permission has already been granted.
4436 // Get a handle for the download file alert dialog.
4437 DialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
4439 // Show the download file alert dialog.
4440 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
4445 // Update the find on page count.
4446 nestedScrollWebView.setFindListener(new WebView.FindListener() {
4447 // Get a handle for `findOnPageCountTextView`.
4448 final TextView findOnPageCountTextView = findViewById(R.id.find_on_page_count_textview);
4451 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
4452 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
4453 // Set `findOnPageCountTextView` to `0/0`.
4454 findOnPageCountTextView.setText(R.string.zero_of_zero);
4455 } else if (isDoneCounting) { // There are matches.
4456 // `activeMatchOrdinal` is zero-based.
4457 int activeMatch = activeMatchOrdinal + 1;
4459 // Build the match string.
4460 String matchString = activeMatch + "/" + numberOfMatches;
4462 // Set `findOnPageCountTextView`.
4463 findOnPageCountTextView.setText(matchString);
4468 if (Build.VERSION.SDK_INT >= 23) {
4469 nestedScrollWebView.setOnScrollChangeListener((View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) -> {
4470 // Update the status of swipe to refresh if it is enabled.
4471 if (nestedScrollWebView.getSwipeToRefresh()) {
4472 // Only enable swipe to refresh if the WebView is scrolled to the top.
4473 swipeRefreshLayout.setEnabled(scrollY == 0);
4478 // Set the web chrome client.
4479 nestedScrollWebView.setWebChromeClient(new WebChromeClient() {
4480 // Update the progress bar when a page is loading.
4482 public void onProgressChanged(WebView view, int progress) {
4483 // Inject the night mode CSS if night mode is enabled.
4484 if (nestedScrollWebView.getNightMode()) {
4485 // `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
4486 // used by WordPress. `text-decoration: none` removes all text underlines. `text-shadow: none` removes text shadows, which usually have a hard coded color.
4487 // `border: none` removes all borders, which can also be used to underline text. `a {color: #1565C0}` sets links to be a dark blue.
4488 // `::selection {background: #0D47A1}' sets the text selection highlight color to be a dark blue. `!important` takes precedent over any existing sub-settings.
4489 nestedScrollWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; " +
4490 "style.innerHTML = '* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important;" +
4491 "text-shadow: none !important; border: none !important;} a {color: #1565C0 !important;} ::selection {background: #0D47A1 !important;}'; parent.appendChild(style)})()", value -> {
4492 // Initialize a handler to display `mainWebView`.
4493 Handler displayWebViewHandler = new Handler();
4495 // Setup a runnable to display `mainWebView` after a delay to allow the CSS to be applied.
4496 Runnable displayWebViewRunnable = () -> {
4497 // Only display `mainWebView` if the progress bar is gone. This prevents the display of the `WebView` while it is still loading.
4498 if (progressBar.getVisibility() == View.GONE) {
4499 nestedScrollWebView.setVisibility(View.VISIBLE);
4503 // Display the WebView after 500 milliseconds.
4504 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
4508 // Update the progress bar.
4509 progressBar.setProgress(progress);
4511 // Set the visibility of the progress bar.
4512 if (progress < 100) {
4513 // Show the progress bar.
4514 progressBar.setVisibility(View.VISIBLE);
4516 // Hide the progress bar.
4517 progressBar.setVisibility(View.GONE);
4519 // Display the nested scroll WebView if night mode is disabled.
4520 // Because of a race condition between `applyDomainSettings` and `onPageStarted`,
4521 // when night mode is set by domain settings the WebView may be hidden even if night mode is not currently enabled.
4522 if (!nestedScrollWebView.getNightMode()) {
4523 nestedScrollWebView.setVisibility(View.VISIBLE);
4526 //Stop the swipe to refresh indicator if it is running
4527 swipeRefreshLayout.setRefreshing(false);
4531 // Set the favorite icon when it changes.
4533 public void onReceivedIcon(WebView view, Bitmap icon) {
4534 // Only update the favorite icon if the website has finished loading.
4535 if (progressBar.getVisibility() == View.GONE) {
4536 // Store the new favorite icon.
4537 nestedScrollWebView.setFavoriteOrDefaultIcon(icon);
4539 // Get the current page position.
4540 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
4542 // Get the current tab.
4543 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
4545 // Check to see if the tab has been populated.
4547 // Get the custom view from the tab.
4548 View tabView = tab.getCustomView();
4550 // Check to see if the custom tab view has been populated.
4551 if (tabView != null) {
4552 // Get the favorite icon image view from the tab.
4553 ImageView tabFavoriteIconImageView = tabView.findViewById(R.id.favorite_icon_imageview);
4555 // Display the favorite icon in the tab.
4556 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
4562 // Save a copy of the title when it changes.
4564 public void onReceivedTitle(WebView view, String title) {
4565 // Get the current page position.
4566 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
4568 // Get the current tab.
4569 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
4571 // Only populate the title text view if the tab has been fully created.
4573 // Get the custom view from the tab.
4574 View tabView = tab.getCustomView();
4576 // Remove the incorrect warning below that the current tab view might be null.
4577 assert tabView != null;
4579 // Get the title text view from the tab.
4580 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
4582 // Set the title as the tab text.
4583 tabTitleTextView.setText(title);
4587 // Enter full screen video.
4589 public void onShowCustomView(View video, CustomViewCallback callback) {
4590 // Get a handle for the full screen video frame layout.
4591 FrameLayout fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
4593 // Set the full screen video flag.
4594 displayingFullScreenVideo = true;
4596 // Pause the ad if this is the free flavor.
4597 if (BuildConfig.FLAVOR.contentEquals("free")) {
4598 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
4599 AdHelper.pauseAd(findViewById(R.id.adview));
4602 // Hide the keyboard.
4603 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
4605 // Hide the main content relative layout.
4606 mainContentRelativeLayout.setVisibility(View.GONE);
4608 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
4609 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
4611 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
4612 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4614 /* Hide the system bars.
4615 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4616 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4617 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4618 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4620 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
4621 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
4623 // Disable the sliding drawers.
4624 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
4626 // Add the video view to the full screen video frame layout.
4627 fullScreenVideoFrameLayout.addView(video);
4629 // Show the full screen video frame layout.
4630 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
4633 // Exit full screen video.
4635 public void onHideCustomView() {
4636 // Get a handle for the full screen video frame layout.
4637 FrameLayout fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
4639 // Unset the full screen video flag.
4640 displayingFullScreenVideo = false;
4642 // Remove all the views from the full screen video frame layout.
4643 fullScreenVideoFrameLayout.removeAllViews();
4645 // Hide the full screen video frame layout.
4646 fullScreenVideoFrameLayout.setVisibility(View.GONE);
4648 // Enable the sliding drawers.
4649 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
4651 // Show the main content relative layout.
4652 mainContentRelativeLayout.setVisibility(View.VISIBLE);
4654 // Apply the appropriate full screen mode flags.
4655 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
4656 // Hide the app bar if specified.
4658 // Hide the tab linear layout.
4659 tabsLinearLayout.setVisibility(View.GONE);
4661 // Hide the action bar.
4665 // Hide the banner ad in the free flavor.
4666 if (BuildConfig.FLAVOR.contentEquals("free")) {
4667 AdHelper.hideAd(findViewById(R.id.adview));
4670 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
4671 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4673 /* Hide the system bars.
4674 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4675 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4676 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4677 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4679 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
4680 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
4681 } else { // Switch to normal viewing mode.
4682 // Remove the `SYSTEM_UI` flags from the root frame layout.
4683 rootFrameLayout.setSystemUiVisibility(0);
4685 // Add the translucent status flag.
4686 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4689 // Reload the ad for the free flavor if not in full screen mode.
4690 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
4692 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
4698 public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
4699 // Show the file chooser if the device is running API >= 21.
4700 if (Build.VERSION.SDK_INT >= 21) {
4701 // Store the file path callback.
4702 fileChooserCallback = filePathCallback;
4704 // Create an intent to open a chooser based ont the file chooser parameters.
4705 Intent fileChooserIntent = fileChooserParams.createIntent();
4707 // Open the file chooser. Currently only one `startActivityForResult` exists in this activity, so the request code, used to differentiate them, is simply `0`.
4708 startActivityForResult(fileChooserIntent, 0);
4714 nestedScrollWebView.setWebViewClient(new WebViewClient() {
4715 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
4716 // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
4718 public boolean shouldOverrideUrlLoading(WebView view, String url) {
4719 if (url.startsWith("http")) { // Load the URL in Privacy Browser.
4720 // Apply the domain settings for the new URL. This doesn't do anything if the domain has not changed.
4721 boolean userAgentChanged = applyDomainSettings(nestedScrollWebView, url, true, false);
4723 // Check if the user agent has changed.
4724 if (userAgentChanged) {
4725 // Manually load the URL. The changing of the user agent will cause WebView to reload the previous URL.
4726 nestedScrollWebView.loadUrl(url, customHeaders);
4728 // Returning true indicates that Privacy Browser is manually handling the loading of the URL.
4731 // Returning false causes the current WebView to handle the URL and prevents it from adding redirects to the history list.
4734 } else if (url.startsWith("mailto:")) { // Load the email address in an external email program.
4735 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
4736 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
4738 // Parse the url and set it as the data for the intent.
4739 emailIntent.setData(Uri.parse(url));
4741 // Open the email program in a new task instead of as part of Privacy Browser.
4742 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4745 startActivity(emailIntent);
4747 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
4749 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
4750 // Open the dialer and load the phone number, but wait for the user to place the call.
4751 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
4753 // Add the phone number to the intent.
4754 dialIntent.setData(Uri.parse(url));
4756 // Open the dialer in a new task instead of as part of Privacy Browser.
4757 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4760 startActivity(dialIntent);
4762 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
4764 } else { // Load a system chooser to select an app that can handle the URL.
4765 // Open an app that can handle the URL.
4766 Intent genericIntent = new Intent(Intent.ACTION_VIEW);
4768 // Add the URL to the intent.
4769 genericIntent.setData(Uri.parse(url));
4771 // List all apps that can handle the URL instead of just opening the first one.
4772 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
4774 // Open the app in a new task instead of as part of Privacy Browser.
4775 genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4777 // Start the app or display a snackbar if no app is available to handle the URL.
4779 startActivity(genericIntent);
4780 } catch (ActivityNotFoundException exception) {
4781 Snackbar.make(nestedScrollWebView, getString(R.string.unrecognized_url) + " " + url, Snackbar.LENGTH_SHORT).show();
4784 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
4789 // Check requests against the block lists. The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
4791 public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
4792 // Get a handle for the navigation view.
4793 NavigationView navigationView = findViewById(R.id.navigationview);
4795 // Get a handle for the navigation menu.
4796 Menu navigationMenu = navigationView.getMenu();
4798 // Get a handle for the navigation requests menu item. The menu is 0 based.
4799 MenuItem navigationRequestsMenuItem = navigationMenu.getItem(6);
4801 // Create an empty web resource response to be used if the resource request is blocked.
4802 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
4804 // Reset the whitelist results tracker.
4805 String[] whitelistResultStringArray = null;
4807 // Initialize the third party request tracker.
4808 boolean isThirdPartyRequest = false;
4810 // Get the current URL. `.getUrl()` throws an error because operations on the WebView cannot be made from this thread.
4811 String currentBaseDomain = nestedScrollWebView.getCurrentDomainName();
4813 // Store a copy of the current domain for use in later requests.
4814 String currentDomain = currentBaseDomain;
4816 // Nobody is happy when comparing null strings.
4817 if ((currentBaseDomain != null) && (url != null)) {
4818 // Convert the request URL to a URI.
4819 Uri requestUri = Uri.parse(url);
4821 // Get the request host name.
4822 String requestBaseDomain = requestUri.getHost();
4824 // Only check for third-party requests if the current base domain is not empty and the request domain is not null.
4825 if (!currentBaseDomain.isEmpty() && (requestBaseDomain != null)) {
4826 // Determine the current base domain.
4827 while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
4828 // Remove the first subdomain.
4829 currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
4832 // Determine the request base domain.
4833 while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
4834 // Remove the first subdomain.
4835 requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
4838 // Update the third party request tracker.
4839 isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
4843 // Get the current WebView page position.
4844 int webViewPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
4846 // Determine if the WebView is currently displayed.
4847 boolean webViewDisplayed = (webViewPagePosition == tabLayout.getSelectedTabPosition());
4849 // Block third-party requests if enabled.
4850 if (isThirdPartyRequest && nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS)) {
4851 // Add the result to the resource requests.
4852 nestedScrollWebView.addResourceRequest(new String[]{BlockListHelper.REQUEST_THIRD_PARTY, url});
4854 // Increment the blocked requests counters.
4855 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
4856 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS);
4858 // Update the titles of the blocklist menu items if the WebView is currently displayed.
4859 if (webViewDisplayed) {
4860 // Updating the UI must be run from the UI thread.
4861 activity.runOnUiThread(() -> {
4862 // Update the menu item titles.
4863 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
4865 // Update the options menu if it has been populated.
4866 if (optionsMenu != null) {
4867 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
4868 optionsMenu.findItem(R.id.block_all_third_party_requests).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " +
4869 getString(R.string.block_all_third_party_requests));
4874 // Return an empty web resource response.
4875 return emptyWebResourceResponse;
4878 // Check UltraPrivacy if it is enabled.
4879 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY)) {
4880 // Check the URL against UltraPrivacy.
4881 String[] ultraPrivacyResults = blockListHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraPrivacy);
4883 // Process the UltraPrivacy results.
4884 if (ultraPrivacyResults[0].equals(BlockListHelper.REQUEST_BLOCKED)) { // The resource request matched UltraPrivacy's blacklist.
4885 // Add the result to the resource requests.
4886 nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
4887 ultraPrivacyResults[5]});
4889 // Increment the blocked requests counters.
4890 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
4891 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRA_PRIVACY);
4893 // Update the titles of the blocklist menu items if the WebView is currently displayed.
4894 if (webViewDisplayed) {
4895 // Updating the UI must be run from the UI thread.
4896 activity.runOnUiThread(() -> {
4897 // Update the menu item titles.
4898 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
4900 // Update the options menu if it has been populated.
4901 if (optionsMenu != null) {
4902 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
4903 optionsMenu.findItem(R.id.ultraprivacy).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRA_PRIVACY) + " - " + getString(R.string.ultraprivacy));
4908 // The resource request was blocked. Return an empty web resource response.
4909 return emptyWebResourceResponse;
4910 } else if (ultraPrivacyResults[0].equals(BlockListHelper.REQUEST_ALLOWED)) { // The resource request matched UltraPrivacy's whitelist.
4911 // Add a whitelist entry to the resource requests array.
4912 nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
4913 ultraPrivacyResults[5]});
4915 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
4920 // Check EasyList if it is enabled.
4921 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST)) {
4922 // Check the URL against EasyList.
4923 String[] easyListResults = blockListHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyList);
4925 // Process the EasyList results.
4926 if (easyListResults[0].equals(BlockListHelper.REQUEST_BLOCKED)) { // The resource request matched EasyList's blacklist.
4927 // Add the result to the resource requests.
4928 nestedScrollWebView.addResourceRequest(new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]});
4930 // Increment the blocked requests counters.
4931 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
4932 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASY_LIST);
4934 // Update the titles of the blocklist menu items if the WebView is currently displayed.
4935 if (webViewDisplayed) {
4936 // Updating the UI must be run from the UI thread.
4937 activity.runOnUiThread(() -> {
4938 // Update the menu item titles.
4939 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
4941 // Update the options menu if it has been populated.
4942 if (optionsMenu != null) {
4943 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
4944 optionsMenu.findItem(R.id.easylist).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASY_LIST) + " - " + getString(R.string.easylist));
4949 // The resource request was blocked. Return an empty web resource response.
4950 return emptyWebResourceResponse;
4951 } else if (easyListResults[0].equals(BlockListHelper.REQUEST_ALLOWED)) { // The resource request matched EasyList's whitelist.
4952 // Update the whitelist result string array tracker.
4953 whitelistResultStringArray = new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]};
4957 // Check EasyPrivacy if it is enabled.
4958 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY)) {
4959 // Check the URL against EasyPrivacy.
4960 String[] easyPrivacyResults = blockListHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyPrivacy);
4962 // Process the EasyPrivacy results.
4963 if (easyPrivacyResults[0].equals(BlockListHelper.REQUEST_BLOCKED)) { // The resource request matched EasyPrivacy's blacklist.
4964 // Add the result to the resource requests.
4965 nestedScrollWebView.addResourceRequest(new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4],
4966 easyPrivacyResults[5]});
4968 // Increment the blocked requests counters.
4969 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
4970 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASY_PRIVACY);
4972 // Update the titles of the blocklist menu items if the WebView is currently displayed.
4973 if (webViewDisplayed) {
4974 // Updating the UI must be run from the UI thread.
4975 activity.runOnUiThread(() -> {
4976 // Update the menu item titles.
4977 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
4979 // Update the options menu if it has been populated.
4980 if (optionsMenu != null) {
4981 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
4982 optionsMenu.findItem(R.id.easyprivacy).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASY_PRIVACY) + " - " + getString(R.string.easyprivacy));
4987 // The resource request was blocked. Return an empty web resource response.
4988 return emptyWebResourceResponse;
4989 } else if (easyPrivacyResults[0].equals(BlockListHelper.REQUEST_ALLOWED)) { // The resource request matched EasyPrivacy's whitelist.
4990 // Update the whitelist result string array tracker.
4991 whitelistResultStringArray = new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5]};
4995 // Check Fanboy’s Annoyance List if it is enabled.
4996 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST)) {
4997 // Check the URL against Fanboy's Annoyance List.
4998 String[] fanboysAnnoyanceListResults = blockListHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList);
5000 // Process the Fanboy's Annoyance List results.
5001 if (fanboysAnnoyanceListResults[0].equals(BlockListHelper.REQUEST_BLOCKED)) { // The resource request matched Fanboy's Annoyance List's blacklist.
5002 // Add the result to the resource requests.
5003 nestedScrollWebView.addResourceRequest(new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5004 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]});
5006 // Increment the blocked requests counters.
5007 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5008 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST);
5010 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5011 if (webViewDisplayed) {
5012 // Updating the UI must be run from the UI thread.
5013 activity.runOnUiThread(() -> {
5014 // Update the menu item titles.
5015 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5017 // Update the options menu if it has been populated.
5018 if (optionsMenu != null) {
5019 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5020 optionsMenu.findItem(R.id.fanboys_annoyance_list).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " +
5021 getString(R.string.fanboys_annoyance_list));
5026 // The resource request was blocked. Return an empty web resource response.
5027 return emptyWebResourceResponse;
5028 } else if (fanboysAnnoyanceListResults[0].equals(BlockListHelper.REQUEST_ALLOWED)){ // The resource request matched Fanboy's Annoyance List's whitelist.
5029 // Update the whitelist result string array tracker.
5030 whitelistResultStringArray = new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5031 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]};
5033 } else if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST)) { // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
5034 // Check the URL against Fanboy's Annoyance List.
5035 String[] fanboysSocialListResults = blockListHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysSocialList);
5037 // Process the Fanboy's Social Blocking List results.
5038 if (fanboysSocialListResults[0].equals(BlockListHelper.REQUEST_BLOCKED)) { // The resource request matched Fanboy's Social Blocking List's blacklist.
5039 // Add the result to the resource requests.
5040 nestedScrollWebView.addResourceRequest(new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5041 fanboysSocialListResults[4], fanboysSocialListResults[5]});
5043 // Increment the blocked requests counters.
5044 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5045 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST);
5047 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5048 if (webViewDisplayed) {
5049 // Updating the UI must be run from the UI thread.
5050 activity.runOnUiThread(() -> {
5051 // Update the menu item titles.
5052 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5054 // Update the options menu if it has been populated.
5055 if (optionsMenu != null) {
5056 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5057 optionsMenu.findItem(R.id.fanboys_social_blocking_list).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " +
5058 getString(R.string.fanboys_social_blocking_list));
5063 // The resource request was blocked. Return an empty web resource response.
5064 return emptyWebResourceResponse;
5065 } else if (fanboysSocialListResults[0].equals(BlockListHelper.REQUEST_ALLOWED)) { // The resource request matched Fanboy's Social Blocking List's whitelist.
5066 // Update the whitelist result string array tracker.
5067 whitelistResultStringArray = new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5068 fanboysSocialListResults[4], fanboysSocialListResults[5]};
5072 // Add the request to the log because it hasn't been processed by any of the previous checks.
5073 if (whitelistResultStringArray != null) { // The request was processed by a whitelist.
5074 nestedScrollWebView.addResourceRequest(whitelistResultStringArray);
5075 } else { // The request didn't match any blocklist entry. Log it as a default request.
5076 nestedScrollWebView.addResourceRequest(new String[]{BlockListHelper.REQUEST_DEFAULT, url});
5079 // The resource request has not been blocked. `return null` loads the requested resource.
5083 // Handle HTTP authentication requests.
5085 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
5086 // Store the handler.
5087 nestedScrollWebView.setHttpAuthHandler(handler);
5089 // Instantiate an HTTP authentication dialog.
5090 DialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm, nestedScrollWebView.getWebViewFragmentId());
5092 // Show the HTTP authentication dialog.
5093 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
5097 public void onPageStarted(WebView view, String url, Bitmap favicon) {
5098 // Get the theme preference.
5099 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
5101 // Reset the list of resource requests.
5102 nestedScrollWebView.clearResourceRequests();
5104 // Reset the requests counters.
5105 nestedScrollWebView.resetRequestsCounters();
5107 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
5108 if (nestedScrollWebView.getNightMode()) {
5109 nestedScrollWebView.setVisibility(View.INVISIBLE);
5112 // Hide the keyboard.
5113 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
5115 // Check to see if Privacy Browser is waiting on Orbot.
5116 if (!waitingForOrbot) { // Process the URL.
5117 // Get the current page position.
5118 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5120 // Update the URL text bar if the page is currently selected.
5121 if (tabLayout.getSelectedTabPosition() == currentPagePosition) {
5122 // Display the formatted URL text.
5123 urlEditText.setText(url);
5125 // Apply text highlighting to `urlTextBox`.
5129 // Reset the list of host IP addresses.
5130 nestedScrollWebView.clearCurrentIpAddresses();
5132 // Get a URI for the current URL.
5133 Uri currentUri = Uri.parse(url);
5135 // Get the IP addresses for the host.
5136 new GetHostIpAddresses(activity, getSupportFragmentManager(), nestedScrollWebView).execute(currentUri.getHost());
5138 // Apply any custom domain settings if the URL was loaded by navigating history.
5139 if (nestedScrollWebView.getNavigatingHistory()) {
5140 // Reset navigating history.
5141 nestedScrollWebView.setNavigatingHistory(false);
5143 // Apply the domain settings.
5144 boolean userAgentChanged = applyDomainSettings(nestedScrollWebView, url, true, false);
5146 // Manually load the URL if the user agent has changed, which will have caused the previous URL to be reloaded.
5147 if (userAgentChanged) {
5152 // Replace Refresh with Stop if the options menu has been created. (The WebView typically begins loading before the menu items are instantiated.)
5153 if (optionsMenu != null) {
5154 // Get a handle for the refresh menu item.
5155 MenuItem refreshMenuItem = optionsMenu.findItem(R.id.refresh);
5158 refreshMenuItem.setTitle(R.string.stop);
5160 // Get the app bar and theme preferences.
5161 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
5163 // If the icon is displayed in the AppBar, set it according to the theme.
5164 if (displayAdditionalAppBarIcons) {
5166 refreshMenuItem.setIcon(R.drawable.close_dark);
5168 refreshMenuItem.setIcon(R.drawable.close_light);
5176 public void onPageFinished(WebView view, String url) {
5177 // Reset the wide view port if it has been turned off by the waiting for Orbot message.
5178 if (!waitingForOrbot) {
5179 // Only use a wide view port if the URL starts with `http`, not for `file://` and `content://`.
5180 nestedScrollWebView.getSettings().setUseWideViewPort(url.startsWith("http"));
5183 // Flush any cookies to persistent storage. The cookie manager has become very lazy about flushing cookies in recent versions.
5184 if (nestedScrollWebView.getAcceptFirstPartyCookies() && Build.VERSION.SDK_INT >= 21) {
5185 CookieManager.getInstance().flush();
5188 // Update the Refresh menu item if the options menu has been created.
5189 if (optionsMenu != null) {
5190 // Get a handle for the refresh menu item.
5191 MenuItem refreshMenuItem = optionsMenu.findItem(R.id.refresh);
5193 // Reset the Refresh title.
5194 refreshMenuItem.setTitle(R.string.refresh);
5196 // Get the app bar and theme preferences.
5197 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
5198 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
5200 // If the icon is displayed in the AppBar, reset it according to the theme.
5201 if (displayAdditionalAppBarIcons) {
5203 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
5205 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
5210 // Clear the cache and history if Incognito Mode is enabled.
5211 if (incognitoModeEnabled) {
5212 // Clear the cache. `true` includes disk files.
5213 nestedScrollWebView.clearCache(true);
5215 // Clear the back/forward history.
5216 nestedScrollWebView.clearHistory();
5218 // Manually delete cache folders.
5220 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
5221 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
5222 String privateDataDirectoryString = getApplicationInfo().dataDir;
5224 // Delete the main cache directory.
5225 Runtime.getRuntime().exec("rm -rf " + privateDataDirectoryString + "/cache");
5227 // Delete the secondary `Service Worker` cache directory.
5228 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
5229 Runtime.getRuntime().exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
5230 } catch (IOException e) {
5231 // Do nothing if an error is thrown.
5235 // Update the URL text box and apply domain settings if not waiting on Orbot.
5236 if (!waitingForOrbot) {
5237 // Get the current page position.
5238 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5240 // Update the URL text bar if the page is currently selected.
5241 if (tabLayout.getSelectedTabPosition() == currentPagePosition) {
5242 // Check to see if the URL is `about:blank`.
5243 if (url.equals("about:blank")) { // The WebView is blank.
5244 // Display the hint in the URL edit text.
5245 urlEditText.setText("");
5247 // Request focus for the URL text box.
5248 urlEditText.requestFocus();
5250 // Display the keyboard.
5251 inputMethodManager.showSoftInput(urlEditText, 0);
5253 // Hide the WebView, which causes the default background color to be displayed according to the theme. // TODO
5254 nestedScrollWebView.setVisibility(View.GONE);
5256 // Apply the domain settings. This clears any settings from the previous domain.
5257 applyDomainSettings(nestedScrollWebView, "", true, false);
5258 } else { // The WebView has loaded a webpage.
5259 // Only update the URL text box if the user is not typing in it.
5260 if (!urlEditText.hasFocus()) {
5261 // Display the final URL. Getting the URL from the WebView instead of using the one provided by `onPageFinished()` makes websites like YouTube function correctly.
5262 urlEditText.setText(nestedScrollWebView.getUrl());
5264 // Apply text highlighting to the URL.
5270 // Check the current website information against any pinned domain information if the current IP addresses have been loaded.
5271 if ((nestedScrollWebView.hasPinnedSslCertificate() || nestedScrollWebView.hasPinnedIpAddresses()) && nestedScrollWebView.hasCurrentIpAddresses() &&
5272 !nestedScrollWebView.ignorePinnedDomainInformation()) {
5273 CheckPinnedMismatchHelper.checkPinnedMismatch(getSupportFragmentManager(), nestedScrollWebView);
5278 // Handle SSL Certificate errors.
5280 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
5281 // Get the current website SSL certificate.
5282 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
5284 // Extract the individual pieces of information from the current website SSL certificate.
5285 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
5286 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
5287 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
5288 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
5289 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
5290 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
5291 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
5292 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
5294 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
5295 if (nestedScrollWebView.hasPinnedSslCertificate()) {
5296 // Get the pinned SSL certificate.
5297 ArrayList<Object> pinnedSslCertificateArrayList = nestedScrollWebView.getPinnedSslCertificate();
5299 // Extract the arrays from the array list.
5300 String[] pinnedSslCertificateStringArray = (String[]) pinnedSslCertificateArrayList.get(0);
5301 Date[] pinnedSslCertificateDateArray = (Date[]) pinnedSslCertificateArrayList.get(1);
5303 // Check if the current SSL certificate matches the pinned certificate.
5304 if (currentWebsiteIssuedToCName.equals(pinnedSslCertificateStringArray[0]) && currentWebsiteIssuedToOName.equals(pinnedSslCertificateStringArray[1]) &&
5305 currentWebsiteIssuedToUName.equals(pinnedSslCertificateStringArray[2]) && currentWebsiteIssuedByCName.equals(pinnedSslCertificateStringArray[3]) &&
5306 currentWebsiteIssuedByOName.equals(pinnedSslCertificateStringArray[4]) && currentWebsiteIssuedByUName.equals(pinnedSslCertificateStringArray[5]) &&
5307 currentWebsiteSslStartDate.equals(pinnedSslCertificateDateArray[0]) && currentWebsiteSslEndDate.equals(pinnedSslCertificateDateArray[1])) {
5309 // An SSL certificate is pinned and matches the current domain certificate. Proceed to the website without displaying an error.
5312 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
5313 // Store the SSL error handler.
5314 nestedScrollWebView.setSslErrorHandler(handler);
5316 // Instantiate an SSL certificate error alert dialog.
5317 DialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error, nestedScrollWebView.getWebViewFragmentId());
5319 // Show the SSL certificate error dialog.
5320 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
5325 // Check to see if this is the first page.
5326 if (pageNumber == 0) {
5327 // Set this nested scroll WebView as the current WebView.
5328 currentWebView = nestedScrollWebView;
5330 // Apply the app settings from the shared preferences.
5333 // Load the website if not waiting for Orbot to connect.
5334 if (!waitingForOrbot) {
5335 // Get the intent that started the app.
5336 Intent launchingIntent = getIntent();
5338 // Get the information from the intent.
5339 String launchingIntentAction = launchingIntent.getAction();
5340 Uri launchingIntentUriData = launchingIntent.getData();
5342 // If the intent action is a web search, perform the search.
5343 if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) {
5344 // Create an encoded URL string.
5345 String encodedUrlString;
5347 // Sanitize the search input and convert it to a search.
5349 encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
5350 } catch (UnsupportedEncodingException exception) {
5351 encodedUrlString = "";
5354 // Load the completed search URL.
5355 loadUrl(searchURL + encodedUrlString);
5356 } else if (launchingIntentUriData != null){ // Check to see if the intent contains a new URL.
5357 // Load the URL from the intent.
5358 loadUrl(launchingIntentUriData.toString());
5359 } else { // The is no URL in the intent.
5360 // Select the homepage based on the proxy through Orbot status.
5361 if (proxyThroughOrbot) {
5362 // Load the Tor homepage.
5363 loadUrl(sharedPreferences.getString("tor_homepage", getString(R.string.tor_homepage_default_value)));
5365 // Load the normal homepage.
5366 loadUrl(sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));