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 // AppCompatActivity from android.support.v7.app.AppCompatActivity must be used to have access to the SupportActionBar until the minimum API is >= 21.
156 public class MainWebViewActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener,
157 DownloadFileDialog.DownloadFileListener, DownloadImageDialog.DownloadImageListener, DownloadLocationPermissionDialog.DownloadLocationPermissionDialogListener, EditBookmarkDialog.EditBookmarkListener,
158 EditBookmarkFolderDialog.EditBookmarkFolderListener, NavigationView.OnNavigationItemSelectedListener, WebViewTabFragment.NewTabListener {
160 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`, `onResume()`, and `applyProxyThroughOrbot()`.
161 public static String orbotStatus;
163 // The WebView pager adapter is accessed from `HttpAuthenticationDialog`, `PinnedMismatchDialog`, and `SslCertificateErrorDialog`. It is also used in `onCreate()`, `onResume()`, and `addTab()`.
164 public static WebViewPagerAdapter webViewPagerAdapter;
166 // The load URL on restart variables are public static so they can be accessed from `BookmarksActivity`. They are used in `onRestart()`.
167 public static boolean loadUrlOnRestart;
168 public static String urlToLoadOnRestart;
170 // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onRestart()`.
171 public static boolean restartFromBookmarksActivity;
173 // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`,
174 // `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
175 public static String currentBookmarksFolder;
177 // The user agent constants are public static so they can be accessed from `SettingsFragment`, `DomainsActivity`, and `DomainSettingsFragment`.
178 public final static int UNRECOGNIZED_USER_AGENT = -1;
179 public final static int SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1;
180 public final static int SETTINGS_CUSTOM_USER_AGENT = 12;
181 public final static int DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0;
182 public final static int DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2;
183 public final static int DOMAINS_CUSTOM_USER_AGENT = 13;
187 // The current WebView is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
188 // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, `applyProxyThroughOrbot()`, and `applyDomainSettings()`.
189 private NestedScrollWebView currentWebView;
191 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
192 private final Map<String, String> customHeaders = new HashMap<>();
194 // The search URL is set in `applyProxyThroughOrbot()` and used in `onCreate()`, `onNewIntent()`, `loadURLFromTextBox()`, and `initializeWebView()`.
195 private String searchURL;
197 // The options menu is set in `onCreateOptionsMenu()` and used in `onOptionsItemSelected()`, `updatePrivacyIcons()`, and `initializeWebView()`.
198 private Menu optionsMenu;
200 // The blocklists are populated in `onCreate()` and accessed from `initializeWebView()`.
201 private ArrayList<List<String[]>> easyList;
202 private ArrayList<List<String[]>> easyPrivacy;
203 private ArrayList<List<String[]>> fanboysAnnoyanceList;
204 private ArrayList<List<String[]>> fanboysSocialList;
205 private ArrayList<List<String[]>> ultraPrivacy;
207 // `webViewDefaultUserAgent` is used in `onCreate()` and `onPrepareOptionsMenu()`.
208 private String webViewDefaultUserAgent;
210 // `proxyThroughOrbot` is used in `onRestart()`, `onOptionsItemSelected()`, `applyAppSettings()`, and `applyProxyThroughOrbot()`.
211 private boolean proxyThroughOrbot;
213 // The incognito mode is set in `applyAppSettings()` and used in `initializeWebView()`.
214 private boolean incognitoModeEnabled;
216 // The full screen browsing mode tracker is set it `applyAppSettings()` and used in `initializeWebView()`.
217 private boolean fullScreenBrowsingModeEnabled;
219 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
220 private boolean inFullScreenBrowsingMode;
222 // The hide app bar tracker is used in `applyAppSettings()` and `initializeWebView()`.
223 private boolean hideAppBar;
225 // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
226 private boolean reapplyDomainSettingsOnRestart;
228 // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
229 private boolean reapplyAppSettingsOnRestart;
231 // `displayingFullScreenVideo` is used in `onCreate()` and `onResume()`.
232 private boolean displayingFullScreenVideo;
234 // `orbotStatusBroadcastReceiver` is used in `onCreate()` and `onDestroy()`.
235 private BroadcastReceiver orbotStatusBroadcastReceiver;
237 // `waitingForOrbot` is used in `onCreate()`, `onResume()`, and `applyProxyThroughOrbot()`.
238 private boolean waitingForOrbot;
240 // The action bar drawer toggle is initialized in `onCreate()` and used in `onResume()`.
241 private ActionBarDrawerToggle actionBarDrawerToggle;
243 // The color spans are used in `onCreate()` and `highlightUrlText()`.
244 private ForegroundColorSpan redColorSpan;
245 private ForegroundColorSpan initialGrayColorSpan;
246 private ForegroundColorSpan finalGrayColorSpan;
248 // The drawer header padding variables are used in `onCreate()` and `onConfigurationChanged()`.
249 private int drawerHeaderPaddingLeftAndRight;
250 private int drawerHeaderPaddingTop;
251 private int drawerHeaderPaddingBottom;
253 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onDestroy`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`,
254 // and `loadBookmarksFolder()`.
255 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
257 // `bookmarksCursor` is used in `onDestroy()`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
258 private Cursor bookmarksCursor;
260 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
261 private CursorAdapter bookmarksCursorAdapter;
263 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
264 private String oldFolderNameString;
266 // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
267 private ValueCallback<Uri[]> fileChooserCallback;
269 // The download strings are used in `onCreate()`, `onRequestPermissionResult()` and `initializeWebView()`.
270 private String downloadUrl;
271 private String downloadContentDisposition;
272 private long downloadContentLength;
274 // `downloadImageUrl` is used in `onCreateContextMenu()` and `onRequestPermissionResult()`.
275 private String downloadImageUrl;
277 // The request codes are used in `onCreate()`, `onCreateContextMenu()`, `onCloseDownloadLocationPermissionDialog()`, `onRequestPermissionResult()`, and `initializeWebView()`.
278 private final int DOWNLOAD_FILE_REQUEST_CODE = 1;
279 private final int DOWNLOAD_IMAGE_REQUEST_CODE = 2;
282 // Remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
283 @SuppressLint("ClickableViewAccessibility")
284 protected void onCreate(Bundle savedInstanceState) {
285 // Get a handle for the shared preferences.
286 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
288 // Get the theme and screenshot preferences.
289 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
290 boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
292 // Disable screenshots if not allowed.
293 if (!allowScreenshots) {
294 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
297 // Set the activity theme.
299 setTheme(R.style.PrivacyBrowserDark);
301 setTheme(R.style.PrivacyBrowserLight);
304 // Run the default commands.
305 super.onCreate(savedInstanceState);
307 // Set the content view.
308 setContentView(R.layout.main_framelayout);
310 // Get a handle for the input method.
311 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
313 // Remove the lint warning below that the input method manager might be null.
314 assert inputMethodManager != null;
316 // Get a handle for the toolbar.
317 Toolbar toolbar = findViewById(R.id.toolbar);
319 // Set the action bar. `SupportActionBar` must be used until the minimum API is >= 21.
320 setSupportActionBar(toolbar);
322 // Get a handle for the action bar.
323 ActionBar actionBar = getSupportActionBar();
325 // This is needed to get rid of the Android Studio warning that the action bar might be null.
326 assert actionBar != null;
328 // Add the custom layout, which shows the URL text bar.
329 actionBar.setCustomView(R.layout.url_app_bar);
330 actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
332 // Initialize the foreground color spans for highlighting the URLs. We have to use the deprecated `getColor()` until API >= 23.
333 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
334 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
335 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
337 // Get handles for the URL views.
338 EditText urlEditText = findViewById(R.id.url_edittext);
340 // Remove the formatting from `urlTextBar` when the user is editing the text.
341 urlEditText.setOnFocusChangeListener((View v, boolean hasFocus) -> {
342 if (hasFocus) { // The user is editing the URL text box.
343 // Remove the highlighting.
344 urlEditText.getText().removeSpan(redColorSpan);
345 urlEditText.getText().removeSpan(initialGrayColorSpan);
346 urlEditText.getText().removeSpan(finalGrayColorSpan);
347 } else { // The user has stopped editing the URL text box.
348 // Move to the beginning of the string.
349 urlEditText.setSelection(0);
351 // Reapply the highlighting.
356 // Set the go button on the keyboard to load the URL in `urlTextBox`.
357 urlEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
358 // If the event is a key-down event on the `enter` button, load the URL.
359 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
360 // Load the URL into the mainWebView and consume the event.
361 loadUrlFromTextBox();
363 // If the enter key was pressed, consume the event.
366 // If any other key was pressed, do not consume the event.
371 // Initialize the Orbot status and the waiting for Orbot trackers.
372 orbotStatus = "unknown";
373 waitingForOrbot = false;
375 // Create an Orbot status `BroadcastReceiver`.
376 orbotStatusBroadcastReceiver = new BroadcastReceiver() {
378 public void onReceive(Context context, Intent intent) {
379 // Store the content of the status message in `orbotStatus`.
380 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
382 // If Privacy Browser is waiting on Orbot, load the website now that Orbot is connected.
383 if (orbotStatus.equals("ON") && waitingForOrbot) {
384 // Reset the waiting for Orbot status.
385 waitingForOrbot = false;
387 // Get the intent that started the app.
388 Intent launchingIntent = getIntent();
390 // Get the information from the intent.
391 String launchingIntentAction = launchingIntent.getAction();
392 Uri launchingIntentUriData = launchingIntent.getData();
394 // If the intent action is a web search, perform the search.
395 if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) {
396 // Create an encoded URL string.
397 String encodedUrlString;
399 // Sanitize the search input and convert it to a search.
401 encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
402 } catch (UnsupportedEncodingException exception) {
403 encodedUrlString = "";
406 // Load the completed search URL.
407 loadUrl(searchURL + encodedUrlString);
408 } else if (launchingIntentUriData != null){ // Check to see if the intent contains a new URL.
409 // Load the URL from the intent.
410 loadUrl(launchingIntentUriData.toString());
411 } else { // The is no URL in the intent.
412 // Select the homepage based on the proxy through Orbot status.
413 if (proxyThroughOrbot) {
414 // Load the Tor homepage.
415 loadUrl(sharedPreferences.getString("tor_homepage", getString(R.string.tor_homepage_default_value)));
417 // Load the normal homepage.
418 loadUrl(sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
425 // Register `orbotStatusBroadcastReceiver` on `this` context.
426 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
428 // Instantiate the blocklist helper.
429 BlockListHelper blockListHelper = new BlockListHelper();
431 // Parse the block lists.
432 easyList = blockListHelper.parseBlockList(getAssets(), "blocklists/easylist.txt");
433 easyPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/easyprivacy.txt");
434 fanboysAnnoyanceList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-annoyance.txt");
435 fanboysSocialList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-social.txt");
436 ultraPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/ultraprivacy.txt");
438 // Get handles for views that need to be modified.
439 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
440 NavigationView navigationView = findViewById(R.id.navigationview);
441 TabLayout tabLayout = findViewById(R.id.tablayout);
442 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
443 ViewPager webViewPager = findViewById(R.id.webviewpager);
444 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
445 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
446 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
447 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
448 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
450 // Listen for touches on the navigation menu.
451 navigationView.setNavigationItemSelectedListener(this);
453 // Get handles for the navigation menu and the back and forward menu items. The menu is zero-based.
454 Menu navigationMenu = navigationView.getMenu();
455 MenuItem navigationCloseTabMenuItem = navigationMenu.getItem(0);
456 MenuItem navigationBackMenuItem = navigationMenu.getItem(3);
457 MenuItem navigationForwardMenuItem = navigationMenu.getItem(4);
458 MenuItem navigationHistoryMenuItem = navigationMenu.getItem(5);
459 MenuItem navigationRequestsMenuItem = navigationMenu.getItem(6);
461 // Initialize the web view pager adapter.
462 webViewPagerAdapter = new WebViewPagerAdapter(getSupportFragmentManager());
464 // Set the pager adapter on the web view pager.
465 webViewPager.setAdapter(webViewPagerAdapter);
467 // Store up to 100 tabs in memory.
468 webViewPager.setOffscreenPageLimit(100);
470 // Update the web view pager every time a tab is modified.
471 webViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
473 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
478 public void onPageSelected(int position) {
479 // Close the find on page bar if it is open.
480 closeFindOnPage(null);
482 // Set the current WebView.
483 setCurrentWebView(position);
485 // 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.
486 if (tabLayout.getSelectedTabPosition() != position) {
487 // Create a handler to select the tab.
488 Handler selectTabHandler = new Handler();
490 // Create a runnable select the new tab.
491 Runnable selectTabRunnable = () -> {
492 // Get a handle for the tab.
493 TabLayout.Tab tab = tabLayout.getTabAt(position);
495 // Assert that the tab is not null.
502 // Select the tab layout after 100 milliseconds, which leaves enough time for a new tab to be created.
503 selectTabHandler.postDelayed(selectTabRunnable, 100);
508 public void onPageScrollStateChanged(int state) {
513 // Display the View SSL Certificate dialog when the currently selected tab is reselected.
514 tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
516 public void onTabSelected(TabLayout.Tab tab) {
517 // Select the same page in the view pager.
518 webViewPager.setCurrentItem(tab.getPosition());
522 public void onTabUnselected(TabLayout.Tab tab) {
527 public void onTabReselected(TabLayout.Tab tab) {
528 // Instantiate the View SSL Certificate dialog.
529 DialogFragment viewSslCertificateDialogFragment = ViewSslCertificateDialog.displayDialog(currentWebView.getWebViewFragmentId());
531 // Display the View SSL Certificate dialog.
532 viewSslCertificateDialogFragment.show(getSupportFragmentManager(), getString(R.string.view_ssl_certificate));
536 // Add the first tab.
539 // Set the bookmarks drawer resources according to the theme. This can't be done in the layout due to compatibility issues with the `DrawerLayout` support widget.
540 // The deprecated `getResources().getDrawable()` must be used until the minimum API >= 21 and and `getResources().getColor()` must be used until the minimum API >= 23.
542 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
543 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
544 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
545 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
547 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
548 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
549 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
550 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
553 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
554 launchBookmarksActivityFab.setOnClickListener(v -> {
555 // Get a copy of the favorite icon bitmap.
556 Bitmap favoriteIconBitmap = currentWebView.getFavoriteOrDefaultIcon();
558 // Create a favorite icon byte array output stream.
559 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
561 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
562 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
564 // Convert the favorite icon byte array stream to a byte array.
565 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
567 // Create an intent to launch the bookmarks activity.
568 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
570 // Add the extra information to the intent.
571 bookmarksIntent.putExtra("current_url", currentWebView.getUrl());
572 bookmarksIntent.putExtra("current_title", currentWebView.getTitle());
573 bookmarksIntent.putExtra("current_folder", currentBookmarksFolder);
574 bookmarksIntent.putExtra("favorite_icon_byte_array", favoriteIconByteArray);
577 startActivity(bookmarksIntent);
580 // Set the create new bookmark folder FAB to display an alert dialog.
581 createBookmarkFolderFab.setOnClickListener(v -> {
582 // Create a create bookmark folder dialog.
583 DialogFragment createBookmarkFolderDialog = CreateBookmarkFolderDialog.createBookmarkFolder(currentWebView.getFavoriteOrDefaultIcon());
585 // Show the create bookmark folder dialog.
586 createBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.create_folder));
589 // Set the create new bookmark FAB to display an alert dialog.
590 createBookmarkFab.setOnClickListener(view -> {
591 // Instantiate the create bookmark dialog.
592 DialogFragment createBookmarkDialog = CreateBookmarkDialog.createBookmark(currentWebView.getUrl(), currentWebView.getTitle(), currentWebView.getFavoriteOrDefaultIcon());
594 // Display the create bookmark dialog.
595 createBookmarkDialog.show(getSupportFragmentManager(), getString(R.string.create_bookmark));
598 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
599 findOnPageEditText.addTextChangedListener(new TextWatcher() {
601 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
606 public void onTextChanged(CharSequence s, int start, int before, int count) {
611 public void afterTextChanged(Editable s) {
612 // Search for the text in the WebView if it is not null. Sometimes on resume after a period of non-use the WebView will be null.
613 if (currentWebView != null) {
614 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 if the URL is not null, which can happen if an empty tab is active when returning from settings.
898 if (nestedScrollWebView.getUrl() != null) {
899 applyDomainSettings(nestedScrollWebView, nestedScrollWebView.getUrl(), false, true);
905 // Load the URL on restart (used when loading a bookmark).
906 if (loadUrlOnRestart) {
907 // Load the specified URL.
908 loadUrl(urlToLoadOnRestart);
910 // Reset the load on restart tracker.
911 loadUrlOnRestart = false;
914 // Update the bookmarks drawer if returning from the Bookmarks activity.
915 if (restartFromBookmarksActivity) {
916 // Get a handle for the drawer layout.
917 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
919 // Close the bookmarks drawer.
920 drawerLayout.closeDrawer(GravityCompat.END);
922 // Reload the bookmarks drawer.
923 loadBookmarksFolder();
925 // Reset `restartFromBookmarksActivity`.
926 restartFromBookmarksActivity = false;
929 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
930 updatePrivacyIcons(true);
933 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
935 public void onResume() {
936 // Run the default commands.
939 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
940 // Get the WebView tab fragment.
941 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
943 // Get the fragment view.
944 View fragmentView = webViewTabFragment.getView();
946 // Only resume the WebViews if they exist (they won't when the app is first created).
947 if (fragmentView != null) {
948 // Get the nested scroll WebView from the tab fragment.
949 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
951 // Resume the nested scroll WebView JavaScript timers.
952 nestedScrollWebView.resumeTimers();
954 // Resume the nested scroll WebView.
955 nestedScrollWebView.onResume();
959 // Display a message to the user if waiting for Orbot.
960 if (waitingForOrbot && !orbotStatus.equals("ON")) {
961 // Disable the wide view port so that the waiting for Orbot text is displayed correctly.
962 currentWebView.getSettings().setUseWideViewPort(false);
964 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
965 currentWebView.loadData("<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>", "text/html", null);
968 if (displayingFullScreenVideo || inFullScreenBrowsingMode) {
969 // Get a handle for the root frame layouts.
970 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
972 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
973 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
975 /* Hide the system bars.
976 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
977 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
978 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
979 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
981 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
982 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
983 } else if (BuildConfig.FLAVOR.contentEquals("free")) { // Resume the adView for the free flavor.
985 AdHelper.resumeAd(findViewById(R.id.adview));
990 public void onPause() {
991 // Run the default commands.
994 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
995 // Get the WebView tab fragment.
996 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
998 // Get the fragment view.
999 View fragmentView = webViewTabFragment.getView();
1001 // Only pause the WebViews if they exist (they won't when the app is first created).
1002 if (fragmentView != null) {
1003 // Get the nested scroll WebView from the tab fragment.
1004 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
1006 // Pause the nested scroll WebView.
1007 nestedScrollWebView.onPause();
1009 // Pause the nested scroll WebView JavaScript timers.
1010 nestedScrollWebView.pauseTimers();
1014 // Pause the ad or it will continue to consume resources in the background on the free flavor.
1015 if (BuildConfig.FLAVOR.contentEquals("free")) {
1017 AdHelper.pauseAd(findViewById(R.id.adview));
1022 public void onDestroy() {
1023 // Unregister the Orbot status broadcast receiver.
1024 this.unregisterReceiver(orbotStatusBroadcastReceiver);
1026 // Close the bookmarks cursor and database.
1027 bookmarksCursor.close();
1028 bookmarksDatabaseHelper.close();
1030 // Run the default commands.
1035 public boolean onCreateOptionsMenu(Menu menu) {
1036 // Inflate the menu. This adds items to the action bar if it is present.
1037 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1039 // Store a handle for the options menu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons()`.
1042 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1043 updatePrivacyIcons(false);
1045 // Get handles for the menu items.
1046 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1047 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1048 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1049 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
1050 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
1051 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1052 MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
1054 // Only display third-party cookies if API >= 21
1055 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1057 // Only display the form data menu items if the API < 26.
1058 toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1059 clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1061 // Disable the clear form data menu item if the API >= 26 so that the status of the main Clear Data is calculated correctly.
1062 clearFormDataMenuItem.setEnabled(Build.VERSION.SDK_INT < 26);
1064 // Only show Ad Consent if this is the free flavor.
1065 adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
1067 // Get the shared preference values.
1068 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1070 // Get the dark theme and app bar preferences..
1071 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
1072 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
1074 // 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.
1075 if (displayAdditionalAppBarIcons) {
1076 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1077 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1078 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
1079 } else { //Do not display the additional icons.
1080 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1081 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1082 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1085 // Replace Refresh with Stop if a URL is already loading.
1086 if (currentWebView != null && currentWebView.getProgress() != 100) {
1088 refreshMenuItem.setTitle(R.string.stop);
1090 // If the icon is displayed in the AppBar, set it according to the theme.
1091 if (displayAdditionalAppBarIcons) {
1093 refreshMenuItem.setIcon(R.drawable.close_dark);
1095 refreshMenuItem.setIcon(R.drawable.close_light);
1104 public boolean onPrepareOptionsMenu(Menu menu) {
1105 // Get handles for the menu items.
1106 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
1107 MenuItem firstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1108 MenuItem thirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1109 MenuItem domStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1110 MenuItem saveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
1111 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
1112 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1113 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1114 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
1115 MenuItem blocklistsMenuItem = menu.findItem(R.id.blocklists);
1116 MenuItem easyListMenuItem = menu.findItem(R.id.easylist);
1117 MenuItem easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
1118 MenuItem fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
1119 MenuItem fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
1120 MenuItem ultraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
1121 MenuItem blockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
1122 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1123 MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
1124 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1125 MenuItem nightModeMenuItem = menu.findItem(R.id.night_mode);
1126 MenuItem proxyThroughOrbotMenuItem = menu.findItem(R.id.proxy_through_orbot);
1128 // Get a handle for the cookie manager.
1129 CookieManager cookieManager = CookieManager.getInstance();
1131 // Initialize the current user agent string and the font size.
1132 String currentUserAgent = getString(R.string.user_agent_privacy_browser);
1135 // 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.
1136 if (currentWebView != null) {
1137 // Set the add or edit domain text.
1138 if (currentWebView.getDomainSettingsApplied()) {
1139 addOrEditDomain.setTitle(R.string.edit_domain_settings);
1141 addOrEditDomain.setTitle(R.string.add_domain_settings);
1144 // Get the current user agent from the WebView.
1145 currentUserAgent = currentWebView.getSettings().getUserAgentString();
1147 // Get the current font size from the
1148 fontSize = currentWebView.getSettings().getTextZoom();
1150 // Set the status of the menu item checkboxes.
1151 domStorageMenuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1152 saveFormDataMenuItem.setChecked(currentWebView.getSettings().getSaveFormData()); // Form data can be removed once the minimum API >= 26.
1153 easyListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST));
1154 easyPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY));
1155 fanboysAnnoyanceListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1156 fanboysSocialBlockingListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1157 ultraPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY));
1158 blockAllThirdPartyRequestsMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1159 swipeToRefreshMenuItem.setChecked(currentWebView.getSwipeToRefresh());
1160 displayImagesMenuItem.setChecked(currentWebView.getSettings().getLoadsImagesAutomatically());
1161 nightModeMenuItem.setChecked(currentWebView.getNightMode());
1163 // Initialize the display names for the blocklists with the number of blocked requests.
1164 blocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
1165 easyListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASY_LIST) + " - " + getString(R.string.easylist));
1166 easyPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASY_PRIVACY) + " - " + getString(R.string.easyprivacy));
1167 fanboysAnnoyanceListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " + getString(R.string.fanboys_annoyance_list));
1168 fanboysSocialBlockingListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " + getString(R.string.fanboys_social_blocking_list));
1169 ultraPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRA_PRIVACY) + " - " + getString(R.string.ultraprivacy));
1170 blockAllThirdPartyRequestsMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " + getString(R.string.block_all_third_party_requests));
1172 // Only modify third-party cookies if the API >= 21.
1173 if (Build.VERSION.SDK_INT >= 21) {
1174 // Set the status of the third-party cookies checkbox.
1175 thirdPartyCookiesMenuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
1177 // Enable third-party cookies if first-party cookies are enabled.
1178 thirdPartyCookiesMenuItem.setEnabled(cookieManager.acceptCookie());
1181 // Enable DOM Storage if JavaScript is enabled.
1182 domStorageMenuItem.setEnabled(currentWebView.getSettings().getJavaScriptEnabled());
1185 // Set the status of the menu item checkboxes.
1186 firstPartyCookiesMenuItem.setChecked(cookieManager.acceptCookie());
1187 proxyThroughOrbotMenuItem.setChecked(proxyThroughOrbot);
1189 // Enable Clear Cookies if there are any.
1190 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1192 // 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`.
1193 String privateDataDirectoryString = getApplicationInfo().dataDir;
1195 // Get a count of the number of files in the Local Storage directory.
1196 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1197 int localStorageDirectoryNumberOfFiles = 0;
1198 if (localStorageDirectory.exists()) {
1199 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1202 // Get a count of the number of files in the IndexedDB directory.
1203 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1204 int indexedDBDirectoryNumberOfFiles = 0;
1205 if (indexedDBDirectory.exists()) {
1206 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1209 // Enable Clear DOM Storage if there is any.
1210 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1212 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
1213 if (Build.VERSION.SDK_INT < 26) {
1214 // Get the WebView database.
1215 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1217 // Enable the clear form data menu item if there is anything to clear.
1218 clearFormDataMenuItem.setEnabled(webViewDatabase.hasFormData());
1221 // Enable Clear Data if any of the submenu items are enabled.
1222 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
1224 // Disable Fanboy's Social Blocking List menu item if Fanboy's Annoyance List is checked.
1225 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListMenuItem.isChecked());
1227 // Select the current user agent menu item. A switch statement cannot be used because the user agents are not compile time constants.
1228 if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) { // Privacy Browser.
1229 menu.findItem(R.id.user_agent_privacy_browser).setChecked(true);
1230 } else if (currentUserAgent.equals(webViewDefaultUserAgent)) { // WebView Default.
1231 menu.findItem(R.id.user_agent_webview_default).setChecked(true);
1232 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) { // Firefox on Android.
1233 menu.findItem(R.id.user_agent_firefox_on_android).setChecked(true);
1234 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) { // Chrome on Android.
1235 menu.findItem(R.id.user_agent_chrome_on_android).setChecked(true);
1236 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) { // Safari on iOS.
1237 menu.findItem(R.id.user_agent_safari_on_ios).setChecked(true);
1238 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) { // Firefox on Linux.
1239 menu.findItem(R.id.user_agent_firefox_on_linux).setChecked(true);
1240 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) { // Chromium on Linux.
1241 menu.findItem(R.id.user_agent_chromium_on_linux).setChecked(true);
1242 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) { // Firefox on Windows.
1243 menu.findItem(R.id.user_agent_firefox_on_windows).setChecked(true);
1244 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) { // Chrome on Windows.
1245 menu.findItem(R.id.user_agent_chrome_on_windows).setChecked(true);
1246 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) { // Edge on Windows.
1247 menu.findItem(R.id.user_agent_edge_on_windows).setChecked(true);
1248 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) { // Internet Explorer on Windows.
1249 menu.findItem(R.id.user_agent_internet_explorer_on_windows).setChecked(true);
1250 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) { // Safari on macOS.
1251 menu.findItem(R.id.user_agent_safari_on_macos).setChecked(true);
1252 } else { // Custom user agent.
1253 menu.findItem(R.id.user_agent_custom).setChecked(true);
1256 // Instantiate the font size title and the selected font size menu item.
1257 String fontSizeTitle;
1258 MenuItem selectedFontSizeMenuItem;
1260 // Prepare the font size title and current size menu item.
1263 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
1264 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1268 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
1269 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1273 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
1274 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1278 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1279 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1283 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
1284 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1288 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
1289 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1293 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
1294 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1298 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
1299 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1303 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1304 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1308 // Set the font size title and select the current size menu item.
1309 fontSizeMenuItem.setTitle(fontSizeTitle);
1310 selectedFontSizeMenuItem.setChecked(true);
1312 // Run all the other default commands.
1313 super.onPrepareOptionsMenu(menu);
1315 // Display the menu.
1320 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1321 @SuppressLint("SetJavaScriptEnabled")
1322 public boolean onOptionsItemSelected(MenuItem menuItem) {
1323 // Reenter full screen browsing mode if it was interrupted by the options menu. <https://redmine.stoutner.com/issues/389>
1324 if (inFullScreenBrowsingMode) {
1325 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
1326 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1328 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
1330 /* Hide the system bars.
1331 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1332 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
1333 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1334 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1336 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
1337 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1340 // Get the selected menu item ID.
1341 int menuItemId = menuItem.getItemId();
1343 // Get a handle for the shared preferences.
1344 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1346 // Get a handle for the cookie manager.
1347 CookieManager cookieManager = CookieManager.getInstance();
1349 // Run the commands that correlate to the selected menu item.
1350 switch (menuItemId) {
1351 case R.id.toggle_javascript:
1352 // Toggle the JavaScript status.
1353 currentWebView.getSettings().setJavaScriptEnabled(!currentWebView.getSettings().getJavaScriptEnabled());
1355 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1356 updatePrivacyIcons(true);
1358 // Display a `Snackbar`.
1359 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScrip is enabled.
1360 Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1361 } else if (cookieManager.acceptCookie()) { // JavaScript is disabled, but first-party cookies are enabled.
1362 Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1363 } else { // Privacy mode.
1364 Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1367 // Reload the current WebView.
1368 currentWebView.reload();
1371 case R.id.add_or_edit_domain:
1372 if (currentWebView.getDomainSettingsApplied()) { // Edit the current domain settings.
1373 // Reapply the domain settings on returning to `MainWebViewActivity`.
1374 reapplyDomainSettingsOnRestart = true;
1376 // Create an intent to launch the domains activity.
1377 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1379 // Add the extra information to the intent.
1380 domainsIntent.putExtra("load_domain", currentWebView.getDomainSettingsDatabaseId());
1381 domainsIntent.putExtra("close_on_back", true);
1382 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1384 // Get the current certificate.
1385 SslCertificate sslCertificate = currentWebView.getCertificate();
1387 // Check to see if the SSL certificate is populated.
1388 if (sslCertificate != null) {
1389 // Extract the certificate to strings.
1390 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1391 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1392 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1393 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1394 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1395 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1396 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1397 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1399 // Add the certificate to the intent.
1400 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1401 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1402 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1403 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1404 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1405 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1406 domainsIntent.putExtra("ssl_start_date", startDateLong);
1407 domainsIntent.putExtra("ssl_end_date", endDateLong);
1410 // Check to see if the current IP addresses have been received.
1411 if (currentWebView.hasCurrentIpAddresses()) {
1412 // Add the current IP addresses to the intent.
1413 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1417 startActivity(domainsIntent);
1418 } else { // Add a new domain.
1419 // Apply the new domain settings on returning to `MainWebViewActivity`.
1420 reapplyDomainSettingsOnRestart = true;
1422 // Get the current domain
1423 Uri currentUri = Uri.parse(currentWebView.getUrl());
1424 String currentDomain = currentUri.getHost();
1426 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1427 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1429 // Create the domain and store the database ID.
1430 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1432 // Create an intent to launch the domains activity.
1433 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1435 // Add the extra information to the intent.
1436 domainsIntent.putExtra("load_domain", newDomainDatabaseId);
1437 domainsIntent.putExtra("close_on_back", true);
1438 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1440 // Get the current certificate.
1441 SslCertificate sslCertificate = currentWebView.getCertificate();
1443 // Check to see if the SSL certificate is populated.
1444 if (sslCertificate != null) {
1445 // Extract the certificate to strings.
1446 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1447 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1448 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1449 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1450 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1451 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1452 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1453 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1455 // Add the certificate to the intent.
1456 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1457 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1458 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1459 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1460 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1461 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1462 domainsIntent.putExtra("ssl_start_date", startDateLong);
1463 domainsIntent.putExtra("ssl_end_date", endDateLong);
1466 // Check to see if the current IP addresses have been received.
1467 if (currentWebView.hasCurrentIpAddresses()) {
1468 // Add the current IP addresses to the intent.
1469 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1473 startActivity(domainsIntent);
1477 case R.id.toggle_first_party_cookies:
1478 // Switch the first-party cookie status.
1479 cookieManager.setAcceptCookie(!cookieManager.acceptCookie());
1481 // Store the first-party cookie status.
1482 currentWebView.setAcceptFirstPartyCookies(cookieManager.acceptCookie());
1484 // Update the menu checkbox.
1485 menuItem.setChecked(cookieManager.acceptCookie());
1487 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1488 updatePrivacyIcons(true);
1490 // Display a snackbar.
1491 if (cookieManager.acceptCookie()) { // First-party cookies are enabled.
1492 Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1493 } else if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is still enabled.
1494 Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1495 } else { // Privacy mode.
1496 Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1499 // Reload the current WebView.
1500 currentWebView.reload();
1503 case R.id.toggle_third_party_cookies:
1504 if (Build.VERSION.SDK_INT >= 21) {
1505 // Switch the status of thirdPartyCookiesEnabled.
1506 cookieManager.setAcceptThirdPartyCookies(currentWebView, !cookieManager.acceptThirdPartyCookies(currentWebView));
1508 // Update the menu checkbox.
1509 menuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
1511 // Display a snackbar.
1512 if (cookieManager.acceptThirdPartyCookies(currentWebView)) {
1513 Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1515 Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1518 // Reload the current WebView.
1519 currentWebView.reload();
1520 } // Else do nothing because SDK < 21.
1523 case R.id.toggle_dom_storage:
1524 // Toggle the status of domStorageEnabled.
1525 currentWebView.getSettings().setDomStorageEnabled(!currentWebView.getSettings().getDomStorageEnabled());
1527 // Update the menu checkbox.
1528 menuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1530 // Update the privacy icon. `true` refreshes the app bar icons.
1531 updatePrivacyIcons(true);
1533 // Display a snackbar.
1534 if (currentWebView.getSettings().getDomStorageEnabled()) {
1535 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1537 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1540 // Reload the current WebView.
1541 currentWebView.reload();
1544 // Form data can be removed once the minimum API >= 26.
1545 case R.id.toggle_save_form_data:
1546 // Switch the status of saveFormDataEnabled.
1547 currentWebView.getSettings().setSaveFormData(!currentWebView.getSettings().getSaveFormData());
1549 // Update the menu checkbox.
1550 menuItem.setChecked(currentWebView.getSettings().getSaveFormData());
1552 // Display a snackbar.
1553 if (currentWebView.getSettings().getSaveFormData()) {
1554 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1556 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1559 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1560 updatePrivacyIcons(true);
1562 // Reload the current WebView.
1563 currentWebView.reload();
1566 case R.id.clear_cookies:
1567 Snackbar.make(findViewById(R.id.webviewpager), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1568 .setAction(R.string.undo, v -> {
1569 // Do nothing because everything will be handled by `onDismissed()` below.
1571 .addCallback(new Snackbar.Callback() {
1572 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1574 public void onDismissed(Snackbar snackbar, int event) {
1575 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1576 // Delete the cookies, which command varies by SDK.
1577 if (Build.VERSION.SDK_INT < 21) {
1578 cookieManager.removeAllCookie();
1580 cookieManager.removeAllCookies(null);
1588 case R.id.clear_dom_storage:
1589 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1590 .setAction(R.string.undo, v -> {
1591 // Do nothing because everything will be handled by `onDismissed()` below.
1593 .addCallback(new Snackbar.Callback() {
1594 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1596 public void onDismissed(Snackbar snackbar, int event) {
1597 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1598 // Delete the DOM Storage.
1599 WebStorage webStorage = WebStorage.getInstance();
1600 webStorage.deleteAllData();
1602 // Initialize a handler to manually delete the DOM storage files and directories.
1603 Handler deleteDomStorageHandler = new Handler();
1605 // Setup a runnable to manually delete the DOM storage files and directories.
1606 Runnable deleteDomStorageRunnable = () -> {
1608 // Get a handle for the runtime.
1609 Runtime runtime = Runtime.getRuntime();
1611 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
1612 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
1613 String privateDataDirectoryString = getApplicationInfo().dataDir;
1615 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1616 Process deleteLocalStorageProcess = runtime.exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1618 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1619 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1620 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1621 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1622 Process deleteDatabasesProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1624 // Wait for the processes to finish.
1625 deleteLocalStorageProcess.waitFor();
1626 deleteIndexProcess.waitFor();
1627 deleteQuotaManagerProcess.waitFor();
1628 deleteQuotaManagerJournalProcess.waitFor();
1629 deleteDatabasesProcess.waitFor();
1630 } catch (Exception exception) {
1631 // Do nothing if an error is thrown.
1635 // Manually delete the DOM storage files after 200 milliseconds.
1636 deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200);
1643 // Form data can be remove once the minimum API >= 26.
1644 case R.id.clear_form_data:
1645 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1646 .setAction(R.string.undo, v -> {
1647 // Do nothing because everything will be handled by `onDismissed()` below.
1649 .addCallback(new Snackbar.Callback() {
1650 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1652 public void onDismissed(Snackbar snackbar, int event) {
1653 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1654 // Delete the form data.
1655 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1656 mainWebViewDatabase.clearFormData();
1664 // Toggle the EasyList status.
1665 currentWebView.enableBlocklist(NestedScrollWebView.EASY_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST));
1667 // Update the menu checkbox.
1668 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST));
1670 // Reload the current WebView.
1671 currentWebView.reload();
1674 case R.id.easyprivacy:
1675 // Toggle the EasyPrivacy status.
1676 currentWebView.enableBlocklist(NestedScrollWebView.EASY_PRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY));
1678 // Update the menu checkbox.
1679 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY));
1681 // Reload the current WebView.
1682 currentWebView.reload();
1685 case R.id.fanboys_annoyance_list:
1686 // Toggle Fanboy's Annoyance List status.
1687 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1689 // Update the menu checkbox.
1690 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1692 // Update the staus of Fanboy's Social Blocking List.
1693 MenuItem fanboysSocialBlockingListMenuItem = optionsMenu.findItem(R.id.fanboys_social_blocking_list);
1694 fanboysSocialBlockingListMenuItem.setEnabled(!currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1696 // Reload the current WebView.
1697 currentWebView.reload();
1700 case R.id.fanboys_social_blocking_list:
1701 // Toggle Fanboy's Social Blocking List status.
1702 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1704 // Update the menu checkbox.
1705 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1707 // Reload the current WebView.
1708 currentWebView.reload();
1711 case R.id.ultraprivacy:
1712 // Toggle the UltraPrivacy status.
1713 currentWebView.enableBlocklist(NestedScrollWebView.ULTRA_PRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY));
1715 // Update the menu checkbox.
1716 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY));
1718 // Reload the current WebView.
1719 currentWebView.reload();
1722 case R.id.block_all_third_party_requests:
1723 //Toggle the third-party requests blocker status.
1724 currentWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, !currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1726 // Update the menu checkbox.
1727 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1729 // Reload the current WebView.
1730 currentWebView.reload();
1733 case R.id.user_agent_privacy_browser:
1734 // Update the user agent.
1735 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
1737 // Reload the current WebView.
1738 currentWebView.reload();
1741 case R.id.user_agent_webview_default:
1742 // Update the user agent.
1743 currentWebView.getSettings().setUserAgentString("");
1745 // Reload the current WebView.
1746 currentWebView.reload();
1749 case R.id.user_agent_firefox_on_android:
1750 // Update the user agent.
1751 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
1753 // Reload the current WebView.
1754 currentWebView.reload();
1757 case R.id.user_agent_chrome_on_android:
1758 // Update the user agent.
1759 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
1761 // Reload the current WebView.
1762 currentWebView.reload();
1765 case R.id.user_agent_safari_on_ios:
1766 // Update the user agent.
1767 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
1769 // Reload the current WebView.
1770 currentWebView.reload();
1773 case R.id.user_agent_firefox_on_linux:
1774 // Update the user agent.
1775 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
1777 // Reload the current WebView.
1778 currentWebView.reload();
1781 case R.id.user_agent_chromium_on_linux:
1782 // Update the user agent.
1783 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
1785 // Reload the current WebView.
1786 currentWebView.reload();
1789 case R.id.user_agent_firefox_on_windows:
1790 // Update the user agent.
1791 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
1793 // Reload the current WebView.
1794 currentWebView.reload();
1797 case R.id.user_agent_chrome_on_windows:
1798 // Update the user agent.
1799 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
1801 // Reload the current WebView.
1802 currentWebView.reload();
1805 case R.id.user_agent_edge_on_windows:
1806 // Update the user agent.
1807 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
1809 // Reload the current WebView.
1810 currentWebView.reload();
1813 case R.id.user_agent_internet_explorer_on_windows:
1814 // Update the user agent.
1815 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
1817 // Reload the current WebView.
1818 currentWebView.reload();
1821 case R.id.user_agent_safari_on_macos:
1822 // Update the user agent.
1823 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
1825 // Reload the current WebView.
1826 currentWebView.reload();
1829 case R.id.user_agent_custom:
1830 // Update the user agent.
1831 currentWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
1833 // Reload the current WebView.
1834 currentWebView.reload();
1837 case R.id.font_size_twenty_five_percent:
1838 currentWebView.getSettings().setTextZoom(25);
1841 case R.id.font_size_fifty_percent:
1842 currentWebView.getSettings().setTextZoom(50);
1845 case R.id.font_size_seventy_five_percent:
1846 currentWebView.getSettings().setTextZoom(75);
1849 case R.id.font_size_one_hundred_percent:
1850 currentWebView.getSettings().setTextZoom(100);
1853 case R.id.font_size_one_hundred_twenty_five_percent:
1854 currentWebView.getSettings().setTextZoom(125);
1857 case R.id.font_size_one_hundred_fifty_percent:
1858 currentWebView.getSettings().setTextZoom(150);
1861 case R.id.font_size_one_hundred_seventy_five_percent:
1862 currentWebView.getSettings().setTextZoom(175);
1865 case R.id.font_size_two_hundred_percent:
1866 currentWebView.getSettings().setTextZoom(200);
1869 case R.id.swipe_to_refresh:
1870 // Toggle the stored status of swipe to refresh.
1871 currentWebView.setSwipeToRefresh(!currentWebView.getSwipeToRefresh());
1873 // Get a handle for the swipe refresh layout.
1874 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
1876 // Update the swipe refresh layout.
1877 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
1878 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.
1879 // Only enable the swipe refresh layout if the WebView is scrolled to the top.
1880 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
1881 } else { // For API < 23, the swipe refresh layout is always enabled.
1882 // Enable the swipe refresh layout.
1883 swipeRefreshLayout.setEnabled(true);
1885 } else { // Swipe to refresh is disabled.
1886 // Disable the swipe refresh layout.
1887 swipeRefreshLayout.setEnabled(false);
1891 case R.id.display_images:
1892 if (currentWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1893 // Disable loading of images.
1894 currentWebView.getSettings().setLoadsImagesAutomatically(false);
1896 // Reload the website to remove existing images.
1897 currentWebView.reload();
1898 } else { // Images are not currently loaded automatically.
1899 // Enable loading of images. Missing images will be loaded without the need for a reload.
1900 currentWebView.getSettings().setLoadsImagesAutomatically(true);
1904 case R.id.night_mode:
1905 // Toggle night mode.
1906 currentWebView.setNightMode(!currentWebView.getNightMode());
1908 // Enable or disable JavaScript according to night mode, the global preference, and any domain settings.
1909 if (currentWebView.getNightMode()) { // Night mode is enabled, which requires JavaScript.
1910 // Enable JavaScript.
1911 currentWebView.getSettings().setJavaScriptEnabled(true);
1912 } else if (currentWebView.getDomainSettingsApplied()) { // Night mode is disabled and domain settings are applied. Set JavaScript according to the domain settings.
1913 // Apply the JavaScript preference that was stored the last time domain settings were loaded.
1914 currentWebView.getSettings().setJavaScriptEnabled(currentWebView.getDomainSettingsJavaScriptEnabled());
1915 } else { // Night mode is disabled and domain settings are not applied. Set JavaScript according to the global preference.
1916 // Apply the JavaScript preference.
1917 currentWebView.getSettings().setJavaScriptEnabled(sharedPreferences.getBoolean("javascript", false));
1920 // Update the privacy icons.
1921 updatePrivacyIcons(false);
1923 // Reload the website.
1924 currentWebView.reload();
1927 case R.id.find_on_page:
1928 // Get a handle for the views.
1929 Toolbar toolbar = findViewById(R.id.toolbar);
1930 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
1931 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
1933 // Set the minimum height of the find on page linear layout to match the toolbar.
1934 findOnPageLinearLayout.setMinimumHeight(toolbar.getHeight());
1936 // Hide the toolbar.
1937 toolbar.setVisibility(View.GONE);
1939 // Show the find on page linear layout.
1940 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1942 // Display the keyboard. The app must wait 200 ms before running the command to work around a bug in Android.
1943 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1944 findOnPageEditText.postDelayed(() -> {
1945 // Set the focus on `findOnPageEditText`.
1946 findOnPageEditText.requestFocus();
1948 // Get a handle for the input method manager.
1949 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1951 // Remove the lint warning below that the input method manager might be null.
1952 assert inputMethodManager != null;
1954 // Display the keyboard. `0` sets no input flags.
1955 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1959 case R.id.view_source:
1960 // Create an intent to launch the view source activity.
1961 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
1963 // Add the variables to the intent.
1964 viewSourceIntent.putExtra("user_agent", currentWebView.getSettings().getUserAgentString());
1965 viewSourceIntent.putExtra("current_url", currentWebView.getUrl());
1968 startActivity(viewSourceIntent);
1971 case R.id.share_url:
1972 // Setup the share string.
1973 String shareString = currentWebView.getTitle() + " – " + currentWebView.getUrl();
1975 // Create the share intent.
1976 Intent shareIntent = new Intent(Intent.ACTION_SEND);
1977 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1978 shareIntent.setType("text/plain");
1981 startActivity(Intent.createChooser(shareIntent, getString(R.string.share_url)));
1985 // Get a print manager instance.
1986 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1988 // Remove the lint error below that print manager might be null.
1989 assert printManager != null;
1991 // Create a print document adapter from the current WebView.
1992 PrintDocumentAdapter printDocumentAdapter = currentWebView.createPrintDocumentAdapter();
1994 // Print the document.
1995 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1998 case R.id.open_with_app:
1999 openWithApp(currentWebView.getUrl());
2002 case R.id.open_with_browser:
2003 openWithBrowser(currentWebView.getUrl());
2006 case R.id.add_to_homescreen:
2007 // Instantiate the create home screen shortcut dialog.
2008 DialogFragment createHomeScreenShortcutDialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView.getTitle(), currentWebView.getUrl(),
2009 currentWebView.getFavoriteOrDefaultIcon());
2011 // Show the create home screen shortcut dialog.
2012 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2015 case R.id.proxy_through_orbot:
2016 // Toggle the proxy through Orbot variable.
2017 proxyThroughOrbot = !proxyThroughOrbot;
2019 // Apply the proxy through Orbot settings.
2020 applyProxyThroughOrbot(true);
2024 if (menuItem.getTitle().equals(getString(R.string.refresh))) { // The refresh button was pushed.
2025 // Reload the current WebView.
2026 currentWebView.reload();
2027 } else { // The stop button was pushed.
2028 // Stop the loading of the WebView.
2029 currentWebView.stopLoading();
2033 case R.id.ad_consent:
2034 // Display the ad consent dialog.
2035 DialogFragment adConsentDialogFragment = new AdConsentDialog();
2036 adConsentDialogFragment.show(getSupportFragmentManager(), getString(R.string.ad_consent));
2040 // Don't consume the event.
2041 return super.onOptionsItemSelected(menuItem);
2045 // removeAllCookies is deprecated, but it is required for API < 21.
2047 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2048 // Get the menu item ID.
2049 int menuItemId = menuItem.getItemId();
2051 // Get a handle for the shared preferences.
2052 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2054 // Run the commands that correspond to the selected menu item.
2055 switch (menuItemId) {
2056 case R.id.close_tab:
2057 // Get a handle for the tab layout and the view pager.
2058 TabLayout tabLayout = findViewById(R.id.tablayout);
2059 ViewPager webViewPager = findViewById(R.id.webviewpager);
2061 // Get the current tab number.
2062 int currentTabNumber = tabLayout.getSelectedTabPosition();
2064 // Delete the current tab.
2065 tabLayout.removeTabAt(currentTabNumber);
2067 // 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.
2068 if (webViewPagerAdapter.deletePage(currentTabNumber, webViewPager)) {
2069 setCurrentWebView(currentTabNumber);
2073 case R.id.clear_and_exit:
2074 // Close the bookmarks cursor and database.
2075 bookmarksCursor.close();
2076 bookmarksDatabaseHelper.close();
2078 // Get the status of the clear everything preference.
2079 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2081 // Get a handle for the runtime.
2082 Runtime runtime = Runtime.getRuntime();
2084 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
2085 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
2086 String privateDataDirectoryString = getApplicationInfo().dataDir;
2089 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2090 // The command to remove cookies changed slightly in API 21.
2091 if (Build.VERSION.SDK_INT >= 21) {
2092 CookieManager.getInstance().removeAllCookies(null);
2094 CookieManager.getInstance().removeAllCookie();
2097 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2099 // Two commands must be used because `Runtime.exec()` does not like `*`.
2100 Process deleteCookiesProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2101 Process deleteCookiesJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2103 // Wait until the processes have finished.
2104 deleteCookiesProcess.waitFor();
2105 deleteCookiesJournalProcess.waitFor();
2106 } catch (Exception exception) {
2107 // Do nothing if an error is thrown.
2111 // Clear DOM storage.
2112 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2113 // Ask `WebStorage` to clear the DOM storage.
2114 WebStorage webStorage = WebStorage.getInstance();
2115 webStorage.deleteAllData();
2117 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2119 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2120 Process deleteLocalStorageProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2122 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2123 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2124 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2125 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2126 Process deleteDatabaseProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2128 // Wait until the processes have finished.
2129 deleteLocalStorageProcess.waitFor();
2130 deleteIndexProcess.waitFor();
2131 deleteQuotaManagerProcess.waitFor();
2132 deleteQuotaManagerJournalProcess.waitFor();
2133 deleteDatabaseProcess.waitFor();
2134 } catch (Exception exception) {
2135 // Do nothing if an error is thrown.
2139 // Clear form data if the API < 26.
2140 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
2141 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
2142 webViewDatabase.clearFormData();
2144 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2146 // A string array must be used because the database contains a space and `Runtime.exec` will not otherwise escape the string correctly.
2147 Process deleteWebDataProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
2148 Process deleteWebDataJournalProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
2150 // Wait until the processes have finished.
2151 deleteWebDataProcess.waitFor();
2152 deleteWebDataJournalProcess.waitFor();
2153 } catch (Exception exception) {
2154 // Do nothing if an error is thrown.
2159 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2160 // Clear the cache from each WebView.
2161 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
2162 // Get the WebView tab fragment.
2163 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
2165 // Get the fragment view.
2166 View fragmentView = webViewTabFragment.getView();
2168 // Only clear the cache if the WebView exists.
2169 if (fragmentView != null) {
2170 // Get the nested scroll WebView from the tab fragment.
2171 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
2173 // Clear the cache for this WebView.
2174 nestedScrollWebView.clearCache(true);
2178 // Manually delete the cache directories.
2180 // Delete the main cache directory.
2181 Process deleteCacheProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2183 // Delete the secondary `Service Worker` cache directory.
2184 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2185 Process deleteServiceWorkerProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2187 // Wait until the processes have finished.
2188 deleteCacheProcess.waitFor();
2189 deleteServiceWorkerProcess.waitFor();
2190 } catch (Exception exception) {
2191 // Do nothing if an error is thrown.
2195 // Wipe out each WebView.
2196 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
2197 // Get the WebView tab fragment.
2198 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
2200 // Get the fragment view.
2201 View fragmentView = webViewTabFragment.getView();
2203 // Only wipe out the WebView if it exists.
2204 if (fragmentView != null) {
2205 // Get the nested scroll WebView from the tab fragment.
2206 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
2208 // Clear SSL certificate preferences for this WebView.
2209 nestedScrollWebView.clearSslPreferences();
2211 // Clear the back/forward history for this WebView.
2212 nestedScrollWebView.clearHistory();
2214 // Destroy the internal state of `mainWebView`.
2215 nestedScrollWebView.destroy();
2219 // Clear the custom headers.
2220 customHeaders.clear();
2222 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
2223 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
2224 if (clearEverything) {
2226 // Delete the folder.
2227 Process deleteAppWebviewProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
2229 // Wait until the process has finished.
2230 deleteAppWebviewProcess.waitFor();
2231 } catch (Exception exception) {
2232 // Do nothing if an error is thrown.
2236 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
2237 if (Build.VERSION.SDK_INT >= 21) {
2238 finishAndRemoveTask();
2243 // Remove the terminated program from RAM. The status code is `0`.
2248 // Select the homepage based on the proxy through Orbot status.
2249 if (proxyThroughOrbot) {
2250 // Load the Tor homepage.
2251 loadUrl(sharedPreferences.getString("tor_homepage", getString(R.string.tor_homepage_default_value)));
2253 // Load the normal homepage.
2254 loadUrl(sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
2259 if (currentWebView.canGoBack()) {
2260 // Reset the current domain name so that navigation works if third-party requests are blocked.
2261 currentWebView.resetCurrentDomainName();
2263 // Set navigating history so that the domain settings are applied when the new URL is loaded.
2264 currentWebView.setNavigatingHistory(true);
2266 // Load the previous website in the history.
2267 currentWebView.goBack();
2272 if (currentWebView.canGoForward()) {
2273 // Reset the current domain name so that navigation works if third-party requests are blocked.
2274 currentWebView.resetCurrentDomainName();
2276 // Set navigating history so that the domain settings are applied when the new URL is loaded.
2277 currentWebView.setNavigatingHistory(true);
2279 // Load the next website in the history.
2280 currentWebView.goForward();
2285 // Instantiate the URL history dialog.
2286 DialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(currentWebView.getWebViewFragmentId());
2288 // Show the URL history dialog.
2289 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2293 // Populate the resource requests.
2294 RequestsActivity.resourceRequests = currentWebView.getResourceRequests();
2296 // Create an intent to launch the Requests activity.
2297 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2299 // Add the block third-party requests status to the intent.
2300 requestsIntent.putExtra("block_all_third_party_requests", currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
2303 startActivity(requestsIntent);
2306 case R.id.downloads:
2307 // Launch the system Download Manager.
2308 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2310 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2311 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2313 startActivity(downloadManagerIntent);
2317 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2318 reapplyDomainSettingsOnRestart = true;
2320 // Launch the domains activity.
2321 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2323 // Add the extra information to the intent.
2324 domainsIntent.putExtra("current_url", currentWebView.getUrl());
2326 // Get the current certificate.
2327 SslCertificate sslCertificate = currentWebView.getCertificate();
2329 // Check to see if the SSL certificate is populated.
2330 if (sslCertificate != null) {
2331 // Extract the certificate to strings.
2332 String issuedToCName = sslCertificate.getIssuedTo().getCName();
2333 String issuedToOName = sslCertificate.getIssuedTo().getOName();
2334 String issuedToUName = sslCertificate.getIssuedTo().getUName();
2335 String issuedByCName = sslCertificate.getIssuedBy().getCName();
2336 String issuedByOName = sslCertificate.getIssuedBy().getOName();
2337 String issuedByUName = sslCertificate.getIssuedBy().getUName();
2338 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
2339 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
2341 // Add the certificate to the intent.
2342 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
2343 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
2344 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
2345 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
2346 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
2347 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
2348 domainsIntent.putExtra("ssl_start_date", startDateLong);
2349 domainsIntent.putExtra("ssl_end_date", endDateLong);
2352 // Check to see if the current IP addresses have been received.
2353 if (currentWebView.hasCurrentIpAddresses()) {
2354 // Add the current IP addresses to the intent.
2355 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
2359 startActivity(domainsIntent);
2363 // Set the flag to reapply app settings on restart when returning from Settings.
2364 reapplyAppSettingsOnRestart = true;
2366 // Set the flag to reapply the domain settings on restart when returning from Settings.
2367 reapplyDomainSettingsOnRestart = true;
2369 // Launch the settings activity.
2370 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2371 startActivity(settingsIntent);
2374 case R.id.import_export:
2375 // Launch the import/export activity.
2376 Intent importExportIntent = new Intent (this, ImportExportActivity.class);
2377 startActivity(importExportIntent);
2381 // Launch the logcat activity.
2382 Intent logcatIntent = new Intent(this, LogcatActivity.class);
2383 startActivity(logcatIntent);
2387 // Launch `GuideActivity`.
2388 Intent guideIntent = new Intent(this, GuideActivity.class);
2389 startActivity(guideIntent);
2393 // Create an intent to launch the about activity.
2394 Intent aboutIntent = new Intent(this, AboutActivity.class);
2396 // Create a string array for the blocklist versions.
2397 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],
2398 ultraPrivacy.get(0).get(0)[0]};
2400 // Add the blocklist versions to the intent.
2401 aboutIntent.putExtra("blocklist_versions", blocklistVersions);
2404 startActivity(aboutIntent);
2408 // Get a handle for the drawer layout.
2409 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
2411 // Close the navigation drawer.
2412 drawerLayout.closeDrawer(GravityCompat.START);
2417 public void onPostCreate(Bundle savedInstanceState) {
2418 // Run the default commands.
2419 super.onPostCreate(savedInstanceState);
2421 // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished. This creates the navigation drawer icon.
2422 actionBarDrawerToggle.syncState();
2426 public void onConfigurationChanged(Configuration newConfig) {
2427 // Run the default commands.
2428 super.onConfigurationChanged(newConfig);
2430 // Get the status bar pixel size.
2431 int statusBarResourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
2432 int statusBarPixelSize = getResources().getDimensionPixelSize(statusBarResourceId);
2434 // Get the resource density.
2435 float screenDensity = getResources().getDisplayMetrics().density;
2437 // Recalculate the drawer header padding.
2438 drawerHeaderPaddingLeftAndRight = (int) (15 * screenDensity);
2439 drawerHeaderPaddingTop = statusBarPixelSize + (int) (4 * screenDensity);
2440 drawerHeaderPaddingBottom = (int) (8 * screenDensity);
2442 // Reload the ad for the free flavor if not in full screen mode.
2443 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2444 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2445 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
2448 // `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:
2449 // https://code.google.com/p/android/issues/detail?id=20493#c8
2450 // ActivityCompat.invalidateOptionsMenu(this);
2454 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2455 // Store the hit test result.
2456 final WebView.HitTestResult hitTestResult = currentWebView.getHitTestResult();
2458 // Create the URL strings.
2459 final String imageUrl;
2460 final String linkUrl;
2462 // Get handles for the system managers.
2463 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2464 FragmentManager fragmentManager = getSupportFragmentManager();
2465 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2467 // Remove the lint errors below that the clipboard manager might be null.
2468 assert clipboardManager != null;
2470 // Process the link according to the type.
2471 switch (hitTestResult.getType()) {
2472 // `SRC_ANCHOR_TYPE` is a link.
2473 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2474 // Get the target URL.
2475 linkUrl = hitTestResult.getExtra();
2477 // Set the target URL as the title of the `ContextMenu`.
2478 menu.setHeaderTitle(linkUrl);
2480 // Add a Load URL entry.
2481 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2490 // Add an Open with App entry.
2491 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2492 openWithApp(linkUrl);
2496 // Add an Open with Browser entry.
2497 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2498 openWithBrowser(linkUrl);
2502 // Add a Copy URL entry.
2503 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2504 // Save the link URL in a `ClipData`.
2505 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2507 // Set the `ClipData` as the clipboard's primary clip.
2508 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2512 // Add a Download URL entry.
2513 menu.add(R.string.download_url).setOnMenuItemClickListener((MenuItem item) -> {
2514 // Check if the download should be processed by an external app.
2515 if (sharedPreferences.getBoolean("download_with_external_app", false)) { // Download with an external app.
2516 openUrlWithExternalApp(linkUrl);
2517 } else { // Download with Android's download manager.
2518 // Check to see if the storage permission has already been granted.
2519 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission needs to be requested.
2520 // Store the variables for future use by `onRequestPermissionsResult()`.
2521 downloadUrl = linkUrl;
2522 downloadContentDisposition = "none";
2523 downloadContentLength = -1;
2525 // Show a dialog if the user has previously denied the permission.
2526 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2527 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
2528 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
2530 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
2531 downloadLocationPermissionDialogFragment.show(fragmentManager, getString(R.string.download_location));
2532 } else { // Show the permission request directly.
2533 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
2534 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2536 } else { // The storage permission has already been granted.
2537 // Get a handle for the download file alert dialog.
2538 DialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(linkUrl, "none", -1);
2540 // Show the download file alert dialog.
2541 downloadFileDialogFragment.show(fragmentManager, getString(R.string.download));
2547 // Add a Cancel entry, which by default closes the context menu.
2548 menu.add(R.string.cancel);
2551 case WebView.HitTestResult.EMAIL_TYPE:
2552 // Get the target URL.
2553 linkUrl = hitTestResult.getExtra();
2555 // Set the target URL as the title of the `ContextMenu`.
2556 menu.setHeaderTitle(linkUrl);
2558 // Add a Write Email entry.
2559 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2560 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2561 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2563 // Parse the url and set it as the data for the `Intent`.
2564 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2566 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2567 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2570 startActivity(emailIntent);
2574 // Add a Copy Email Address entry.
2575 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2576 // Save the email address in a `ClipData`.
2577 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2579 // Set the `ClipData` as the clipboard's primary clip.
2580 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2584 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2585 menu.add(R.string.cancel);
2588 // `IMAGE_TYPE` is an image.
2589 case WebView.HitTestResult.IMAGE_TYPE:
2590 // Get the image URL.
2591 imageUrl = hitTestResult.getExtra();
2593 // Set the image URL as the title of the `ContextMenu`.
2594 menu.setHeaderTitle(imageUrl);
2596 // Add a View Image entry.
2597 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2602 // Add a Download Image entry.
2603 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2604 // Check if the download should be processed by an external app.
2605 if (sharedPreferences.getBoolean("download_with_external_app", false)) { // Download with an external app.
2606 openUrlWithExternalApp(imageUrl);
2607 } else { // Download with Android's download manager.
2608 // Check to see if the storage permission has already been granted.
2609 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission needs to be requested.
2610 // Store the image URL for use by `onRequestPermissionResult()`.
2611 downloadImageUrl = imageUrl;
2613 // Show a dialog if the user has previously denied the permission.
2614 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2615 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2616 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2618 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
2619 downloadLocationPermissionDialogFragment.show(fragmentManager, getString(R.string.download_location));
2620 } else { // Show the permission request directly.
2621 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
2622 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2624 } else { // The storage permission has already been granted.
2625 // Get a handle for the download image alert dialog.
2626 DialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2628 // Show the download image alert dialog.
2629 downloadImageDialogFragment.show(fragmentManager, getString(R.string.download));
2635 // Add a Copy URL entry.
2636 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2637 // Save the image URL in a `ClipData`.
2638 ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2640 // Set the `ClipData` as the clipboard's primary clip.
2641 clipboardManager.setPrimaryClip(srcImageTypeClipData);
2645 // Add an Open with App entry.
2646 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2647 openWithApp(imageUrl);
2651 // Add an Open with Browser entry.
2652 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2653 openWithBrowser(imageUrl);
2657 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2658 menu.add(R.string.cancel);
2662 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2663 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2664 // Get the image URL.
2665 imageUrl = hitTestResult.getExtra();
2667 // Set the image URL as the title of the `ContextMenu`.
2668 menu.setHeaderTitle(imageUrl);
2670 // Add a `View Image` entry.
2671 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2676 // Add a `Download Image` entry.
2677 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2678 // Check if the download should be processed by an external app.
2679 if (sharedPreferences.getBoolean("download_with_external_app", false)) { // Download with an external app.
2680 openUrlWithExternalApp(imageUrl);
2681 } else { // Download with Android's download manager.
2682 // Check to see if the storage permission has already been granted.
2683 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission needs to be requested.
2684 // Store the image URL for use by `onRequestPermissionResult()`.
2685 downloadImageUrl = imageUrl;
2687 // Show a dialog if the user has previously denied the permission.
2688 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2689 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2690 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2692 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
2693 downloadLocationPermissionDialogFragment.show(fragmentManager, getString(R.string.download_location));
2694 } else { // Show the permission request directly.
2695 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
2696 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2698 } else { // The storage permission has already been granted.
2699 // Get a handle for the download image alert dialog.
2700 DialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2702 // Show the download image alert dialog.
2703 downloadImageDialogFragment.show(fragmentManager, getString(R.string.download));
2709 // Add a `Copy URL` entry.
2710 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2711 // Save the image URL in a `ClipData`.
2712 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2714 // Set the `ClipData` as the clipboard's primary clip.
2715 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2719 // Add an Open with App entry.
2720 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2721 openWithApp(imageUrl);
2725 // Add an Open with Browser entry.
2726 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2727 openWithBrowser(imageUrl);
2731 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2732 menu.add(R.string.cancel);
2738 public void onCreateBookmark(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2739 // Get a handle for the bookmarks list view.
2740 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2742 // Get the views from the dialog fragment.
2743 EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
2744 EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
2746 // Extract the strings from the edit texts.
2747 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2748 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2750 // Create a favorite icon byte array output stream.
2751 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2753 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2754 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2756 // Convert the favorite icon byte array stream to a byte array.
2757 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2759 // Display the new bookmark below the current items in the (0 indexed) list.
2760 int newBookmarkDisplayOrder = bookmarksListView.getCount();
2762 // Create the bookmark.
2763 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2765 // Update the bookmarks cursor with the current contents of this folder.
2766 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2768 // Update the list view.
2769 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2771 // Scroll to the new bookmark.
2772 bookmarksListView.setSelection(newBookmarkDisplayOrder);
2776 public void onCreateBookmarkFolder(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2777 // Get a handle for the bookmarks list view.
2778 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2780 // Get handles for the views in the dialog fragment.
2781 EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
2782 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
2783 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
2785 // Get new folder name string.
2786 String folderNameString = createFolderNameEditText.getText().toString();
2788 // Create a folder icon bitmap.
2789 Bitmap folderIconBitmap;
2791 // Set the folder icon bitmap according to the dialog.
2792 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
2793 // Get the default folder icon drawable.
2794 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2796 // Convert the folder icon drawable to a bitmap drawable.
2797 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2799 // Convert the folder icon bitmap drawable to a bitmap.
2800 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2801 } else { // Use the WebView favorite icon.
2802 // Copy the favorite icon bitmap to the folder icon bitmap.
2803 folderIconBitmap = favoriteIconBitmap;
2806 // Create a folder icon byte array output stream.
2807 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2809 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2810 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2812 // Convert the folder icon byte array stream to a byte array.
2813 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2815 // Move all the bookmarks down one in the display order.
2816 for (int i = 0; i < bookmarksListView.getCount(); i++) {
2817 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2818 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2821 // Create the folder, which will be placed at the top of the `ListView`.
2822 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2824 // Update the bookmarks cursor with the current contents of this folder.
2825 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2827 // Update the `ListView`.
2828 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2830 // Scroll to the new folder.
2831 bookmarksListView.setSelection(0);
2835 public void onSaveBookmark(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, Bitmap favoriteIconBitmap) {
2836 // Get handles for the views from `dialogFragment`.
2837 EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
2838 EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
2839 RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
2841 // Store the bookmark strings.
2842 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
2843 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
2845 // Update the bookmark.
2846 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
2847 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
2848 } else { // Update the bookmark using the `WebView` favorite icon.
2849 // Create a favorite icon byte array output stream.
2850 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2852 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2853 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
2855 // Convert the favorite icon byte array stream to a byte array.
2856 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
2858 // Update the bookmark and the favorite icon.
2859 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
2862 // Update the bookmarks cursor with the current contents of this folder.
2863 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2865 // Update the list view.
2866 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2870 public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId, Bitmap favoriteIconBitmap) {
2871 // Get handles for the views from `dialogFragment`.
2872 EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
2873 RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
2874 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
2875 ImageView defaultFolderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
2877 // Get the new folder name.
2878 String newFolderNameString = editFolderNameEditText.getText().toString();
2880 // Check if the favorite icon has changed.
2881 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
2882 // Update the name in the database.
2883 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2884 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
2885 // Create the new folder icon Bitmap.
2886 Bitmap folderIconBitmap;
2888 // Populate the new folder icon bitmap.
2889 if (defaultFolderIconRadioButton.isChecked()) {
2890 // Get the default folder icon drawable.
2891 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2893 // Convert the folder icon drawable to a bitmap drawable.
2894 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2896 // Convert the folder icon bitmap drawable to a bitmap.
2897 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2898 } else { // Use the `WebView` favorite icon.
2899 // Copy the favorite icon bitmap to the folder icon bitmap.
2900 folderIconBitmap = favoriteIconBitmap;
2903 // Create a folder icon byte array output stream.
2904 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2906 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2907 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2909 // Convert the folder icon byte array stream to a byte array.
2910 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2912 // Update the folder icon in the database.
2913 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, newFolderIconByteArray);
2914 } else { // The folder icon and the name have changed.
2915 // Get the new folder icon `Bitmap`.
2916 Bitmap folderIconBitmap;
2917 if (defaultFolderIconRadioButton.isChecked()) {
2918 // Get the default folder icon drawable.
2919 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2921 // Convert the folder icon drawable to a bitmap drawable.
2922 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2924 // Convert the folder icon bitmap drawable to a bitmap.
2925 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2926 } else { // Use the `WebView` favorite icon.
2927 // Copy the favorite icon bitmap to the folder icon bitmap.
2928 folderIconBitmap = favoriteIconBitmap;
2931 // Create a folder icon byte array output stream.
2932 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2934 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2935 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2937 // Convert the folder icon byte array stream to a byte array.
2938 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2940 // Update the folder name and icon in the database.
2941 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, newFolderIconByteArray);
2944 // Update the bookmarks cursor with the current contents of this folder.
2945 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2947 // Update the `ListView`.
2948 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2952 public void onCloseDownloadLocationPermissionDialog(int downloadType) {
2953 switch (downloadType) {
2954 case DownloadLocationPermissionDialog.DOWNLOAD_FILE:
2955 // Request the WRITE_EXTERNAL_STORAGE permission with a file request code.
2956 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2959 case DownloadLocationPermissionDialog.DOWNLOAD_IMAGE:
2960 // Request the WRITE_EXTERNAL_STORAGE permission with an image request code.
2961 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2967 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
2968 // Get a handle for the fragment manager.
2969 FragmentManager fragmentManager = getSupportFragmentManager();
2971 switch (requestCode) {
2972 case DOWNLOAD_FILE_REQUEST_CODE:
2973 // Show the download file alert dialog. When the dialog closes, the correct command will be used based on the permission status.
2974 DialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(downloadUrl, downloadContentDisposition, downloadContentLength);
2976 // On API 23, displaying the fragment must be delayed or the app will crash.
2977 if (Build.VERSION.SDK_INT == 23) {
2978 new Handler().postDelayed(() -> downloadFileDialogFragment.show(fragmentManager, getString(R.string.download)), 500);
2980 downloadFileDialogFragment.show(fragmentManager, getString(R.string.download));
2983 // Reset the download variables.
2985 downloadContentDisposition = "";
2986 downloadContentLength = 0;
2989 case DOWNLOAD_IMAGE_REQUEST_CODE:
2990 // Show the download image alert dialog. When the dialog closes, the correct command will be used based on the permission status.
2991 DialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(downloadImageUrl);
2993 // On API 23, displaying the fragment must be delayed or the app will crash.
2994 if (Build.VERSION.SDK_INT == 23) {
2995 new Handler().postDelayed(() -> downloadImageDialogFragment.show(fragmentManager, getString(R.string.download)), 500);
2997 downloadImageDialogFragment.show(fragmentManager, getString(R.string.download));
3000 // Reset the image URL variable.
3001 downloadImageUrl = "";
3007 public void onDownloadImage(DialogFragment dialogFragment, String imageUrl) {
3008 // Download the image if it has an HTTP or HTTPS URI.
3009 if (imageUrl.startsWith("http")) {
3010 // Get a handle for the system `DOWNLOAD_SERVICE`.
3011 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
3013 // Parse `imageUrl`.
3014 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
3016 // Get a handle for the cookie manager.
3017 CookieManager cookieManager = CookieManager.getInstance();
3019 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
3020 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
3021 if (cookieManager.acceptCookie()) {
3022 // Get the cookies for `imageUrl`.
3023 String cookies = cookieManager.getCookie(imageUrl);
3025 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
3026 downloadRequest.addRequestHeader("Cookie", cookies);
3029 // Get the file name from the dialog fragment.
3030 EditText downloadImageNameEditText = dialogFragment.getDialog().findViewById(R.id.download_image_name);
3031 String imageName = downloadImageNameEditText.getText().toString();
3033 // Specify the download location.
3034 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
3035 // Download to the public download directory.
3036 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, imageName);
3037 } else { // External write permission denied.
3038 // Download to the app's external download directory.
3039 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, imageName);
3042 // Allow `MediaScanner` to index the download if it is a media file.
3043 downloadRequest.allowScanningByMediaScanner();
3045 // Add the URL as the description for the download.
3046 downloadRequest.setDescription(imageUrl);
3048 // Show the download notification after the download is completed.
3049 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3051 // Remove the lint warning below that `downloadManager` might be `null`.
3052 assert downloadManager != null;
3054 // Initiate the download.
3055 downloadManager.enqueue(downloadRequest);
3056 } else { // The image is not an HTTP or HTTPS URI.
3057 Snackbar.make(currentWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
3062 public void onDownloadFile(DialogFragment dialogFragment, String downloadUrl) {
3063 // Download the file if it has an HTTP or HTTPS URI.
3064 if (downloadUrl.startsWith("http")) {
3065 // Get a handle for the system `DOWNLOAD_SERVICE`.
3066 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
3068 // Parse `downloadUrl`.
3069 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
3071 // Get a handle for the cookie manager.
3072 CookieManager cookieManager = CookieManager.getInstance();
3074 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
3075 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
3076 if (cookieManager.acceptCookie()) {
3077 // Get the cookies for `downloadUrl`.
3078 String cookies = cookieManager.getCookie(downloadUrl);
3080 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
3081 downloadRequest.addRequestHeader("Cookie", cookies);
3084 // Get the file name from the dialog fragment.
3085 EditText downloadFileNameEditText = dialogFragment.getDialog().findViewById(R.id.download_file_name);
3086 String fileName = downloadFileNameEditText.getText().toString();
3088 // Specify the download location.
3089 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
3090 // Download to the public download directory.
3091 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
3092 } else { // External write permission denied.
3093 // Download to the app's external download directory.
3094 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, fileName);
3097 // Allow `MediaScanner` to index the download if it is a media file.
3098 downloadRequest.allowScanningByMediaScanner();
3100 // Add the URL as the description for the download.
3101 downloadRequest.setDescription(downloadUrl);
3103 // Show the download notification after the download is completed.
3104 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3106 // Remove the lint warning below that `downloadManager` might be `null`.
3107 assert downloadManager != null;
3109 // Initiate the download.
3110 downloadManager.enqueue(downloadRequest);
3111 } else { // The download is not an HTTP or HTTPS URI.
3112 Snackbar.make(currentWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
3116 // Override `onBackPressed` to handle the navigation drawer and and the WebView.
3118 public void onBackPressed() {
3119 // Get a handle for the drawer layout.
3120 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
3122 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
3123 // Close the navigation drawer.
3124 drawerLayout.closeDrawer(GravityCompat.START);
3125 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
3126 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
3127 // close the bookmarks drawer.
3128 drawerLayout.closeDrawer(GravityCompat.END);
3129 } else { // A subfolder is displayed.
3130 // Place the former parent folder in `currentFolder`.
3131 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolderName(currentBookmarksFolder);
3133 // Load the new folder.
3134 loadBookmarksFolder();
3136 } else if (currentWebView.canGoBack()) { // There is at least one item in the current WebView history.
3137 // Reset the current domain name so that navigation works if third-party requests are blocked.
3138 currentWebView.resetCurrentDomainName();
3140 // Set navigating history so that the domain settings are applied when the new URL is loaded.
3141 currentWebView.setNavigatingHistory(true);
3144 currentWebView.goBack();
3145 } else { // There is nothing else to do.
3146 // Load a blank website.
3151 // 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.
3153 public void onActivityResult(int requestCode, int resultCode, Intent data) {
3154 // File uploads only work on API >= 21.
3155 if (Build.VERSION.SDK_INT >= 21) {
3156 // Pass the file to the WebView.
3157 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
3161 private void loadUrlFromTextBox() {
3162 // Get a handle for the URL edit text.
3163 EditText urlEditText = findViewById(R.id.url_edittext);
3165 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
3166 String unformattedUrlString = urlEditText.getText().toString().trim();
3168 // Initialize the formatted URL string.
3171 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
3172 if (unformattedUrlString.startsWith("content://")) { // This is a Content URL.
3173 // Load the entire content URL.
3174 url = unformattedUrlString;
3175 } else if (Patterns.WEB_URL.matcher(unformattedUrlString).matches() || unformattedUrlString.startsWith("http://") || unformattedUrlString.startsWith("https://") ||
3176 unformattedUrlString.startsWith("file://")) { // This is a standard URL.
3177 // Add `https://` at the beginning if there is no protocol. Otherwise the app will segfault.
3178 if (!unformattedUrlString.startsWith("http") && !unformattedUrlString.startsWith("file://") && !unformattedUrlString.startsWith("content://")) {
3179 unformattedUrlString = "https://" + unformattedUrlString;
3182 // Initialize `unformattedUrl`.
3183 URL unformattedUrl = null;
3185 // 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.
3187 unformattedUrl = new URL(unformattedUrlString);
3188 } catch (MalformedURLException e) {
3189 e.printStackTrace();
3192 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
3193 String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
3194 String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
3195 String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
3196 String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
3197 String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
3200 Uri.Builder uri = new Uri.Builder();
3201 uri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
3203 // Decode the URI as a UTF-8 string in.
3205 url = URLDecoder.decode(uri.build().toString(), "UTF-8");
3206 } catch (UnsupportedEncodingException exception) {
3207 // Do nothing. The formatted URL string will remain blank.
3209 } else if (!unformattedUrlString.isEmpty()){ // This is not a URL, but rather a search string.
3210 // Create an encoded URL String.
3211 String encodedUrlString;
3213 // Sanitize the search input.
3215 encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
3216 } catch (UnsupportedEncodingException exception) {
3217 encodedUrlString = "";
3220 // Add the base search URL.
3221 url = searchURL + encodedUrlString;
3224 // 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.
3225 urlEditText.clearFocus();
3231 private void loadUrl(String url) {
3232 // Apply the domain settings.
3233 applyDomainSettings(currentWebView, url, true, false);
3236 currentWebView.loadUrl(url, customHeaders);
3239 public void findPreviousOnPage(View view) {
3240 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
3241 currentWebView.findNext(false);
3244 public void findNextOnPage(View view) {
3245 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
3246 currentWebView.findNext(true);
3249 public void closeFindOnPage(View view) {
3250 // Get a handle for the views.
3251 Toolbar toolbar = findViewById(R.id.toolbar);
3252 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
3253 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
3255 // Delete the contents of `find_on_page_edittext`.
3256 findOnPageEditText.setText(null);
3258 // Clear the highlighted phrases.
3259 currentWebView.clearMatches();
3261 // Hide the find on page linear layout.
3262 findOnPageLinearLayout.setVisibility(View.GONE);
3264 // Show the toolbar.
3265 toolbar.setVisibility(View.VISIBLE);
3267 // Get a handle for the input method manager.
3268 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
3270 // Remove the lint warning below that the input method manager might be null.
3271 assert inputMethodManager != null;
3273 // Hide the keyboard.
3274 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
3277 private void applyAppSettings() {
3278 // Get a handle for the shared preferences.
3279 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3281 // Store the values from the shared preferences in variables.
3282 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3283 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
3284 proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
3285 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3286 hideAppBar = sharedPreferences.getBoolean("hide_app_bar", true);
3288 // Get handles for the views that need to be modified.
3289 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
3290 ActionBar actionBar = getSupportActionBar();
3291 LinearLayout tabsLinearLayout = findViewById(R.id.tabs_linearlayout);
3293 // Remove the incorrect lint warning below that the action bar might be null.
3294 assert actionBar != null;
3296 // Apply the proxy through Orbot settings.
3297 applyProxyThroughOrbot(false);
3299 // Set Do Not Track status.
3300 if (doNotTrackEnabled) {
3301 customHeaders.put("DNT", "1");
3303 customHeaders.remove("DNT");
3306 // Set the app bar scrolling for each WebView.
3307 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3308 // Get the WebView tab fragment.
3309 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3311 // Get the fragment view.
3312 View fragmentView = webViewTabFragment.getView();
3314 // Only modify the WebViews if they exist.
3315 if (fragmentView != null) {
3316 // Get the nested scroll WebView from the tab fragment.
3317 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3319 // Set the app bar scrolling.
3320 nestedScrollWebView.setNestedScrollingEnabled(sharedPreferences.getBoolean("scroll_app_bar", true));
3324 // Update the full screen browsing mode settings.
3325 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
3326 // Update the visibility of the app bar, which might have changed in the settings.
3328 // Hide the tab linear layout.
3329 tabsLinearLayout.setVisibility(View.GONE);
3331 // Hide the action bar.
3334 // Show the tab linear layout.
3335 tabsLinearLayout.setVisibility(View.VISIBLE);
3337 // Show the action bar.
3341 // Hide the banner ad in the free flavor.
3342 if (BuildConfig.FLAVOR.contentEquals("free")) {
3343 AdHelper.hideAd(findViewById(R.id.adview));
3346 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
3347 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3349 /* Hide the system bars.
3350 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3351 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
3352 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3353 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3355 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
3356 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3357 } else { // Privacy Browser is not in full screen browsing mode.
3358 // 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.
3359 inFullScreenBrowsingMode = false;
3361 // Show the tab linear layout.
3362 tabsLinearLayout.setVisibility(View.VISIBLE);
3364 // Show the action bar.
3367 // Show the banner ad in the free flavor.
3368 if (BuildConfig.FLAVOR.contentEquals("free")) {
3369 // Initialize the ads. If this isn't the first run, `loadAd()` will be automatically called instead.
3370 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getSupportFragmentManager(), getString(R.string.google_app_id), getString(R.string.ad_unit_id));
3373 // Remove the `SYSTEM_UI` flags from the root frame layout.
3374 rootFrameLayout.setSystemUiVisibility(0);
3376 // Add the translucent status flag.
3377 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3382 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
3383 @SuppressLint("SetJavaScriptEnabled")
3384 private boolean applyDomainSettings(NestedScrollWebView nestedScrollWebView, String url, boolean resetTab, boolean reloadWebsite) {
3385 // Store a copy of the current user agent to track changes for the return boolean.
3386 String initialUserAgent = nestedScrollWebView.getSettings().getUserAgentString();
3388 // Parse the URL into a URI.
3389 Uri uri = Uri.parse(url);
3391 // Extract the domain from `uri`.
3392 String newHostName = uri.getHost();
3394 // Strings don't like to be null.
3395 if (newHostName == null) {
3399 // 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.
3400 if (!nestedScrollWebView.getCurrentDomainName().equals(newHostName)) {
3401 // Set the new host name as the current domain name.
3402 nestedScrollWebView.setCurrentDomainName(newHostName);
3404 // Reset the ignoring of pinned domain information.
3405 nestedScrollWebView.setIgnorePinnedDomainInformation(false);
3407 // Clear any pinned SSL certificate or IP addresses.
3408 nestedScrollWebView.clearPinnedSslCertificate();
3409 nestedScrollWebView.clearPinnedIpAddresses();
3411 // Reset the favorite icon if specified.
3413 // Initialize the favorite icon.
3414 nestedScrollWebView.initializeFavoriteIcon();
3416 // Get the current page position.
3417 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
3419 // Get a handle for the tab layout.
3420 TabLayout tabLayout = findViewById(R.id.tablayout);
3422 // Get the corresponding tab.
3423 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
3425 // Remove the warning below that the tab might be null.
3428 // Get the tab custom view.
3429 View tabCustomView = tab.getCustomView();
3431 // Remove the warning below that the tab custom view might be null.
3432 assert tabCustomView != null;
3434 // Get the tab views.
3435 ImageView tabFavoriteIconImageView = tabCustomView.findViewById(R.id.favorite_icon_imageview);
3436 TextView tabTitleTextView = tabCustomView.findViewById(R.id.title_textview);
3438 // Set the default favorite icon as the favorite icon for this tab.
3439 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(nestedScrollWebView.getFavoriteOrDefaultIcon(), 64, 64, true));
3441 // Set the loading title text.
3442 tabTitleTextView.setText(R.string.loading);
3445 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3446 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3448 // Get a full cursor from `domainsDatabaseHelper`.
3449 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3451 // Initialize `domainSettingsSet`.
3452 Set<String> domainSettingsSet = new HashSet<>();
3454 // Get the domain name column index.
3455 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3457 // Populate `domainSettingsSet`.
3458 for (int i = 0; i < domainNameCursor.getCount(); i++) {
3459 // Move `domainsCursor` to the current row.
3460 domainNameCursor.moveToPosition(i);
3462 // Store the domain name in `domainSettingsSet`.
3463 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3466 // Close `domainNameCursor.
3467 domainNameCursor.close();
3469 // Initialize the domain name in database variable.
3470 String domainNameInDatabase = null;
3472 // Check the hostname against the domain settings set.
3473 if (domainSettingsSet.contains(newHostName)) { // The hostname is contained in the domain settings set.
3474 // Record the domain name in the database.
3475 domainNameInDatabase = newHostName;
3477 // Set the domain settings applied tracker to true.
3478 nestedScrollWebView.setDomainSettingsApplied(true);
3479 } else { // The hostname is not contained in the domain settings set.
3480 // Set the domain settings applied tracker to false.
3481 nestedScrollWebView.setDomainSettingsApplied(false);
3484 // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3485 while (!nestedScrollWebView.getDomainSettingsApplied() && newHostName.contains(".")) { // Stop checking if domain settings are already applied or there are no more `.` in the host name.
3486 if (domainSettingsSet.contains("*." + newHostName)) { // Check the host name prepended by `*.`.
3487 // Set the domain settings applied tracker to true.
3488 nestedScrollWebView.setDomainSettingsApplied(true);
3490 // Store the applied domain names as it appears in the database.
3491 domainNameInDatabase = "*." + newHostName;
3494 // Strip out the lowest subdomain of of the host name.
3495 newHostName = newHostName.substring(newHostName.indexOf(".") + 1);
3499 // Get a handle for the shared preferences.
3500 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3502 // Store the general preference information.
3503 String defaultFontSizeString = sharedPreferences.getString("font_size", getString(R.string.font_size_default_value));
3504 String defaultUserAgentName = sharedPreferences.getString("user_agent", getString(R.string.user_agent_default_value));
3505 boolean defaultSwipeToRefresh = sharedPreferences.getBoolean("swipe_to_refresh", true);
3506 boolean displayWebpageImages = sharedPreferences.getBoolean("display_webpage_images", true);
3507 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
3509 // Get a handle for the cookie manager.
3510 CookieManager cookieManager = CookieManager.getInstance();
3512 // Get handles for the views.
3513 RelativeLayout urlRelativeLayout = findViewById(R.id.url_relativelayout);
3514 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
3516 // Initialize the user agent array adapter and string array.
3517 ArrayAdapter<CharSequence> userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item);
3518 String[] userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
3520 if (nestedScrollWebView.getDomainSettingsApplied()) { // The url has custom domain settings.
3521 // Get a cursor for the current host and move it to the first position.
3522 Cursor currentDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3523 currentDomainSettingsCursor.moveToFirst();
3525 // Get the settings from the cursor.
3526 nestedScrollWebView.setDomainSettingsDatabaseId(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3527 nestedScrollWebView.setDomainSettingsJavaScriptEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3528 nestedScrollWebView.setAcceptFirstPartyCookies(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3529 boolean domainThirdPartyCookiesEnabled = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3530 nestedScrollWebView.getSettings().setDomStorageEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3531 // Form data can be removed once the minimum API >= 26.
3532 boolean saveFormData = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3533 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASY_LIST,
3534 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3535 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASY_PRIVACY,
3536 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3537 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST,
3538 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3539 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST,
3540 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3541 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRA_PRIVACY,
3542 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_ULTRAPRIVACY)) == 1);
3543 nestedScrollWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS,
3544 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
3545 String userAgentName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3546 int fontSize = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3547 int swipeToRefreshInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
3548 int nightModeInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
3549 int displayWebpageImagesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3550 boolean pinnedSslCertificate = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3551 String pinnedSslIssuedToCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3552 String pinnedSslIssuedToOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3553 String pinnedSslIssuedToUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3554 String pinnedSslIssuedByCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3555 String pinnedSslIssuedByOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3556 String pinnedSslIssuedByUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3557 boolean pinnedIpAddresses = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_IP_ADDRESSES)) == 1);
3558 String pinnedHostIpAddresses = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.IP_ADDRESSES));
3560 // Create the pinned SSL date variables.
3561 Date pinnedSslStartDate;
3562 Date pinnedSslEndDate;
3564 // 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.
3565 if (currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
3566 pinnedSslStartDate = null;
3568 pinnedSslStartDate = new Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
3571 // 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.
3572 if (currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
3573 pinnedSslEndDate = null;
3575 pinnedSslEndDate = new Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
3578 // If there is a pinned SSL certificate, store it in the WebView.
3579 if (pinnedSslCertificate) {
3580 nestedScrollWebView.setPinnedSslCertificate(pinnedSslIssuedToCName, pinnedSslIssuedToOName, pinnedSslIssuedToUName, pinnedSslIssuedByCName, pinnedSslIssuedByOName, pinnedSslIssuedByUName,
3581 pinnedSslStartDate, pinnedSslEndDate);
3584 // If there is a pinned IP address, store it in the WebView.
3585 if (pinnedIpAddresses) {
3586 nestedScrollWebView.setPinnedIpAddresses(pinnedHostIpAddresses);
3589 // Set night mode according to the night mode int.
3590 switch (nightModeInt) {
3591 case DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT:
3592 // Set night mode according to the current default.
3593 nestedScrollWebView.setNightMode(sharedPreferences.getBoolean("night_mode", false));
3596 case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
3597 // Enable night mode.
3598 nestedScrollWebView.setNightMode(true);
3601 case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
3602 // Disable night mode.
3603 nestedScrollWebView.setNightMode(false);
3607 // Enable JavaScript if night mode is enabled.
3608 if (nestedScrollWebView.getNightMode()) {
3609 // Enable JavaScript.
3610 nestedScrollWebView.getSettings().setJavaScriptEnabled(true);
3612 // Set JavaScript according to the domain settings.
3613 nestedScrollWebView.getSettings().setJavaScriptEnabled(nestedScrollWebView.getDomainSettingsJavaScriptEnabled());
3616 // Close the current host domain settings cursor.
3617 currentDomainSettingsCursor.close();
3619 // Apply the domain settings.
3620 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptFirstPartyCookies());
3622 // Set third-party cookies status if API >= 21.
3623 if (Build.VERSION.SDK_INT >= 21) {
3624 cookieManager.setAcceptThirdPartyCookies(nestedScrollWebView, domainThirdPartyCookiesEnabled);
3627 // Apply the form data setting if the API < 26.
3628 if (Build.VERSION.SDK_INT < 26) {
3629 nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
3632 // Apply the font size.
3633 if (fontSize == 0) { // Apply the default font size.
3634 nestedScrollWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3635 } else { // Apply the specified font size.
3636 nestedScrollWebView.getSettings().setTextZoom(fontSize);
3639 // 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.
3640 // <https://redmine.stoutner.com/issues/160>
3641 if (nestedScrollWebView.getProgress() == 100) { // A URL is not loading.
3642 // Set the user agent.
3643 if (userAgentName.equals(getString(R.string.system_default_user_agent))) { // Use the system default user agent.
3644 // Get the array position of the default user agent name.
3645 int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3647 // Set the user agent according to the system default.
3648 switch (defaultUserAgentArrayPosition) {
3649 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
3650 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3651 nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
3654 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3655 // Set the user agent to `""`, which uses the default value.
3656 nestedScrollWebView.getSettings().setUserAgentString("");
3659 case SETTINGS_CUSTOM_USER_AGENT:
3660 // Set the default custom user agent.
3661 nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
3665 // Get the user agent string from the user agent data array
3666 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
3668 } else { // Set the user agent according to the stored name.
3669 // Get the array position of the user agent name.
3670 int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
3672 switch (userAgentArrayPosition) {
3673 case UNRECOGNIZED_USER_AGENT: // The user agent name contains a custom user agent.
3674 nestedScrollWebView.getSettings().setUserAgentString(userAgentName);
3677 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3678 // Set the user agent to `""`, which uses the default value.
3679 nestedScrollWebView.getSettings().setUserAgentString("");
3683 // Get the user agent string from the user agent data array.
3684 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3689 // Set swipe to refresh.
3690 switch (swipeToRefreshInt) {
3691 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_SYSTEM_DEFAULT:
3692 // Store the swipe to refresh status in the nested scroll WebView.
3693 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
3695 // 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.
3696 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
3699 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_ENABLED:
3700 // Store the swipe to refresh status in the nested scroll WebView.
3701 nestedScrollWebView.setSwipeToRefresh(true);
3703 // Enable swipe to refresh. This can be removed once the minimum API >= 23 because it is continuously set by an on scroll change listener.
3704 swipeRefreshLayout.setEnabled(true);
3707 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_DISABLED:
3708 // Store the swipe to refresh status in the nested scroll WebView.
3709 nestedScrollWebView.setSwipeToRefresh(false);
3711 // Disable swipe to refresh. This can be removed once the minimum API >= 23 because it is continuously set by an on scroll change listener.
3712 swipeRefreshLayout.setEnabled(false);
3715 // Set the loading of webpage images.
3716 switch (displayWebpageImagesInt) {
3717 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
3718 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
3721 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
3722 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(true);
3725 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
3726 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(false);
3730 // 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.
3732 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
3734 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
3736 } else { // The new URL does not have custom domain settings. Load the defaults.
3737 // Store the values from the shared preferences.
3738 boolean defaultJavaScriptEnabled = sharedPreferences.getBoolean("javascript", false);
3739 nestedScrollWebView.setAcceptFirstPartyCookies(sharedPreferences.getBoolean("first_party_cookies", false));
3740 boolean defaultThirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies", false);
3741 nestedScrollWebView.getSettings().setDomStorageEnabled(sharedPreferences.getBoolean("dom_storage", false));
3742 boolean saveFormData = sharedPreferences.getBoolean("save_form_data", false); // Form data can be removed once the minimum API >= 26.
3743 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASY_LIST, sharedPreferences.getBoolean("easylist", true));
3744 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASY_PRIVACY, sharedPreferences.getBoolean("easyprivacy", true));
3745 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, sharedPreferences.getBoolean("fanboys_annoyance_list", true));
3746 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, sharedPreferences.getBoolean("fanboys_social_blocking_list", true));
3747 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRA_PRIVACY, sharedPreferences.getBoolean("ultraprivacy", true));
3748 nestedScrollWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, sharedPreferences.getBoolean("block_all_third_party_requests", false));
3749 nestedScrollWebView.setNightMode(sharedPreferences.getBoolean("night_mode", false));
3751 // Enable JavaScript if night mode is enabled.
3752 if (nestedScrollWebView.getNightMode()) {
3753 // Enable JavaScript.
3754 nestedScrollWebView.getSettings().setJavaScriptEnabled(true);
3756 // Set JavaScript according to the domain settings.
3757 nestedScrollWebView.getSettings().setJavaScriptEnabled(defaultJavaScriptEnabled);
3760 // Apply the default settings.
3761 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptFirstPartyCookies());
3762 nestedScrollWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3764 // Apply the form data setting if the API < 26.
3765 if (Build.VERSION.SDK_INT < 26) {
3766 nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
3769 // Store the swipe to refresh status in the nested scroll WebView.
3770 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
3772 // Apply swipe to refresh according to the default.
3773 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
3775 // Reset the pinned variables.
3776 nestedScrollWebView.setDomainSettingsDatabaseId(-1);
3778 // Set third-party cookies status if API >= 21.
3779 if (Build.VERSION.SDK_INT >= 21) {
3780 cookieManager.setAcceptThirdPartyCookies(nestedScrollWebView, defaultThirdPartyCookiesEnabled);
3783 // 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.
3784 // <https://redmine.stoutner.com/issues/160>
3785 if (nestedScrollWebView.getProgress() == 100) { // A URL is not loading.
3786 // Get the array position of the user agent name.
3787 int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3789 // Set the user agent.
3790 switch (userAgentArrayPosition) {
3791 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
3792 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3793 nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
3796 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3797 // Set the user agent to `""`, which uses the default value.
3798 nestedScrollWebView.getSettings().setUserAgentString("");
3801 case SETTINGS_CUSTOM_USER_AGENT:
3802 // Set the default custom user agent.
3803 nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
3807 // Get the user agent string from the user agent data array
3808 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3812 // Set the loading of webpage images.
3813 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
3815 // Set a transparent background on URL edit text. The deprecated `getResources().getDrawable()` must be used until the minimum API >= 21.
3816 urlRelativeLayout.setBackground(getResources().getDrawable(R.color.transparent));
3819 // Close the domains database helper.
3820 domainsDatabaseHelper.close();
3822 // Update the privacy icons.
3823 updatePrivacyIcons(true);
3826 // Reload the website if returning from the Domains activity.
3827 if (reloadWebsite) {
3828 nestedScrollWebView.reload();
3831 // Return the user agent changed status.
3832 return !nestedScrollWebView.getSettings().getUserAgentString().equals(initialUserAgent);
3835 private void applyProxyThroughOrbot(boolean reloadWebsite) {
3836 // Get a handle for the shared preferences.
3837 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3839 // Get the search and theme preferences.
3840 String torSearchString = sharedPreferences.getString("tor_search", getString(R.string.tor_search_default_value));
3841 String torSearchCustomUrlString = sharedPreferences.getString("tor_search_custom_url", getString(R.string.tor_search_custom_url_default_value));
3842 String searchString = sharedPreferences.getString("search", getString(R.string.search_default_value));
3843 String searchCustomUrlString = sharedPreferences.getString("search_custom_url", getString(R.string.search_custom_url_default_value));
3844 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
3846 // Get a handle for the action bar. `getSupportActionBar()` must be used until the minimum API >= 21.
3847 ActionBar actionBar = getSupportActionBar();
3849 // Remove the incorrect lint warning later that the action bar might be null.
3850 assert actionBar != null;
3852 // Set the homepage, search, and proxy options.
3853 if (proxyThroughOrbot) { // Set the Tor options.
3854 // Set the search URL.
3855 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
3856 searchURL = torSearchCustomUrlString;
3857 } else { // Use the string from the pre-built list.
3858 searchURL = torSearchString;
3861 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
3862 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
3864 // Set the `appBar` background to indicate proxying through Orbot is enabled.
3866 actionBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
3868 actionBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
3871 // Check to see if Orbot is ready.
3872 if (!orbotStatus.equals("ON")) { // Orbot is not ready.
3873 // Set `waitingForOrbot`.
3874 waitingForOrbot = true;
3876 // Disable the wide view port so that the waiting for Orbot text is displayed correctly.
3877 currentWebView.getSettings().setUseWideViewPort(false);
3879 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
3880 currentWebView.loadData("<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>", "text/html", null);
3881 } else if (reloadWebsite) { // Orbot is ready and the website should be reloaded.
3882 // Reload the website.
3883 currentWebView.reload();
3885 } else { // Set the non-Tor options.
3886 // Set the search URL.
3887 if (searchString.equals("Custom URL")) { // Get the custom URL string.
3888 searchURL = searchCustomUrlString;
3889 } else { // Use the string from the pre-built list.
3890 searchURL = searchString;
3893 // Reset the proxy to default. The host is `""` and the port is `"0"`.
3894 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
3896 // Set the default `appBar` background.
3898 actionBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
3900 actionBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
3903 // Reset `waitingForOrbot.
3904 waitingForOrbot = false;
3906 // Reload the WebViews if requested.
3907 if (reloadWebsite) {
3908 // Reload the WebViews.
3909 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3910 // Get the WebView tab fragment.
3911 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3913 // Get the fragment view.
3914 View fragmentView = webViewTabFragment.getView();
3916 // Only reload the WebViews if they exist.
3917 if (fragmentView != null) {
3918 // Get the nested scroll WebView from the tab fragment.
3919 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3921 // Reload the WebView.
3922 nestedScrollWebView.reload();
3929 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
3930 // Only update the privacy icons if the options menu and the current WebView have already been populated.
3931 if ((optionsMenu != null) && (currentWebView != null)) {
3932 // Get a handle for the shared preferences.
3933 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3935 // Get the theme and screenshot preferences.
3936 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
3938 // Get handles for the menu items.
3939 MenuItem privacyMenuItem = optionsMenu.findItem(R.id.toggle_javascript);
3940 MenuItem firstPartyCookiesMenuItem = optionsMenu.findItem(R.id.toggle_first_party_cookies);
3941 MenuItem domStorageMenuItem = optionsMenu.findItem(R.id.toggle_dom_storage);
3942 MenuItem refreshMenuItem = optionsMenu.findItem(R.id.refresh);
3944 // Update the privacy icon.
3945 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is enabled.
3946 privacyMenuItem.setIcon(R.drawable.javascript_enabled);
3947 } else if (currentWebView.getAcceptFirstPartyCookies()) { // JavaScript is disabled but cookies are enabled.
3948 privacyMenuItem.setIcon(R.drawable.warning);
3949 } else { // All the dangerous features are disabled.
3950 privacyMenuItem.setIcon(R.drawable.privacy_mode);
3953 // Update the first-party cookies icon.
3954 if (currentWebView.getAcceptFirstPartyCookies()) { // First-party cookies are enabled.
3955 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
3956 } else { // First-party cookies are disabled.
3958 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_dark);
3960 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_light);
3964 // Update the DOM storage icon.
3965 if (currentWebView.getSettings().getJavaScriptEnabled() && currentWebView.getSettings().getDomStorageEnabled()) { // Both JavaScript and DOM storage are enabled.
3966 domStorageMenuItem.setIcon(R.drawable.dom_storage_enabled);
3967 } else if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is enabled but DOM storage is disabled.
3969 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
3971 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
3973 } else { // JavaScript is disabled, so DOM storage is ghosted.
3975 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
3977 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
3981 // Update the refresh icon.
3983 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
3985 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
3988 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
3989 if (runInvalidateOptionsMenu) {
3990 invalidateOptionsMenu();
3995 private void openUrlWithExternalApp(String url) {
3996 // Create a download intent. Not specifying the action type will display the maximum number of options.
3997 Intent downloadIntent = new Intent();
3999 // Set the URI and the MIME type. Specifying `text/html` displays a good number of options.
4000 downloadIntent.setDataAndType(Uri.parse(url), "text/html");
4002 // Flag the intent to open in a new task.
4003 downloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4005 // Show the chooser.
4006 startActivity(Intent.createChooser(downloadIntent, getString(R.string.open_with)));
4009 private void highlightUrlText() {
4010 // Get a handle for the URL edit text.
4011 EditText urlEditText = findViewById(R.id.url_edittext);
4013 // Only highlight the URL text if the box is not currently selected.
4014 if (!urlEditText.hasFocus()) {
4015 // Get the URL string.
4016 String urlString = urlEditText.getText().toString();
4018 // Highlight the URL according to the protocol.
4019 if (urlString.startsWith("file://")) { // This is a file URL.
4020 // De-emphasize only the protocol.
4021 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4022 } else if (urlString.startsWith("content://")) {
4023 // De-emphasize only the protocol.
4024 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 10, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4025 } else { // This is a web URL.
4026 // Get the index of the `/` immediately after the domain name.
4027 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
4029 // Create a base URL string.
4032 // Get the base URL.
4033 if (endOfDomainName > 0) { // There is at least one character after the base URL.
4034 // Get the base URL.
4035 baseUrl = urlString.substring(0, endOfDomainName);
4036 } else { // There are no characters after the base URL.
4037 // Set the base URL to be the entire URL string.
4038 baseUrl = urlString;
4041 // Get the index of the last `.` in the domain.
4042 int lastDotIndex = baseUrl.lastIndexOf(".");
4044 // Get the index of the penultimate `.` in the domain.
4045 int penultimateDotIndex = baseUrl.lastIndexOf(".", lastDotIndex - 1);
4047 // Markup the beginning of the URL.
4048 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
4049 urlEditText.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4051 // De-emphasize subdomains.
4052 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
4053 urlEditText.getText().setSpan(initialGrayColorSpan, 7, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4055 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
4056 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
4057 // De-emphasize the protocol and the additional subdomains.
4058 urlEditText.getText().setSpan(initialGrayColorSpan, 0, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4059 } else { // There is only one subdomain in the domain name.
4060 // De-emphasize only the protocol.
4061 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4065 // De-emphasize the text after the domain name.
4066 if (endOfDomainName > 0) {
4067 urlEditText.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4073 private void loadBookmarksFolder() {
4074 // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
4075 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
4077 // Populate the bookmarks cursor adapter. `this` specifies the `Context`. `false` disables `autoRequery`.
4078 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
4080 public View newView(Context context, Cursor cursor, ViewGroup parent) {
4081 // Inflate the individual item layout. `false` does not attach it to the root.
4082 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
4086 public void bindView(View view, Context context, Cursor cursor) {
4087 // Get handles for the views.
4088 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
4089 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
4091 // Get the favorite icon byte array from the cursor.
4092 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
4094 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
4095 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
4097 // Display the bitmap in `bookmarkFavoriteIcon`.
4098 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
4100 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
4101 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
4102 bookmarkNameTextView.setText(bookmarkNameString);
4104 // Make the font bold for folders.
4105 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
4106 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
4107 } else { // Reset the font to default for normal bookmarks.
4108 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
4113 // Get a handle for the bookmarks list view.
4114 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
4116 // Populate the list view with the adapter.
4117 bookmarksListView.setAdapter(bookmarksCursorAdapter);
4119 // Get a handle for the bookmarks title text view.
4120 TextView bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
4122 // Set the bookmarks drawer title.
4123 if (currentBookmarksFolder.isEmpty()) {
4124 bookmarksTitleTextView.setText(R.string.bookmarks);
4126 bookmarksTitleTextView.setText(currentBookmarksFolder);
4130 private void openWithApp(String url) {
4131 // Create the open with intent with `ACTION_VIEW`.
4132 Intent openWithAppIntent = new Intent(Intent.ACTION_VIEW);
4134 // Set the URI but not the MIME type. This should open all available apps.
4135 openWithAppIntent.setData(Uri.parse(url));
4137 // Flag the intent to open in a new task.
4138 openWithAppIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4140 // Show the chooser.
4141 startActivity(openWithAppIntent);
4144 private void openWithBrowser(String url) {
4145 // Create the open with intent with `ACTION_VIEW`.
4146 Intent openWithBrowserIntent = new Intent(Intent.ACTION_VIEW);
4148 // Set the URI and the MIME type. `"text/html"` should load browser options.
4149 openWithBrowserIntent.setDataAndType(Uri.parse(url), "text/html");
4151 // Flag the intent to open in a new task.
4152 openWithBrowserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4154 // Show the chooser.
4155 startActivity(openWithBrowserIntent);
4158 public void addTab(View view) {
4159 // Get a handle for the tab layout and the view pager.
4160 TabLayout tabLayout = findViewById(R.id.tablayout);
4161 ViewPager webViewPager = findViewById(R.id.webviewpager);
4163 // Get the new page number. The page numbers are 0 indexed, so the new page number will match the current count.
4164 int newTabNumber = tabLayout.getTabCount();
4167 tabLayout.addTab(tabLayout.newTab());
4170 TabLayout.Tab newTab = tabLayout.getTabAt(newTabNumber);
4172 // Remove the lint warning below that the current tab might be null.
4173 assert newTab != null;
4175 // Set a custom view on the new tab.
4176 newTab.setCustomView(R.layout.tab_custom_view);
4178 // Add the new WebView page.
4179 webViewPagerAdapter.addPage(newTabNumber, webViewPager);
4182 private void setCurrentWebView(int pageNumber) {
4183 // Get a handle for the shared preferences.
4184 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4186 // Get the theme preference.
4187 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
4189 // Get handles for the URL views.
4190 RelativeLayout urlRelativeLayout = findViewById(R.id.url_relativelayout);
4191 EditText urlEditText = findViewById(R.id.url_edittext);
4192 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
4194 //Stop the swipe to refresh indicator if it is running
4195 swipeRefreshLayout.setRefreshing(false);
4197 // Get the WebView tab fragment.
4198 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(pageNumber);
4200 // Get the fragment view.
4201 View fragmentView = webViewTabFragment.getView();
4203 // Set the current WebView if the fragment view is not null.
4204 if (fragmentView != null) {
4205 // Store the current WebView.
4206 currentWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4208 // Update the status of swipe to refresh.
4209 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
4210 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.
4211 // Enable the swipe refresh layout if the WebView is scrolled all the way to the top.
4212 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
4214 // Enable the swipe refresh layout.
4215 swipeRefreshLayout.setEnabled(true);
4217 } else { // Swipe to refresh is disabled.
4218 // Disable the swipe refresh layout.
4219 swipeRefreshLayout.setEnabled(false);
4222 // Get a handle for the cookie manager.
4223 CookieManager cookieManager = CookieManager.getInstance();
4225 // Set the first-party cookie status.
4226 cookieManager.setAcceptCookie(currentWebView.getAcceptFirstPartyCookies());
4228 // Update the privacy icons. `true` redraws the icons in the app bar.
4229 updatePrivacyIcons(true);
4231 // Get a handle for the input method manager.
4232 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
4234 // Remove the lint warning below that the input method manager might be null.
4235 assert inputMethodManager != null;
4237 // Get the current URL.
4238 String url = currentWebView.getUrl();
4240 if ((url == null) || url.equals("about:blank")) { // The WebView is blank.
4241 // Display the hint in the URL edit text.
4242 urlEditText.setText("");
4244 // Request focus for the URL text box.
4245 urlEditText.requestFocus();
4247 // Display the keyboard.
4248 inputMethodManager.showSoftInput(urlEditText, 0);
4249 } else { // The WebView has a loaded URL.
4250 // Clear the focus from the URL text box.
4251 urlEditText.clearFocus();
4253 // Hide the soft keyboard.
4254 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
4256 // Display the current URL in the URL text box.
4257 urlEditText.setText(url);
4259 // Highlight the URL text.
4263 // Set the background to indicate the domain settings status.
4264 if (currentWebView.getDomainSettingsApplied()) {
4265 // 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.
4267 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
4269 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
4272 urlRelativeLayout.setBackground(getResources().getDrawable(R.color.transparent));
4278 public void initializeWebView(NestedScrollWebView nestedScrollWebView, int pageNumber, ProgressBar progressBar) {
4279 // Get handles for the activity views.
4280 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
4281 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
4282 RelativeLayout mainContentRelativeLayout = findViewById(R.id.main_content_relativelayout);
4283 ActionBar actionBar = getSupportActionBar();
4284 LinearLayout tabsLinearLayout = findViewById(R.id.tabs_linearlayout);
4285 EditText urlEditText = findViewById(R.id.url_edittext);
4286 TabLayout tabLayout = findViewById(R.id.tablayout);
4287 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
4289 // Remove the incorrect lint warning below that the action bar might be null.
4290 assert actionBar != null;
4292 // Get a handle for the activity
4293 Activity activity = this;
4295 // Get a handle for the input method manager.
4296 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
4298 // Instantiate the blocklist helper.
4299 BlockListHelper blockListHelper = new BlockListHelper();
4301 // Remove the lint warning below that the input method manager might be null.
4302 assert inputMethodManager != null;
4304 // Get a handle for the shared preferences.
4305 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4307 // Get the relevant preferences.
4308 boolean downloadWithExternalApp = sharedPreferences.getBoolean("download_with_external_app", false);
4310 // Initialize the favorite icon.
4311 nestedScrollWebView.initializeFavoriteIcon();
4313 // Set the app bar scrolling.
4314 nestedScrollWebView.setNestedScrollingEnabled(sharedPreferences.getBoolean("scroll_app_bar", true));
4316 // Allow pinch to zoom.
4317 nestedScrollWebView.getSettings().setBuiltInZoomControls(true);
4319 // Hide zoom controls.
4320 nestedScrollWebView.getSettings().setDisplayZoomControls(false);
4322 // Don't allow mixed content (HTTP and HTTPS) on the same website.
4323 if (Build.VERSION.SDK_INT >= 21) {
4324 nestedScrollWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW);
4327 // Set the WebView to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
4328 nestedScrollWebView.getSettings().setUseWideViewPort(true);
4330 // Set the WebView to load in overview mode (zoomed out to the maximum width).
4331 nestedScrollWebView.getSettings().setLoadWithOverviewMode(true);
4333 // Explicitly disable geolocation.
4334 nestedScrollWebView.getSettings().setGeolocationEnabled(false);
4336 // Create a double-tap gesture detector to toggle full-screen mode.
4337 GestureDetector doubleTapGestureDetector = new GestureDetector(getApplicationContext(), new GestureDetector.SimpleOnGestureListener() {
4338 // Override `onDoubleTap()`. All other events are handled using the default settings.
4340 public boolean onDoubleTap(MotionEvent event) {
4341 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
4342 // Toggle the full screen browsing mode tracker.
4343 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
4345 // Toggle the full screen browsing mode.
4346 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
4347 // Hide the app bar if specified.
4349 // Close the find on page bar if it is visible.
4350 closeFindOnPage(null);
4352 // Hide the tab linear layout.
4353 tabsLinearLayout.setVisibility(View.GONE);
4355 // Hide the action bar.
4359 // Hide the banner ad in the free flavor.
4360 if (BuildConfig.FLAVOR.contentEquals("free")) {
4361 AdHelper.hideAd(findViewById(R.id.adview));
4364 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
4365 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4367 /* Hide the system bars.
4368 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4369 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4370 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4371 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4373 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
4374 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
4375 } else { // Switch to normal viewing mode.
4376 // Show the tab linear layout.
4377 tabsLinearLayout.setVisibility(View.VISIBLE);
4379 // Show the action bar.
4382 // Show the banner ad in the free flavor.
4383 if (BuildConfig.FLAVOR.contentEquals("free")) {
4385 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
4388 // Remove the `SYSTEM_UI` flags from the root frame layout.
4389 rootFrameLayout.setSystemUiVisibility(0);
4391 // Add the translucent status flag.
4392 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4395 // Consume the double-tap.
4397 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
4403 // Pass all touch events on the WebView through the double-tap gesture detector.
4404 nestedScrollWebView.setOnTouchListener((View view, MotionEvent event) -> {
4405 // Call `performClick()` on the view, which is required for accessibility.
4406 view.performClick();
4408 // Send the event to the gesture detector.
4409 return doubleTapGestureDetector.onTouchEvent(event);
4412 // Register the WebView for a context menu. This is used to see link targets and download images.
4413 registerForContextMenu(nestedScrollWebView);
4415 // Allow the downloading of files.
4416 nestedScrollWebView.setDownloadListener((String url, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
4417 // Check if the download should be processed by an external app.
4418 if (downloadWithExternalApp) { // Download with an external app.
4419 // Create a download intent. Not specifying the action type will display the maximum number of options.
4420 Intent downloadIntent = new Intent();
4422 // Set the URI and the MIME type. Specifying `text/html` displays a good number of options.
4423 downloadIntent.setDataAndType(Uri.parse(url), "text/html");
4425 // Flag the intent to open in a new task.
4426 downloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4428 // Show the chooser.
4429 startActivity(Intent.createChooser(downloadIntent, getString(R.string.open_with)));
4430 } else { // Download with Android's download manager.
4431 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
4432 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission has not been granted.
4433 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
4435 // Store the variables for future use by `onRequestPermissionsResult()`.
4437 downloadContentDisposition = contentDisposition;
4438 downloadContentLength = contentLength;
4440 // Show a dialog if the user has previously denied the permission.
4441 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
4442 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
4443 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
4445 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
4446 downloadLocationPermissionDialogFragment.show(getSupportFragmentManager(), getString(R.string.download_location));
4447 } else { // Show the permission request directly.
4448 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
4449 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
4451 } else { // The storage permission has already been granted.
4452 // Get a handle for the download file alert dialog.
4453 DialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
4455 // Show the download file alert dialog.
4456 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
4461 // Update the find on page count.
4462 nestedScrollWebView.setFindListener(new WebView.FindListener() {
4463 // Get a handle for `findOnPageCountTextView`.
4464 final TextView findOnPageCountTextView = findViewById(R.id.find_on_page_count_textview);
4467 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
4468 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
4469 // Set `findOnPageCountTextView` to `0/0`.
4470 findOnPageCountTextView.setText(R.string.zero_of_zero);
4471 } else if (isDoneCounting) { // There are matches.
4472 // `activeMatchOrdinal` is zero-based.
4473 int activeMatch = activeMatchOrdinal + 1;
4475 // Build the match string.
4476 String matchString = activeMatch + "/" + numberOfMatches;
4478 // Set `findOnPageCountTextView`.
4479 findOnPageCountTextView.setText(matchString);
4484 if (Build.VERSION.SDK_INT >= 23) {
4485 nestedScrollWebView.setOnScrollChangeListener((View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) -> {
4486 // Update the status of swipe to refresh if it is enabled.
4487 if (nestedScrollWebView.getSwipeToRefresh()) {
4488 // Only enable swipe to refresh if the WebView is scrolled to the top.
4489 swipeRefreshLayout.setEnabled(scrollY == 0);
4494 // Set the web chrome client.
4495 nestedScrollWebView.setWebChromeClient(new WebChromeClient() {
4496 // Update the progress bar when a page is loading.
4498 public void onProgressChanged(WebView view, int progress) {
4499 // Inject the night mode CSS if night mode is enabled.
4500 if (nestedScrollWebView.getNightMode()) { // Night mode is enabled.
4501 // `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
4502 // used by WordPress. `text-decoration: none` removes all text underlines. `text-shadow: none` removes text shadows, which usually have a hard coded color.
4503 // `border: none` removes all borders, which can also be used to underline text. `a {color: #1565C0}` sets links to be a dark blue.
4504 // `::selection {background: #0D47A1}' sets the text selection highlight color to be a dark blue. `!important` takes precedent over any existing sub-settings.
4505 nestedScrollWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; " +
4506 "style.innerHTML = '* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important;" +
4507 "text-shadow: none !important; border: none !important;} a {color: #1565C0 !important;} ::selection {background: #0D47A1 !important;}'; parent.appendChild(style)})()", value -> {
4508 // Initialize a handler to display `mainWebView`.
4509 Handler displayWebViewHandler = new Handler();
4511 // Setup a runnable to display `mainWebView` after a delay to allow the CSS to be applied.
4512 Runnable displayWebViewRunnable = () -> {
4513 // Only display `mainWebView` if the progress bar is gone. This prevents the display of the `WebView` while it is still loading.
4514 if (progressBar.getVisibility() == View.GONE) {
4515 nestedScrollWebView.setVisibility(View.VISIBLE);
4519 // Display the WebView after 500 milliseconds.
4520 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
4522 } else { // Night mode is disabled.
4523 // Display the nested scroll WebView if night mode is disabled.
4524 // Because of a race condition between `applyDomainSettings` and `onPageStarted`,
4525 // when night mode is set by domain settings the WebView may be hidden even if night mode is not currently enabled.
4526 nestedScrollWebView.setVisibility(View.VISIBLE);
4529 // Update the progress bar.
4530 progressBar.setProgress(progress);
4532 // Set the visibility of the progress bar.
4533 if (progress < 100) {
4534 // Show the progress bar.
4535 progressBar.setVisibility(View.VISIBLE);
4537 // Hide the progress bar.
4538 progressBar.setVisibility(View.GONE);
4540 //Stop the swipe to refresh indicator if it is running
4541 swipeRefreshLayout.setRefreshing(false);
4545 // Set the favorite icon when it changes.
4547 public void onReceivedIcon(WebView view, Bitmap icon) {
4548 // Only update the favorite icon if the website has finished loading.
4549 if (progressBar.getVisibility() == View.GONE) {
4550 // Store the new favorite icon.
4551 nestedScrollWebView.setFavoriteOrDefaultIcon(icon);
4553 // Get the current page position.
4554 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
4556 // Get the current tab.
4557 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
4559 // Check to see if the tab has been populated.
4561 // Get the custom view from the tab.
4562 View tabView = tab.getCustomView();
4564 // Check to see if the custom tab view has been populated.
4565 if (tabView != null) {
4566 // Get the favorite icon image view from the tab.
4567 ImageView tabFavoriteIconImageView = tabView.findViewById(R.id.favorite_icon_imageview);
4569 // Display the favorite icon in the tab.
4570 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
4576 // Save a copy of the title when it changes.
4578 public void onReceivedTitle(WebView view, String title) {
4579 // Get the current page position.
4580 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
4582 // Get the current tab.
4583 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
4585 // Only populate the title text view if the tab has been fully created.
4587 // Get the custom view from the tab.
4588 View tabView = tab.getCustomView();
4590 // Remove the incorrect warning below that the current tab view might be null.
4591 assert tabView != null;
4593 // Get the title text view from the tab.
4594 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
4596 // Set the title as the tab text.
4597 tabTitleTextView.setText(title);
4601 // Enter full screen video.
4603 public void onShowCustomView(View video, CustomViewCallback callback) {
4604 // Get a handle for the full screen video frame layout.
4605 FrameLayout fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
4607 // Set the full screen video flag.
4608 displayingFullScreenVideo = true;
4610 // Pause the ad if this is the free flavor.
4611 if (BuildConfig.FLAVOR.contentEquals("free")) {
4612 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
4613 AdHelper.pauseAd(findViewById(R.id.adview));
4616 // Hide the keyboard.
4617 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
4619 // Hide the main content relative layout.
4620 mainContentRelativeLayout.setVisibility(View.GONE);
4622 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
4623 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
4625 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
4626 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4628 /* Hide the system bars.
4629 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4630 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4631 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4632 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4634 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
4635 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
4637 // Disable the sliding drawers.
4638 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
4640 // Add the video view to the full screen video frame layout.
4641 fullScreenVideoFrameLayout.addView(video);
4643 // Show the full screen video frame layout.
4644 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
4647 // Exit full screen video.
4649 public void onHideCustomView() {
4650 // Get a handle for the full screen video frame layout.
4651 FrameLayout fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
4653 // Unset the full screen video flag.
4654 displayingFullScreenVideo = false;
4656 // Remove all the views from the full screen video frame layout.
4657 fullScreenVideoFrameLayout.removeAllViews();
4659 // Hide the full screen video frame layout.
4660 fullScreenVideoFrameLayout.setVisibility(View.GONE);
4662 // Enable the sliding drawers.
4663 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
4665 // Show the main content relative layout.
4666 mainContentRelativeLayout.setVisibility(View.VISIBLE);
4668 // Apply the appropriate full screen mode flags.
4669 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
4670 // Hide the app bar if specified.
4672 // Hide the tab linear layout.
4673 tabsLinearLayout.setVisibility(View.GONE);
4675 // Hide the action bar.
4679 // Hide the banner ad in the free flavor.
4680 if (BuildConfig.FLAVOR.contentEquals("free")) {
4681 AdHelper.hideAd(findViewById(R.id.adview));
4684 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
4685 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4687 /* Hide the system bars.
4688 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4689 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4690 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4691 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4693 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
4694 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
4695 } else { // Switch to normal viewing mode.
4696 // Remove the `SYSTEM_UI` flags from the root frame layout.
4697 rootFrameLayout.setSystemUiVisibility(0);
4699 // Add the translucent status flag.
4700 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4703 // Reload the ad for the free flavor if not in full screen mode.
4704 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
4706 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
4712 public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
4713 // Show the file chooser if the device is running API >= 21.
4714 if (Build.VERSION.SDK_INT >= 21) {
4715 // Store the file path callback.
4716 fileChooserCallback = filePathCallback;
4718 // Create an intent to open a chooser based ont the file chooser parameters.
4719 Intent fileChooserIntent = fileChooserParams.createIntent();
4721 // Open the file chooser. Currently only one `startActivityForResult` exists in this activity, so the request code, used to differentiate them, is simply `0`.
4722 startActivityForResult(fileChooserIntent, 0);
4728 nestedScrollWebView.setWebViewClient(new WebViewClient() {
4729 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
4730 // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
4732 public boolean shouldOverrideUrlLoading(WebView view, String url) {
4733 if (url.startsWith("http")) { // Load the URL in Privacy Browser.
4734 // Apply the domain settings for the new URL. This doesn't do anything if the domain has not changed.
4735 boolean userAgentChanged = applyDomainSettings(nestedScrollWebView, url, true, false);
4737 // Check if the user agent has changed.
4738 if (userAgentChanged) {
4739 // Manually load the URL. The changing of the user agent will cause WebView to reload the previous URL.
4740 nestedScrollWebView.loadUrl(url, customHeaders);
4742 // Returning true indicates that Privacy Browser is manually handling the loading of the URL.
4745 // Returning false causes the current WebView to handle the URL and prevents it from adding redirects to the history list.
4748 } else if (url.startsWith("mailto:")) { // Load the email address in an external email program.
4749 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
4750 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
4752 // Parse the url and set it as the data for the intent.
4753 emailIntent.setData(Uri.parse(url));
4755 // Open the email program in a new task instead of as part of Privacy Browser.
4756 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4759 startActivity(emailIntent);
4761 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
4763 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
4764 // Open the dialer and load the phone number, but wait for the user to place the call.
4765 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
4767 // Add the phone number to the intent.
4768 dialIntent.setData(Uri.parse(url));
4770 // Open the dialer in a new task instead of as part of Privacy Browser.
4771 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4774 startActivity(dialIntent);
4776 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
4778 } else { // Load a system chooser to select an app that can handle the URL.
4779 // Open an app that can handle the URL.
4780 Intent genericIntent = new Intent(Intent.ACTION_VIEW);
4782 // Add the URL to the intent.
4783 genericIntent.setData(Uri.parse(url));
4785 // List all apps that can handle the URL instead of just opening the first one.
4786 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
4788 // Open the app in a new task instead of as part of Privacy Browser.
4789 genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4791 // Start the app or display a snackbar if no app is available to handle the URL.
4793 startActivity(genericIntent);
4794 } catch (ActivityNotFoundException exception) {
4795 Snackbar.make(nestedScrollWebView, getString(R.string.unrecognized_url) + " " + url, Snackbar.LENGTH_SHORT).show();
4798 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
4803 // Check requests against the block lists. The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
4805 public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
4806 // Get a handle for the navigation view.
4807 NavigationView navigationView = findViewById(R.id.navigationview);
4809 // Get a handle for the navigation menu.
4810 Menu navigationMenu = navigationView.getMenu();
4812 // Get a handle for the navigation requests menu item. The menu is 0 based.
4813 MenuItem navigationRequestsMenuItem = navigationMenu.getItem(6);
4815 // Create an empty web resource response to be used if the resource request is blocked.
4816 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
4818 // Reset the whitelist results tracker.
4819 String[] whitelistResultStringArray = null;
4821 // Initialize the third party request tracker.
4822 boolean isThirdPartyRequest = false;
4824 // Get the current URL. `.getUrl()` throws an error because operations on the WebView cannot be made from this thread.
4825 String currentBaseDomain = nestedScrollWebView.getCurrentDomainName();
4827 // Store a copy of the current domain for use in later requests.
4828 String currentDomain = currentBaseDomain;
4830 // Nobody is happy when comparing null strings.
4831 if ((currentBaseDomain != null) && (url != null)) {
4832 // Convert the request URL to a URI.
4833 Uri requestUri = Uri.parse(url);
4835 // Get the request host name.
4836 String requestBaseDomain = requestUri.getHost();
4838 // Only check for third-party requests if the current base domain is not empty and the request domain is not null.
4839 if (!currentBaseDomain.isEmpty() && (requestBaseDomain != null)) {
4840 // Determine the current base domain.
4841 while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
4842 // Remove the first subdomain.
4843 currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
4846 // Determine the request base domain.
4847 while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
4848 // Remove the first subdomain.
4849 requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
4852 // Update the third party request tracker.
4853 isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
4857 // Get the current WebView page position.
4858 int webViewPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
4860 // Determine if the WebView is currently displayed.
4861 boolean webViewDisplayed = (webViewPagePosition == tabLayout.getSelectedTabPosition());
4863 // Block third-party requests if enabled.
4864 if (isThirdPartyRequest && nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS)) {
4865 // Add the result to the resource requests.
4866 nestedScrollWebView.addResourceRequest(new String[]{BlockListHelper.REQUEST_THIRD_PARTY, url});
4868 // Increment the blocked requests counters.
4869 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
4870 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS);
4872 // Update the titles of the blocklist menu items if the WebView is currently displayed.
4873 if (webViewDisplayed) {
4874 // Updating the UI must be run from the UI thread.
4875 activity.runOnUiThread(() -> {
4876 // Update the menu item titles.
4877 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
4879 // Update the options menu if it has been populated.
4880 if (optionsMenu != null) {
4881 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
4882 optionsMenu.findItem(R.id.block_all_third_party_requests).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " +
4883 getString(R.string.block_all_third_party_requests));
4888 // Return an empty web resource response.
4889 return emptyWebResourceResponse;
4892 // Check UltraPrivacy if it is enabled.
4893 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY)) {
4894 // Check the URL against UltraPrivacy.
4895 String[] ultraPrivacyResults = blockListHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraPrivacy);
4897 // Process the UltraPrivacy results.
4898 if (ultraPrivacyResults[0].equals(BlockListHelper.REQUEST_BLOCKED)) { // The resource request matched UltraPrivacy's blacklist.
4899 // Add the result to the resource requests.
4900 nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
4901 ultraPrivacyResults[5]});
4903 // Increment the blocked requests counters.
4904 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
4905 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRA_PRIVACY);
4907 // Update the titles of the blocklist menu items if the WebView is currently displayed.
4908 if (webViewDisplayed) {
4909 // Updating the UI must be run from the UI thread.
4910 activity.runOnUiThread(() -> {
4911 // Update the menu item titles.
4912 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
4914 // Update the options menu if it has been populated.
4915 if (optionsMenu != null) {
4916 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
4917 optionsMenu.findItem(R.id.ultraprivacy).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRA_PRIVACY) + " - " + getString(R.string.ultraprivacy));
4922 // The resource request was blocked. Return an empty web resource response.
4923 return emptyWebResourceResponse;
4924 } else if (ultraPrivacyResults[0].equals(BlockListHelper.REQUEST_ALLOWED)) { // The resource request matched UltraPrivacy's whitelist.
4925 // Add a whitelist entry to the resource requests array.
4926 nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
4927 ultraPrivacyResults[5]});
4929 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
4934 // Check EasyList if it is enabled.
4935 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST)) {
4936 // Check the URL against EasyList.
4937 String[] easyListResults = blockListHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyList);
4939 // Process the EasyList results.
4940 if (easyListResults[0].equals(BlockListHelper.REQUEST_BLOCKED)) { // The resource request matched EasyList's blacklist.
4941 // Add the result to the resource requests.
4942 nestedScrollWebView.addResourceRequest(new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]});
4944 // Increment the blocked requests counters.
4945 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
4946 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASY_LIST);
4948 // Update the titles of the blocklist menu items if the WebView is currently displayed.
4949 if (webViewDisplayed) {
4950 // Updating the UI must be run from the UI thread.
4951 activity.runOnUiThread(() -> {
4952 // Update the menu item titles.
4953 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
4955 // Update the options menu if it has been populated.
4956 if (optionsMenu != null) {
4957 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
4958 optionsMenu.findItem(R.id.easylist).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASY_LIST) + " - " + getString(R.string.easylist));
4963 // The resource request was blocked. Return an empty web resource response.
4964 return emptyWebResourceResponse;
4965 } else if (easyListResults[0].equals(BlockListHelper.REQUEST_ALLOWED)) { // The resource request matched EasyList's whitelist.
4966 // Update the whitelist result string array tracker.
4967 whitelistResultStringArray = new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]};
4971 // Check EasyPrivacy if it is enabled.
4972 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY)) {
4973 // Check the URL against EasyPrivacy.
4974 String[] easyPrivacyResults = blockListHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyPrivacy);
4976 // Process the EasyPrivacy results.
4977 if (easyPrivacyResults[0].equals(BlockListHelper.REQUEST_BLOCKED)) { // The resource request matched EasyPrivacy's blacklist.
4978 // Add the result to the resource requests.
4979 nestedScrollWebView.addResourceRequest(new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4],
4980 easyPrivacyResults[5]});
4982 // Increment the blocked requests counters.
4983 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
4984 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASY_PRIVACY);
4986 // Update the titles of the blocklist menu items if the WebView is currently displayed.
4987 if (webViewDisplayed) {
4988 // Updating the UI must be run from the UI thread.
4989 activity.runOnUiThread(() -> {
4990 // Update the menu item titles.
4991 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
4993 // Update the options menu if it has been populated.
4994 if (optionsMenu != null) {
4995 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
4996 optionsMenu.findItem(R.id.easyprivacy).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASY_PRIVACY) + " - " + getString(R.string.easyprivacy));
5001 // The resource request was blocked. Return an empty web resource response.
5002 return emptyWebResourceResponse;
5003 } else if (easyPrivacyResults[0].equals(BlockListHelper.REQUEST_ALLOWED)) { // The resource request matched EasyPrivacy's whitelist.
5004 // Update the whitelist result string array tracker.
5005 whitelistResultStringArray = new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5]};
5009 // Check Fanboy’s Annoyance List if it is enabled.
5010 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST)) {
5011 // Check the URL against Fanboy's Annoyance List.
5012 String[] fanboysAnnoyanceListResults = blockListHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList);
5014 // Process the Fanboy's Annoyance List results.
5015 if (fanboysAnnoyanceListResults[0].equals(BlockListHelper.REQUEST_BLOCKED)) { // The resource request matched Fanboy's Annoyance List's blacklist.
5016 // Add the result to the resource requests.
5017 nestedScrollWebView.addResourceRequest(new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5018 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]});
5020 // Increment the blocked requests counters.
5021 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5022 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST);
5024 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5025 if (webViewDisplayed) {
5026 // Updating the UI must be run from the UI thread.
5027 activity.runOnUiThread(() -> {
5028 // Update the menu item titles.
5029 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5031 // Update the options menu if it has been populated.
5032 if (optionsMenu != null) {
5033 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5034 optionsMenu.findItem(R.id.fanboys_annoyance_list).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " +
5035 getString(R.string.fanboys_annoyance_list));
5040 // The resource request was blocked. Return an empty web resource response.
5041 return emptyWebResourceResponse;
5042 } else if (fanboysAnnoyanceListResults[0].equals(BlockListHelper.REQUEST_ALLOWED)){ // The resource request matched Fanboy's Annoyance List's whitelist.
5043 // Update the whitelist result string array tracker.
5044 whitelistResultStringArray = new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5045 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]};
5047 } else if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST)) { // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
5048 // Check the URL against Fanboy's Annoyance List.
5049 String[] fanboysSocialListResults = blockListHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysSocialList);
5051 // Process the Fanboy's Social Blocking List results.
5052 if (fanboysSocialListResults[0].equals(BlockListHelper.REQUEST_BLOCKED)) { // The resource request matched Fanboy's Social Blocking List's blacklist.
5053 // Add the result to the resource requests.
5054 nestedScrollWebView.addResourceRequest(new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5055 fanboysSocialListResults[4], fanboysSocialListResults[5]});
5057 // Increment the blocked requests counters.
5058 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5059 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST);
5061 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5062 if (webViewDisplayed) {
5063 // Updating the UI must be run from the UI thread.
5064 activity.runOnUiThread(() -> {
5065 // Update the menu item titles.
5066 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5068 // Update the options menu if it has been populated.
5069 if (optionsMenu != null) {
5070 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5071 optionsMenu.findItem(R.id.fanboys_social_blocking_list).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " +
5072 getString(R.string.fanboys_social_blocking_list));
5077 // The resource request was blocked. Return an empty web resource response.
5078 return emptyWebResourceResponse;
5079 } else if (fanboysSocialListResults[0].equals(BlockListHelper.REQUEST_ALLOWED)) { // The resource request matched Fanboy's Social Blocking List's whitelist.
5080 // Update the whitelist result string array tracker.
5081 whitelistResultStringArray = new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5082 fanboysSocialListResults[4], fanboysSocialListResults[5]};
5086 // Add the request to the log because it hasn't been processed by any of the previous checks.
5087 if (whitelistResultStringArray != null) { // The request was processed by a whitelist.
5088 nestedScrollWebView.addResourceRequest(whitelistResultStringArray);
5089 } else { // The request didn't match any blocklist entry. Log it as a default request.
5090 nestedScrollWebView.addResourceRequest(new String[]{BlockListHelper.REQUEST_DEFAULT, url});
5093 // The resource request has not been blocked. `return null` loads the requested resource.
5097 // Handle HTTP authentication requests.
5099 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
5100 // Store the handler.
5101 nestedScrollWebView.setHttpAuthHandler(handler);
5103 // Instantiate an HTTP authentication dialog.
5104 DialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm, nestedScrollWebView.getWebViewFragmentId());
5106 // Show the HTTP authentication dialog.
5107 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
5111 public void onPageStarted(WebView view, String url, Bitmap favicon) {
5112 // Get the theme preference.
5113 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
5115 // Reset the list of resource requests.
5116 nestedScrollWebView.clearResourceRequests();
5118 // Reset the requests counters.
5119 nestedScrollWebView.resetRequestsCounters();
5121 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
5122 if (nestedScrollWebView.getNightMode()) {
5123 nestedScrollWebView.setVisibility(View.INVISIBLE);
5125 nestedScrollWebView.setVisibility(View.VISIBLE);
5128 // Hide the keyboard.
5129 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
5131 // Check to see if Privacy Browser is waiting on Orbot.
5132 if (!waitingForOrbot) { // Process the URL.
5133 // Get the current page position.
5134 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5136 // Update the URL text bar if the page is currently selected.
5137 if (tabLayout.getSelectedTabPosition() == currentPagePosition) {
5138 // Display the formatted URL text.
5139 urlEditText.setText(url);
5141 // Apply text highlighting to `urlTextBox`.
5145 // Reset the list of host IP addresses.
5146 nestedScrollWebView.clearCurrentIpAddresses();
5148 // Get a URI for the current URL.
5149 Uri currentUri = Uri.parse(url);
5151 // Get the IP addresses for the host.
5152 new GetHostIpAddresses(activity, getSupportFragmentManager(), nestedScrollWebView).execute(currentUri.getHost());
5154 // Apply any custom domain settings if the URL was loaded by navigating history.
5155 if (nestedScrollWebView.getNavigatingHistory()) {
5156 // Reset navigating history.
5157 nestedScrollWebView.setNavigatingHistory(false);
5159 // Apply the domain settings.
5160 boolean userAgentChanged = applyDomainSettings(nestedScrollWebView, url, true, false);
5162 // Manually load the URL if the user agent has changed, which will have caused the previous URL to be reloaded.
5163 if (userAgentChanged) {
5168 // Replace Refresh with Stop if the options menu has been created. (The WebView typically begins loading before the menu items are instantiated.)
5169 if (optionsMenu != null) {
5170 // Get a handle for the refresh menu item.
5171 MenuItem refreshMenuItem = optionsMenu.findItem(R.id.refresh);
5174 refreshMenuItem.setTitle(R.string.stop);
5176 // Get the app bar and theme preferences.
5177 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
5179 // If the icon is displayed in the AppBar, set it according to the theme.
5180 if (displayAdditionalAppBarIcons) {
5182 refreshMenuItem.setIcon(R.drawable.close_dark);
5184 refreshMenuItem.setIcon(R.drawable.close_light);
5192 public void onPageFinished(WebView view, String url) {
5193 // Reset the wide view port if it has been turned off by the waiting for Orbot message.
5194 if (!waitingForOrbot) {
5195 // Only use a wide view port if the URL starts with `http`, not for `file://` and `content://`.
5196 nestedScrollWebView.getSettings().setUseWideViewPort(url.startsWith("http"));
5199 // Flush any cookies to persistent storage. The cookie manager has become very lazy about flushing cookies in recent versions.
5200 if (nestedScrollWebView.getAcceptFirstPartyCookies() && Build.VERSION.SDK_INT >= 21) {
5201 CookieManager.getInstance().flush();
5204 // Update the Refresh menu item if the options menu has been created.
5205 if (optionsMenu != null) {
5206 // Get a handle for the refresh menu item.
5207 MenuItem refreshMenuItem = optionsMenu.findItem(R.id.refresh);
5209 // Reset the Refresh title.
5210 refreshMenuItem.setTitle(R.string.refresh);
5212 // Get the app bar and theme preferences.
5213 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
5214 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
5216 // If the icon is displayed in the AppBar, reset it according to the theme.
5217 if (displayAdditionalAppBarIcons) {
5219 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
5221 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
5226 // Clear the cache and history if Incognito Mode is enabled.
5227 if (incognitoModeEnabled) {
5228 // Clear the cache. `true` includes disk files.
5229 nestedScrollWebView.clearCache(true);
5231 // Clear the back/forward history.
5232 nestedScrollWebView.clearHistory();
5234 // Manually delete cache folders.
5236 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
5237 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
5238 String privateDataDirectoryString = getApplicationInfo().dataDir;
5240 // Delete the main cache directory.
5241 Runtime.getRuntime().exec("rm -rf " + privateDataDirectoryString + "/cache");
5243 // Delete the secondary `Service Worker` cache directory.
5244 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
5245 Runtime.getRuntime().exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
5246 } catch (IOException e) {
5247 // Do nothing if an error is thrown.
5251 // Update the URL text box and apply domain settings if not waiting on Orbot.
5252 if (!waitingForOrbot) {
5253 // Get the current page position.
5254 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5256 // Update the URL text bar if the page is currently selected.
5257 if (tabLayout.getSelectedTabPosition() == currentPagePosition) {
5258 // Check to see if the URL is `about:blank`.
5259 if (url.equals("about:blank")) { // The WebView is blank.
5260 // Display the hint in the URL edit text.
5261 urlEditText.setText("");
5263 // Request focus for the URL text box.
5264 urlEditText.requestFocus();
5266 // Display the keyboard.
5267 inputMethodManager.showSoftInput(urlEditText, 0);
5269 // Hide the WebView, which causes the default background color to be displayed according to the theme.
5270 nestedScrollWebView.setVisibility(View.INVISIBLE);
5272 // Apply the domain settings. This clears any settings from the previous domain.
5273 applyDomainSettings(nestedScrollWebView, "", true, false);
5274 } else { // The WebView has loaded a webpage.
5275 // Only update the URL text box if the user is not typing in it.
5276 if (!urlEditText.hasFocus()) {
5277 // Display the final URL. Getting the URL from the WebView instead of using the one provided by `onPageFinished()` makes websites like YouTube function correctly.
5278 urlEditText.setText(nestedScrollWebView.getUrl());
5280 // Apply text highlighting to the URL.
5286 // Check the current website information against any pinned domain information if the current IP addresses have been loaded.
5287 if ((nestedScrollWebView.hasPinnedSslCertificate() || nestedScrollWebView.hasPinnedIpAddresses()) && nestedScrollWebView.hasCurrentIpAddresses() &&
5288 !nestedScrollWebView.ignorePinnedDomainInformation()) {
5289 CheckPinnedMismatchHelper.checkPinnedMismatch(getSupportFragmentManager(), nestedScrollWebView);
5294 // Handle SSL Certificate errors.
5296 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
5297 // Get the current website SSL certificate.
5298 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
5300 // Extract the individual pieces of information from the current website SSL certificate.
5301 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
5302 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
5303 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
5304 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
5305 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
5306 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
5307 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
5308 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
5310 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
5311 if (nestedScrollWebView.hasPinnedSslCertificate()) {
5312 // Get the pinned SSL certificate.
5313 ArrayList<Object> pinnedSslCertificateArrayList = nestedScrollWebView.getPinnedSslCertificate();
5315 // Extract the arrays from the array list.
5316 String[] pinnedSslCertificateStringArray = (String[]) pinnedSslCertificateArrayList.get(0);
5317 Date[] pinnedSslCertificateDateArray = (Date[]) pinnedSslCertificateArrayList.get(1);
5319 // Check if the current SSL certificate matches the pinned certificate.
5320 if (currentWebsiteIssuedToCName.equals(pinnedSslCertificateStringArray[0]) && currentWebsiteIssuedToOName.equals(pinnedSslCertificateStringArray[1]) &&
5321 currentWebsiteIssuedToUName.equals(pinnedSslCertificateStringArray[2]) && currentWebsiteIssuedByCName.equals(pinnedSslCertificateStringArray[3]) &&
5322 currentWebsiteIssuedByOName.equals(pinnedSslCertificateStringArray[4]) && currentWebsiteIssuedByUName.equals(pinnedSslCertificateStringArray[5]) &&
5323 currentWebsiteSslStartDate.equals(pinnedSslCertificateDateArray[0]) && currentWebsiteSslEndDate.equals(pinnedSslCertificateDateArray[1])) {
5325 // An SSL certificate is pinned and matches the current domain certificate. Proceed to the website without displaying an error.
5328 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
5329 // Store the SSL error handler.
5330 nestedScrollWebView.setSslErrorHandler(handler);
5332 // Instantiate an SSL certificate error alert dialog.
5333 DialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error, nestedScrollWebView.getWebViewFragmentId());
5335 // Show the SSL certificate error dialog.
5336 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
5341 // Check to see if this is the first page.
5342 if (pageNumber == 0) {
5343 // Set this nested scroll WebView as the current WebView.
5344 currentWebView = nestedScrollWebView;
5346 // Apply the app settings from the shared preferences.
5349 // Load the website if not waiting for Orbot to connect.
5350 if (!waitingForOrbot) {
5351 // Get the intent that started the app.
5352 Intent launchingIntent = getIntent();
5354 // Get the information from the intent.
5355 String launchingIntentAction = launchingIntent.getAction();
5356 Uri launchingIntentUriData = launchingIntent.getData();
5358 // If the intent action is a web search, perform the search.
5359 if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) {
5360 // Create an encoded URL string.
5361 String encodedUrlString;
5363 // Sanitize the search input and convert it to a search.
5365 encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
5366 } catch (UnsupportedEncodingException exception) {
5367 encodedUrlString = "";
5370 // Load the completed search URL.
5371 loadUrl(searchURL + encodedUrlString);
5372 } else if (launchingIntentUriData != null){ // Check to see if the intent contains a new URL.
5373 // Load the URL from the intent.
5374 loadUrl(launchingIntentUriData.toString());
5375 } else { // The is no URL in the intent.
5376 // Select the homepage based on the proxy through Orbot status.
5377 if (proxyThroughOrbot) {
5378 // Load the Tor homepage.
5379 loadUrl(sharedPreferences.getString("tor_homepage", getString(R.string.tor_homepage_default_value)));
5381 // Load the normal homepage.
5382 loadUrl(sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));