2 * Copyright © 2015-2019 Soren Stoutner <soren@stoutner.com>.
4 * Download cookie code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
6 * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
8 * Privacy Browser is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
13 * Privacy Browser is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with Privacy Browser. If not, see <http://www.gnu.org/licenses/>.
22 package com.stoutner.privacybrowser.activities;
24 import android.Manifest;
25 import android.annotation.SuppressLint;
26 import android.app.Activity;
27 import android.app.DownloadManager;
28 import android.app.SearchManager;
29 import android.content.ActivityNotFoundException;
30 import android.content.BroadcastReceiver;
31 import android.content.ClipData;
32 import android.content.ClipboardManager;
33 import android.content.Context;
34 import android.content.Intent;
35 import android.content.IntentFilter;
36 import android.content.SharedPreferences;
37 import android.content.pm.PackageManager;
38 import android.content.res.Configuration;
39 import android.database.Cursor;
40 import android.graphics.Bitmap;
41 import android.graphics.BitmapFactory;
42 import android.graphics.Typeface;
43 import android.graphics.drawable.BitmapDrawable;
44 import android.graphics.drawable.Drawable;
45 import android.net.Uri;
46 import android.net.http.SslCertificate;
47 import android.net.http.SslError;
48 import android.os.Build;
49 import android.os.Bundle;
50 import android.os.Environment;
51 import android.os.Handler;
52 import android.preference.PreferenceManager;
53 import android.print.PrintDocumentAdapter;
54 import android.print.PrintManager;
55 import android.text.Editable;
56 import android.text.Spanned;
57 import android.text.TextWatcher;
58 import android.text.style.ForegroundColorSpan;
59 import android.util.Patterns;
60 import android.view.ContextMenu;
61 import android.view.GestureDetector;
62 import android.view.KeyEvent;
63 import android.view.Menu;
64 import android.view.MenuItem;
65 import android.view.MotionEvent;
66 import android.view.View;
67 import android.view.ViewGroup;
68 import android.view.WindowManager;
69 import android.view.inputmethod.InputMethodManager;
70 import android.webkit.CookieManager;
71 import android.webkit.HttpAuthHandler;
72 import android.webkit.SslErrorHandler;
73 import android.webkit.ValueCallback;
74 import android.webkit.WebChromeClient;
75 import android.webkit.WebResourceResponse;
76 import android.webkit.WebSettings;
77 import android.webkit.WebStorage;
78 import android.webkit.WebView;
79 import android.webkit.WebViewClient;
80 import android.webkit.WebViewDatabase;
81 import android.widget.ArrayAdapter;
82 import android.widget.CursorAdapter;
83 import android.widget.EditText;
84 import android.widget.FrameLayout;
85 import android.widget.ImageView;
86 import android.widget.LinearLayout;
87 import android.widget.ListView;
88 import android.widget.ProgressBar;
89 import android.widget.RadioButton;
90 import android.widget.RelativeLayout;
91 import android.widget.TextView;
93 import androidx.annotation.NonNull;
94 import androidx.appcompat.app.ActionBar;
95 import androidx.appcompat.app.ActionBarDrawerToggle;
96 import androidx.appcompat.app.AppCompatActivity;
97 import androidx.appcompat.widget.Toolbar;
98 import androidx.coordinatorlayout.widget.CoordinatorLayout;
99 import androidx.core.app.ActivityCompat;
100 import androidx.core.content.ContextCompat;
101 import androidx.core.view.GravityCompat;
102 import androidx.drawerlayout.widget.DrawerLayout;
103 import androidx.fragment.app.DialogFragment;
104 import androidx.fragment.app.FragmentManager;
105 import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
106 import androidx.viewpager.widget.ViewPager;
108 import com.google.android.material.appbar.AppBarLayout;
109 import com.google.android.material.floatingactionbutton.FloatingActionButton;
110 import com.google.android.material.navigation.NavigationView;
111 import com.google.android.material.snackbar.Snackbar;
112 import com.google.android.material.tabs.TabLayout;
114 import com.stoutner.privacybrowser.BuildConfig;
115 import com.stoutner.privacybrowser.R;
116 import com.stoutner.privacybrowser.adapters.WebViewPagerAdapter;
117 import com.stoutner.privacybrowser.asynctasks.GetHostIpAddresses;
118 import com.stoutner.privacybrowser.dialogs.AdConsentDialog;
119 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
120 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
121 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
122 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
123 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
124 import com.stoutner.privacybrowser.dialogs.DownloadLocationPermissionDialog;
125 import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
126 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
127 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
128 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
129 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
130 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
131 import com.stoutner.privacybrowser.fragments.WebViewTabFragment;
132 import com.stoutner.privacybrowser.helpers.AdHelper;
133 import com.stoutner.privacybrowser.helpers.BlockListHelper;
134 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
135 import com.stoutner.privacybrowser.helpers.CheckPinnedMismatchHelper;
136 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
137 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
138 import com.stoutner.privacybrowser.views.NestedScrollWebView;
140 import java.io.ByteArrayInputStream;
141 import java.io.ByteArrayOutputStream;
143 import java.io.IOException;
144 import java.io.UnsupportedEncodingException;
145 import java.net.MalformedURLException;
147 import java.net.URLDecoder;
148 import java.net.URLEncoder;
149 import java.util.ArrayList;
150 import java.util.Date;
151 import java.util.HashMap;
152 import java.util.HashSet;
153 import java.util.List;
154 import java.util.Map;
155 import java.util.Set;
157 // AppCompatActivity from android.support.v7.app.AppCompatActivity must be used to have access to the SupportActionBar until the minimum API is >= 21.
158 public class MainWebViewActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener,
159 DownloadFileDialog.DownloadFileListener, DownloadImageDialog.DownloadImageListener, DownloadLocationPermissionDialog.DownloadLocationPermissionDialogListener, EditBookmarkDialog.EditBookmarkListener,
160 EditBookmarkFolderDialog.EditBookmarkFolderListener, NavigationView.OnNavigationItemSelectedListener, WebViewTabFragment.NewTabListener {
162 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`, `onResume()`, and `applyProxyThroughOrbot()`.
163 public static String orbotStatus;
165 // The WebView pager adapter is accessed from `HttpAuthenticationDialog`, `PinnedMismatchDialog`, and `SslCertificateErrorDialog`. It is also used in `onCreate()`, `onResume()`, and `addTab()`.
166 public static WebViewPagerAdapter webViewPagerAdapter;
168 // The load URL on restart variables are public static so they can be accessed from `BookmarksActivity`. They are used in `onRestart()`.
169 public static boolean loadUrlOnRestart;
170 public static String urlToLoadOnRestart;
172 // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onRestart()`.
173 public static boolean restartFromBookmarksActivity;
175 // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`,
176 // `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
177 public static String currentBookmarksFolder;
179 // The user agent constants are public static so they can be accessed from `SettingsFragment`, `DomainsActivity`, and `DomainSettingsFragment`.
180 public final static int UNRECOGNIZED_USER_AGENT = -1;
181 public final static int SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1;
182 public final static int SETTINGS_CUSTOM_USER_AGENT = 12;
183 public final static int DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0;
184 public final static int DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2;
185 public final static int DOMAINS_CUSTOM_USER_AGENT = 13;
189 // The current WebView is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
190 // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, `applyProxyThroughOrbot()`, and `applyDomainSettings()`.
191 private NestedScrollWebView currentWebView;
193 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
194 private final Map<String, String> customHeaders = new HashMap<>();
196 // The search URL is set in `applyProxyThroughOrbot()` and used in `onCreate()`, `onNewIntent()`, `loadURLFromTextBox()`, and `initializeWebView()`.
197 private String searchURL;
199 // The options menu is set in `onCreateOptionsMenu()` and used in `onOptionsItemSelected()`, `updatePrivacyIcons()`, and `initializeWebView()`.
200 private Menu optionsMenu;
202 // The blocklists are populated in `onCreate()` and accessed from `initializeWebView()`.
203 private ArrayList<List<String[]>> easyList;
204 private ArrayList<List<String[]>> easyPrivacy;
205 private ArrayList<List<String[]>> fanboysAnnoyanceList;
206 private ArrayList<List<String[]>> fanboysSocialList;
207 private ArrayList<List<String[]>> ultraPrivacy;
209 // `webViewDefaultUserAgent` is used in `onCreate()` and `onPrepareOptionsMenu()`.
210 private String webViewDefaultUserAgent;
212 // `proxyThroughOrbot` is used in `onRestart()`, `onOptionsItemSelected()`, `applyAppSettings()`, and `applyProxyThroughOrbot()`.
213 private boolean proxyThroughOrbot;
215 // The incognito mode is set in `applyAppSettings()` and used in `initializeWebView()`.
216 private boolean incognitoModeEnabled;
218 // The full screen browsing mode tracker is set it `applyAppSettings()` and used in `initializeWebView()`.
219 private boolean fullScreenBrowsingModeEnabled;
221 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
222 private boolean inFullScreenBrowsingMode;
224 // The app bar trackers are set in `applyAppSettings()` and used in `initializeWebView()`.
225 private boolean hideAppBar;
226 private boolean scrollAppBar;
228 // The loading new intent tracker is set in `onNewIntent()` and used in `setCurrentWebView()`.
229 private boolean loadingNewIntent;
231 // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
232 private boolean reapplyDomainSettingsOnRestart;
234 // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
235 private boolean reapplyAppSettingsOnRestart;
237 // `displayingFullScreenVideo` is used in `onCreate()` and `onResume()`.
238 private boolean displayingFullScreenVideo;
240 // `orbotStatusBroadcastReceiver` is used in `onCreate()` and `onDestroy()`.
241 private BroadcastReceiver orbotStatusBroadcastReceiver;
243 // `waitingForOrbot` is used in `onCreate()`, `onResume()`, and `applyProxyThroughOrbot()`.
244 private boolean waitingForOrbot;
246 // The action bar drawer toggle is initialized in `onCreate()` and used in `onResume()`.
247 private ActionBarDrawerToggle actionBarDrawerToggle;
249 // The color spans are used in `onCreate()` and `highlightUrlText()`.
250 private ForegroundColorSpan redColorSpan;
251 private ForegroundColorSpan initialGrayColorSpan;
252 private ForegroundColorSpan finalGrayColorSpan;
254 // The drawer header padding variables are used in `onCreate()` and `onConfigurationChanged()`.
255 private int drawerHeaderPaddingLeftAndRight;
256 private int drawerHeaderPaddingTop;
257 private int drawerHeaderPaddingBottom;
259 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onDestroy`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`,
260 // and `loadBookmarksFolder()`.
261 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
263 // `bookmarksCursor` is used in `onDestroy()`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
264 private Cursor bookmarksCursor;
266 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
267 private CursorAdapter bookmarksCursorAdapter;
269 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
270 private String oldFolderNameString;
272 // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
273 private ValueCallback<Uri[]> fileChooserCallback;
275 // The default progress view offsets are set in `onCreate()` and used in `initializeWebView()`.
276 private int defaultProgressViewStartOffset;
277 private int defaultProgressViewEndOffset;
279 // The swipe refresh layout top padding is used when exiting full screen browsing mode. It is used in an inner class in `initializeWebView()`.
280 private int swipeRefreshLayoutPaddingTop;
282 // The URL sanitizers are set in `applyAppSettings()` and used in `sanitizeUrl()`.
283 private boolean sanitizeGoogleAnalytics;
285 // The download strings are used in `onCreate()`, `onRequestPermissionResult()` and `initializeWebView()`.
286 private String downloadUrl;
287 private String downloadContentDisposition;
288 private long downloadContentLength;
290 // `downloadImageUrl` is used in `onCreateContextMenu()` and `onRequestPermissionResult()`.
291 private String downloadImageUrl;
293 // The request codes are used in `onCreate()`, `onCreateContextMenu()`, `onCloseDownloadLocationPermissionDialog()`, `onRequestPermissionResult()`, and `initializeWebView()`.
294 private final int DOWNLOAD_FILE_REQUEST_CODE = 1;
295 private final int DOWNLOAD_IMAGE_REQUEST_CODE = 2;
298 // Remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
299 @SuppressLint("ClickableViewAccessibility")
300 protected void onCreate(Bundle savedInstanceState) {
301 // Get a handle for the shared preferences.
302 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
304 // Get the theme and screenshot preferences.
305 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
306 boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
308 // Disable screenshots if not allowed.
309 if (!allowScreenshots) {
310 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
313 // Set the activity theme.
315 setTheme(R.style.PrivacyBrowserDark);
317 setTheme(R.style.PrivacyBrowserLight);
320 // Run the default commands.
321 super.onCreate(savedInstanceState);
323 // Set the content view.
324 setContentView(R.layout.main_framelayout);
326 // Get a handle for the input method.
327 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
329 // Remove the lint warning below that the input method manager might be null.
330 assert inputMethodManager != null;
332 // Get a handle for the toolbar.
333 Toolbar toolbar = findViewById(R.id.toolbar);
335 // Set the action bar. `SupportActionBar` must be used until the minimum API is >= 21.
336 setSupportActionBar(toolbar);
338 // Get a handle for the action bar.
339 ActionBar actionBar = getSupportActionBar();
341 // This is needed to get rid of the Android Studio warning that the action bar might be null.
342 assert actionBar != null;
344 // Add the custom layout, which shows the URL text bar.
345 actionBar.setCustomView(R.layout.url_app_bar);
346 actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
348 // Initialize the foreground color spans for highlighting the URLs. We have to use the deprecated `getColor()` until API >= 23.
349 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
350 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
351 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
353 // Get handles for the URL views.
354 EditText urlEditText = findViewById(R.id.url_edittext);
356 // Remove the formatting from `urlTextBar` when the user is editing the text.
357 urlEditText.setOnFocusChangeListener((View v, boolean hasFocus) -> {
358 if (hasFocus) { // The user is editing the URL text box.
359 // Remove the highlighting.
360 urlEditText.getText().removeSpan(redColorSpan);
361 urlEditText.getText().removeSpan(initialGrayColorSpan);
362 urlEditText.getText().removeSpan(finalGrayColorSpan);
363 } else { // The user has stopped editing the URL text box.
364 // Move to the beginning of the string.
365 urlEditText.setSelection(0);
367 // Reapply the highlighting.
372 // Set the go button on the keyboard to load the URL in `urlTextBox`.
373 urlEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
374 // If the event is a key-down event on the `enter` button, load the URL.
375 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
376 // Load the URL into the mainWebView and consume the event.
377 loadUrlFromTextBox();
379 // If the enter key was pressed, consume the event.
382 // If any other key was pressed, do not consume the event.
387 // Initialize the Orbot status and the waiting for Orbot trackers.
388 orbotStatus = "unknown";
389 waitingForOrbot = false;
391 // Create an Orbot status `BroadcastReceiver`.
392 orbotStatusBroadcastReceiver = new BroadcastReceiver() {
394 public void onReceive(Context context, Intent intent) {
395 // Store the content of the status message in `orbotStatus`.
396 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
398 // If Privacy Browser is waiting on Orbot, load the website now that Orbot is connected.
399 if (orbotStatus.equals("ON") && waitingForOrbot) {
400 // Reset the waiting for Orbot status.
401 waitingForOrbot = false;
403 // Get the intent that started the app.
404 Intent launchingIntent = getIntent();
406 // Get the information from the intent.
407 String launchingIntentAction = launchingIntent.getAction();
408 Uri launchingIntentUriData = launchingIntent.getData();
410 // If the intent action is a web search, perform the search.
411 if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) {
412 // Create an encoded URL string.
413 String encodedUrlString;
415 // Sanitize the search input and convert it to a search.
417 encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
418 } catch (UnsupportedEncodingException exception) {
419 encodedUrlString = "";
422 // Load the completed search URL.
423 loadUrl(searchURL + encodedUrlString);
424 } else if (launchingIntentUriData != null){ // Check to see if the intent contains a new URL.
425 // Load the URL from the intent.
426 loadUrl(launchingIntentUriData.toString());
427 } else { // The is no URL in the intent.
428 // Select the homepage based on the proxy through Orbot status.
429 if (proxyThroughOrbot) {
430 // Load the Tor homepage.
431 loadUrl(sharedPreferences.getString("tor_homepage", getString(R.string.tor_homepage_default_value)));
433 // Load the normal homepage.
434 loadUrl(sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
441 // Register `orbotStatusBroadcastReceiver` on `this` context.
442 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
444 // Instantiate the blocklist helper.
445 BlockListHelper blockListHelper = new BlockListHelper();
447 // Parse the block lists.
448 easyList = blockListHelper.parseBlockList(getAssets(), "blocklists/easylist.txt");
449 easyPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/easyprivacy.txt");
450 fanboysAnnoyanceList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-annoyance.txt");
451 fanboysSocialList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-social.txt");
452 ultraPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/ultraprivacy.txt");
454 // Get handles for views that need to be modified.
455 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
456 NavigationView navigationView = findViewById(R.id.navigationview);
457 TabLayout tabLayout = findViewById(R.id.tablayout);
458 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
459 ViewPager webViewPager = findViewById(R.id.webviewpager);
460 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
461 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
462 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
463 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
464 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
466 // Listen for touches on the navigation menu.
467 navigationView.setNavigationItemSelectedListener(this);
469 // Get handles for the navigation menu and the back and forward menu items. The menu is zero-based.
470 Menu navigationMenu = navigationView.getMenu();
471 MenuItem navigationBackMenuItem = navigationMenu.getItem(2);
472 MenuItem navigationForwardMenuItem = navigationMenu.getItem(3);
473 MenuItem navigationHistoryMenuItem = navigationMenu.getItem(4);
474 MenuItem navigationRequestsMenuItem = navigationMenu.getItem(5);
476 // Initialize the web view pager adapter.
477 webViewPagerAdapter = new WebViewPagerAdapter(getSupportFragmentManager());
479 // Set the pager adapter on the web view pager.
480 webViewPager.setAdapter(webViewPagerAdapter);
482 // Store up to 100 tabs in memory.
483 webViewPager.setOffscreenPageLimit(100);
485 // Update the web view pager every time a tab is modified.
486 webViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
488 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
493 public void onPageSelected(int position) {
494 // Close the find on page bar if it is open.
495 closeFindOnPage(null);
497 // Set the current WebView.
498 setCurrentWebView(position);
500 // 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.
501 if (tabLayout.getSelectedTabPosition() != position) {
502 // Create a handler to select the tab.
503 Handler selectTabHandler = new Handler();
505 // Create a runnable select the new tab.
506 Runnable selectTabRunnable = () -> {
507 // Get a handle for the tab.
508 TabLayout.Tab tab = tabLayout.getTabAt(position);
510 // Assert that the tab is not null.
517 // Select the tab layout after 100 milliseconds, which leaves enough time for a new tab to be created.
518 selectTabHandler.postDelayed(selectTabRunnable, 100);
523 public void onPageScrollStateChanged(int state) {
528 // Display the View SSL Certificate dialog when the currently selected tab is reselected.
529 tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
531 public void onTabSelected(TabLayout.Tab tab) {
532 // Select the same page in the view pager.
533 webViewPager.setCurrentItem(tab.getPosition());
537 public void onTabUnselected(TabLayout.Tab tab) {
542 public void onTabReselected(TabLayout.Tab tab) {
543 // Instantiate the View SSL Certificate dialog.
544 DialogFragment viewSslCertificateDialogFragment = ViewSslCertificateDialog.displayDialog(currentWebView.getWebViewFragmentId());
546 // Display the View SSL Certificate dialog.
547 viewSslCertificateDialogFragment.show(getSupportFragmentManager(), getString(R.string.view_ssl_certificate));
551 // Add the first tab.
554 // 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.
555 // The deprecated `getResources().getDrawable()` must be used until the minimum API >= 21 and and `getResources().getColor()` must be used until the minimum API >= 23.
557 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
558 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
559 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
560 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
562 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
563 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
564 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
565 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
568 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
569 launchBookmarksActivityFab.setOnClickListener(v -> {
570 // Get a copy of the favorite icon bitmap.
571 Bitmap favoriteIconBitmap = currentWebView.getFavoriteOrDefaultIcon();
573 // Create a favorite icon byte array output stream.
574 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
576 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
577 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
579 // Convert the favorite icon byte array stream to a byte array.
580 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
582 // Create an intent to launch the bookmarks activity.
583 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
585 // Add the extra information to the intent.
586 bookmarksIntent.putExtra("current_url", currentWebView.getUrl());
587 bookmarksIntent.putExtra("current_title", currentWebView.getTitle());
588 bookmarksIntent.putExtra("current_folder", currentBookmarksFolder);
589 bookmarksIntent.putExtra("favorite_icon_byte_array", favoriteIconByteArray);
592 startActivity(bookmarksIntent);
595 // Set the create new bookmark folder FAB to display an alert dialog.
596 createBookmarkFolderFab.setOnClickListener(v -> {
597 // Create a create bookmark folder dialog.
598 DialogFragment createBookmarkFolderDialog = CreateBookmarkFolderDialog.createBookmarkFolder(currentWebView.getFavoriteOrDefaultIcon());
600 // Show the create bookmark folder dialog.
601 createBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.create_folder));
604 // Set the create new bookmark FAB to display an alert dialog.
605 createBookmarkFab.setOnClickListener(view -> {
606 // Instantiate the create bookmark dialog.
607 DialogFragment createBookmarkDialog = CreateBookmarkDialog.createBookmark(currentWebView.getUrl(), currentWebView.getTitle(), currentWebView.getFavoriteOrDefaultIcon());
609 // Display the create bookmark dialog.
610 createBookmarkDialog.show(getSupportFragmentManager(), getString(R.string.create_bookmark));
613 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
614 findOnPageEditText.addTextChangedListener(new TextWatcher() {
616 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
621 public void onTextChanged(CharSequence s, int start, int before, int count) {
626 public void afterTextChanged(Editable s) {
627 // 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.
628 if (currentWebView != null) {
629 currentWebView.findAllAsync(findOnPageEditText.getText().toString());
634 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
635 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
636 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
637 // Hide the soft keyboard.
638 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
640 // Consume the event.
642 } else { // A different key was pressed.
643 // Do not consume the event.
648 // Implement swipe to refresh.
649 swipeRefreshLayout.setOnRefreshListener(() -> currentWebView.reload());
651 // Store the default progress view offsets for use later in `initializeWebView()`.
652 defaultProgressViewStartOffset = swipeRefreshLayout.getProgressViewStartOffset();
653 defaultProgressViewEndOffset = swipeRefreshLayout.getProgressViewEndOffset();
655 // Set the swipe to refresh color according to the theme.
657 swipeRefreshLayout.setColorSchemeResources(R.color.blue_800);
658 swipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.gray_850);
660 swipeRefreshLayout.setColorSchemeResources(R.color.blue_500);
663 // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
664 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
665 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
667 // Initialize the bookmarks database helper. The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
668 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
670 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
671 currentBookmarksFolder = "";
673 // Load the home folder, which is `""` in the database.
674 loadBookmarksFolder();
676 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
677 // Convert the id from long to int to match the format of the bookmarks database.
678 int databaseID = (int) id;
680 // Get the bookmark cursor for this ID and move it to the first row.
681 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseID);
682 bookmarkCursor.moveToFirst();
684 // Act upon the bookmark according to the type.
685 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
686 // Store the new folder name in `currentBookmarksFolder`.
687 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
689 // Load the new folder.
690 loadBookmarksFolder();
691 } else { // The selected bookmark is not a folder.
692 // Load the bookmark URL.
693 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
695 // Close the bookmarks drawer.
696 drawerLayout.closeDrawer(GravityCompat.END);
699 // Close the `Cursor`.
700 bookmarkCursor.close();
703 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
704 // Convert the database ID from `long` to `int`.
705 int databaseId = (int) id;
707 // Find out if the selected bookmark is a folder.
708 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
711 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
712 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
714 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
715 DialogFragment editBookmarkFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId, currentWebView.getFavoriteOrDefaultIcon());
716 editBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.edit_folder));
718 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
719 DialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId, currentWebView.getFavoriteOrDefaultIcon());
720 editBookmarkDialog.show(getSupportFragmentManager(), getString(R.string.edit_bookmark));
723 // Consume the event.
727 // Get the status bar pixel size.
728 int statusBarResourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
729 int statusBarPixelSize = getResources().getDimensionPixelSize(statusBarResourceId);
731 // Get the resource density.
732 float screenDensity = getResources().getDisplayMetrics().density;
734 // Calculate the drawer header padding. This is used to move the text in the drawer headers below any cutouts.
735 drawerHeaderPaddingLeftAndRight = (int) (15 * screenDensity);
736 drawerHeaderPaddingTop = statusBarPixelSize + (int) (4 * screenDensity);
737 drawerHeaderPaddingBottom = (int) (8 * screenDensity);
739 // The drawer listener is used to update the navigation menu.`
740 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
742 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
746 public void onDrawerOpened(@NonNull View drawerView) {
750 public void onDrawerClosed(@NonNull View drawerView) {
754 public void onDrawerStateChanged(int newState) {
755 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // A drawer is opening or closing.
756 // Get handles for the drawer headers.
757 TextView navigationHeaderTextView = findViewById(R.id.navigationText);
758 TextView bookmarksHeaderTextView = findViewById(R.id.bookmarks_title_textview);
760 // 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.
761 if (navigationHeaderTextView != null) {
762 navigationHeaderTextView.setPadding(drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingTop, drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingBottom);
765 // 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.
766 if (bookmarksHeaderTextView != null) {
767 bookmarksHeaderTextView.setPadding(drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingTop, drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingBottom);
770 // Update the navigation menu items.
771 navigationBackMenuItem.setEnabled(currentWebView.canGoBack());
772 navigationForwardMenuItem.setEnabled(currentWebView.canGoForward());
773 navigationHistoryMenuItem.setEnabled((currentWebView.canGoBack() || currentWebView.canGoForward()));
774 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
776 // Hide the keyboard (if displayed).
777 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
779 // 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.
780 urlEditText.clearFocus();
781 currentWebView.clearFocus();
786 // Create the hamburger icon at the start of the AppBar.
787 actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
789 // 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).
790 customHeaders.put("X-Requested-With", "");
792 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
793 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
795 // Inflate a bare WebView to get the default user agent. It is not used to render content on the screen.
796 @SuppressLint("InflateParams") View webViewLayout = getLayoutInflater().inflate(R.layout.bare_webview, null, false);
798 // Get a handle for the WebView.
799 WebView bareWebView = webViewLayout.findViewById(R.id.bare_webview);
801 // Store the default user agent.
802 webViewDefaultUserAgent = bareWebView.getSettings().getUserAgentString();
804 // Destroy the bare WebView.
805 bareWebView.destroy();
809 protected void onNewIntent(Intent intent) {
810 // Get the information from the intent.
811 String intentAction = intent.getAction();
812 Uri intentUriData = intent.getData();
814 // Determine if this is a web search.
815 boolean isWebSearch = ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH));
817 // Only process the URI if it contains data or it is a web search. If the user pressed the desktop icon after the app was already running the URI will be null.
818 if (intentUriData != null || isWebSearch) {
819 // Get the shared preferences.
820 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
822 // Create a URL string.
825 // If the intent action is a web search, perform the search.
827 // Create an encoded URL string.
828 String encodedUrlString;
830 // Sanitize the search input and convert it to a search.
832 encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
833 } catch (UnsupportedEncodingException exception) {
834 encodedUrlString = "";
837 // Add the base search URL.
838 url = searchURL + encodedUrlString;
839 } else { // The intent should contain a URL.
840 // Set the intent data as the URL.
841 url = intentUriData.toString();
844 // Add a new tab if specified in the preferences.
845 if (sharedPreferences.getBoolean("open_intents_in_new_tab", true)) { // Load the URL in a new tab.
846 // Set the loading new intent flag.
847 loadingNewIntent = true;
851 } else { // Load the URL in the current tab.
856 // Get a handle for the drawer layout.
857 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
859 // Close the navigation drawer if it is open.
860 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
861 drawerLayout.closeDrawer(GravityCompat.START);
864 // Close the bookmarks drawer if it is open.
865 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
866 drawerLayout.closeDrawer(GravityCompat.END);
872 public void onRestart() {
873 // Run the default commands.
876 // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
877 if (proxyThroughOrbot) {
878 // Request Orbot to start. If Orbot is already running no hard will be caused by this request.
879 Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
881 // Send the intent to the Orbot package.
882 orbotIntent.setPackage("org.torproject.android");
885 sendBroadcast(orbotIntent);
888 // Apply the app settings if returning from the Settings activity.
889 if (reapplyAppSettingsOnRestart) {
890 // Reset the reapply app settings on restart tracker.
891 reapplyAppSettingsOnRestart = false;
893 // Apply the app settings.
897 // Apply the domain settings if returning from the settings or domains activity.
898 if (reapplyDomainSettingsOnRestart) {
899 // Reset the reapply domain settings on restart tracker.
900 reapplyDomainSettingsOnRestart = false;
902 // Reapply the domain settings for each tab.
903 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
904 // Get the WebView tab fragment.
905 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
907 // Get the fragment view.
908 View fragmentView = webViewTabFragment.getView();
910 // Only reload the WebViews if they exist.
911 if (fragmentView != null) {
912 // Get the nested scroll WebView from the tab fragment.
913 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
915 // Reset the current domain name so the domain settings will be reapplied.
916 nestedScrollWebView.resetCurrentDomainName();
918 // Reapply the domain settings if the URL is not null, which can happen if an empty tab is active when returning from settings.
919 if (nestedScrollWebView.getUrl() != null) {
920 applyDomainSettings(nestedScrollWebView, nestedScrollWebView.getUrl(), false, true);
926 // Load the URL on restart (used when loading a bookmark).
927 if (loadUrlOnRestart) {
928 // Load the specified URL.
929 loadUrl(urlToLoadOnRestart);
931 // Reset the load on restart tracker.
932 loadUrlOnRestart = false;
935 // Update the bookmarks drawer if returning from the Bookmarks activity.
936 if (restartFromBookmarksActivity) {
937 // Get a handle for the drawer layout.
938 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
940 // Close the bookmarks drawer.
941 drawerLayout.closeDrawer(GravityCompat.END);
943 // Reload the bookmarks drawer.
944 loadBookmarksFolder();
946 // Reset `restartFromBookmarksActivity`.
947 restartFromBookmarksActivity = false;
950 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
951 updatePrivacyIcons(true);
954 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
956 public void onResume() {
957 // Run the default commands.
960 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
961 // Get the WebView tab fragment.
962 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
964 // Get the fragment view.
965 View fragmentView = webViewTabFragment.getView();
967 // Only resume the WebViews if they exist (they won't when the app is first created).
968 if (fragmentView != null) {
969 // Get the nested scroll WebView from the tab fragment.
970 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
972 // Resume the nested scroll WebView JavaScript timers.
973 nestedScrollWebView.resumeTimers();
975 // Resume the nested scroll WebView.
976 nestedScrollWebView.onResume();
980 // Display a message to the user if waiting for Orbot.
981 if (waitingForOrbot && !orbotStatus.equals("ON")) {
982 // Disable the wide view port so that the waiting for Orbot text is displayed correctly.
983 currentWebView.getSettings().setUseWideViewPort(false);
985 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
986 currentWebView.loadData("<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>", "text/html", null);
989 if (displayingFullScreenVideo || inFullScreenBrowsingMode) {
990 // Get a handle for the root frame layouts.
991 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
993 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
994 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
996 /* Hide the system bars.
997 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
998 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
999 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1000 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1002 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
1003 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1004 } else if (BuildConfig.FLAVOR.contentEquals("free")) { // Resume the adView for the free flavor.
1006 AdHelper.resumeAd(findViewById(R.id.adview));
1011 public void onPause() {
1012 // Run the default commands.
1015 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
1016 // Get the WebView tab fragment.
1017 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
1019 // Get the fragment view.
1020 View fragmentView = webViewTabFragment.getView();
1022 // Only pause the WebViews if they exist (they won't when the app is first created).
1023 if (fragmentView != null) {
1024 // Get the nested scroll WebView from the tab fragment.
1025 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
1027 // Pause the nested scroll WebView.
1028 nestedScrollWebView.onPause();
1030 // Pause the nested scroll WebView JavaScript timers.
1031 nestedScrollWebView.pauseTimers();
1035 // Pause the ad or it will continue to consume resources in the background on the free flavor.
1036 if (BuildConfig.FLAVOR.contentEquals("free")) {
1038 AdHelper.pauseAd(findViewById(R.id.adview));
1043 public void onDestroy() {
1044 // Unregister the Orbot status broadcast receiver.
1045 this.unregisterReceiver(orbotStatusBroadcastReceiver);
1047 // Close the bookmarks cursor and database.
1048 bookmarksCursor.close();
1049 bookmarksDatabaseHelper.close();
1051 // Run the default commands.
1056 public boolean onCreateOptionsMenu(Menu menu) {
1057 // Inflate the menu. This adds items to the action bar if it is present.
1058 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1060 // Store a handle for the options menu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons()`.
1063 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1064 updatePrivacyIcons(false);
1066 // Get handles for the menu items.
1067 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1068 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1069 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1070 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
1071 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
1072 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1073 MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
1075 // Only display third-party cookies if API >= 21
1076 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1078 // Only display the form data menu items if the API < 26.
1079 toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1080 clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1082 // Disable the clear form data menu item if the API >= 26 so that the status of the main Clear Data is calculated correctly.
1083 clearFormDataMenuItem.setEnabled(Build.VERSION.SDK_INT < 26);
1085 // Only show Ad Consent if this is the free flavor.
1086 adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
1088 // Get the shared preferences.
1089 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1091 // Get the dark theme and app bar preferences..
1092 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
1093 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
1095 // 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.
1096 if (displayAdditionalAppBarIcons) {
1097 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1098 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1099 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
1100 } else { //Do not display the additional icons.
1101 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1102 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1103 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1106 // Replace Refresh with Stop if a URL is already loading.
1107 if (currentWebView != null && currentWebView.getProgress() != 100) {
1109 refreshMenuItem.setTitle(R.string.stop);
1111 // If the icon is displayed in the AppBar, set it according to the theme.
1112 if (displayAdditionalAppBarIcons) {
1114 refreshMenuItem.setIcon(R.drawable.close_dark);
1116 refreshMenuItem.setIcon(R.drawable.close_light);
1125 public boolean onPrepareOptionsMenu(Menu menu) {
1126 // Get handles for the menu items.
1127 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
1128 MenuItem firstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1129 MenuItem thirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1130 MenuItem domStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1131 MenuItem saveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
1132 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
1133 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1134 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1135 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
1136 MenuItem blocklistsMenuItem = menu.findItem(R.id.blocklists);
1137 MenuItem easyListMenuItem = menu.findItem(R.id.easylist);
1138 MenuItem easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
1139 MenuItem fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
1140 MenuItem fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
1141 MenuItem ultraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
1142 MenuItem blockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
1143 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1144 MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
1145 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1146 MenuItem nightModeMenuItem = menu.findItem(R.id.night_mode);
1147 MenuItem proxyThroughOrbotMenuItem = menu.findItem(R.id.proxy_through_orbot);
1149 // Get a handle for the cookie manager.
1150 CookieManager cookieManager = CookieManager.getInstance();
1152 // Initialize the current user agent string and the font size.
1153 String currentUserAgent = getString(R.string.user_agent_privacy_browser);
1156 // 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.
1157 if (currentWebView != null) {
1158 // Set the add or edit domain text.
1159 if (currentWebView.getDomainSettingsApplied()) {
1160 addOrEditDomain.setTitle(R.string.edit_domain_settings);
1162 addOrEditDomain.setTitle(R.string.add_domain_settings);
1165 // Get the current user agent from the WebView.
1166 currentUserAgent = currentWebView.getSettings().getUserAgentString();
1168 // Get the current font size from the
1169 fontSize = currentWebView.getSettings().getTextZoom();
1171 // Set the status of the menu item checkboxes.
1172 domStorageMenuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1173 saveFormDataMenuItem.setChecked(currentWebView.getSettings().getSaveFormData()); // Form data can be removed once the minimum API >= 26.
1174 easyListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST));
1175 easyPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY));
1176 fanboysAnnoyanceListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1177 fanboysSocialBlockingListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1178 ultraPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY));
1179 blockAllThirdPartyRequestsMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1180 swipeToRefreshMenuItem.setChecked(currentWebView.getSwipeToRefresh());
1181 displayImagesMenuItem.setChecked(currentWebView.getSettings().getLoadsImagesAutomatically());
1182 nightModeMenuItem.setChecked(currentWebView.getNightMode());
1184 // Initialize the display names for the blocklists with the number of blocked requests.
1185 blocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
1186 easyListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASY_LIST) + " - " + getString(R.string.easylist));
1187 easyPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASY_PRIVACY) + " - " + getString(R.string.easyprivacy));
1188 fanboysAnnoyanceListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " + getString(R.string.fanboys_annoyance_list));
1189 fanboysSocialBlockingListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " + getString(R.string.fanboys_social_blocking_list));
1190 ultraPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRA_PRIVACY) + " - " + getString(R.string.ultraprivacy));
1191 blockAllThirdPartyRequestsMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " + getString(R.string.block_all_third_party_requests));
1193 // Only modify third-party cookies if the API >= 21.
1194 if (Build.VERSION.SDK_INT >= 21) {
1195 // Set the status of the third-party cookies checkbox.
1196 thirdPartyCookiesMenuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
1198 // Enable third-party cookies if first-party cookies are enabled.
1199 thirdPartyCookiesMenuItem.setEnabled(cookieManager.acceptCookie());
1202 // Enable DOM Storage if JavaScript is enabled.
1203 domStorageMenuItem.setEnabled(currentWebView.getSettings().getJavaScriptEnabled());
1206 // Set the status of the menu item checkboxes.
1207 firstPartyCookiesMenuItem.setChecked(cookieManager.acceptCookie());
1208 proxyThroughOrbotMenuItem.setChecked(proxyThroughOrbot);
1210 // Enable Clear Cookies if there are any.
1211 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1213 // 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`.
1214 String privateDataDirectoryString = getApplicationInfo().dataDir;
1216 // Get a count of the number of files in the Local Storage directory.
1217 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1218 int localStorageDirectoryNumberOfFiles = 0;
1219 if (localStorageDirectory.exists()) {
1220 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1223 // Get a count of the number of files in the IndexedDB directory.
1224 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1225 int indexedDBDirectoryNumberOfFiles = 0;
1226 if (indexedDBDirectory.exists()) {
1227 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1230 // Enable Clear DOM Storage if there is any.
1231 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1233 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
1234 if (Build.VERSION.SDK_INT < 26) {
1235 // Get the WebView database.
1236 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1238 // Enable the clear form data menu item if there is anything to clear.
1239 clearFormDataMenuItem.setEnabled(webViewDatabase.hasFormData());
1242 // Enable Clear Data if any of the submenu items are enabled.
1243 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
1245 // Disable Fanboy's Social Blocking List menu item if Fanboy's Annoyance List is checked.
1246 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListMenuItem.isChecked());
1248 // Select the current user agent menu item. A switch statement cannot be used because the user agents are not compile time constants.
1249 if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) { // Privacy Browser.
1250 menu.findItem(R.id.user_agent_privacy_browser).setChecked(true);
1251 } else if (currentUserAgent.equals(webViewDefaultUserAgent)) { // WebView Default.
1252 menu.findItem(R.id.user_agent_webview_default).setChecked(true);
1253 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) { // Firefox on Android.
1254 menu.findItem(R.id.user_agent_firefox_on_android).setChecked(true);
1255 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) { // Chrome on Android.
1256 menu.findItem(R.id.user_agent_chrome_on_android).setChecked(true);
1257 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) { // Safari on iOS.
1258 menu.findItem(R.id.user_agent_safari_on_ios).setChecked(true);
1259 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) { // Firefox on Linux.
1260 menu.findItem(R.id.user_agent_firefox_on_linux).setChecked(true);
1261 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) { // Chromium on Linux.
1262 menu.findItem(R.id.user_agent_chromium_on_linux).setChecked(true);
1263 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) { // Firefox on Windows.
1264 menu.findItem(R.id.user_agent_firefox_on_windows).setChecked(true);
1265 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) { // Chrome on Windows.
1266 menu.findItem(R.id.user_agent_chrome_on_windows).setChecked(true);
1267 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) { // Edge on Windows.
1268 menu.findItem(R.id.user_agent_edge_on_windows).setChecked(true);
1269 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) { // Internet Explorer on Windows.
1270 menu.findItem(R.id.user_agent_internet_explorer_on_windows).setChecked(true);
1271 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) { // Safari on macOS.
1272 menu.findItem(R.id.user_agent_safari_on_macos).setChecked(true);
1273 } else { // Custom user agent.
1274 menu.findItem(R.id.user_agent_custom).setChecked(true);
1277 // Instantiate the font size title and the selected font size menu item.
1278 String fontSizeTitle;
1279 MenuItem selectedFontSizeMenuItem;
1281 // Prepare the font size title and current size menu item.
1284 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
1285 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1289 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
1290 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1294 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
1295 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1299 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1300 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1304 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
1305 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1309 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
1310 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1314 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
1315 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1319 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
1320 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1324 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1325 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1329 // Set the font size title and select the current size menu item.
1330 fontSizeMenuItem.setTitle(fontSizeTitle);
1331 selectedFontSizeMenuItem.setChecked(true);
1333 // Run all the other default commands.
1334 super.onPrepareOptionsMenu(menu);
1336 // Display the menu.
1341 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1342 @SuppressLint("SetJavaScriptEnabled")
1343 public boolean onOptionsItemSelected(MenuItem menuItem) {
1344 // Reenter full screen browsing mode if it was interrupted by the options menu. <https://redmine.stoutner.com/issues/389>
1345 if (inFullScreenBrowsingMode) {
1346 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
1347 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1349 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
1351 /* Hide the system bars.
1352 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1353 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
1354 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1355 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1357 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
1358 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1361 // Get the selected menu item ID.
1362 int menuItemId = menuItem.getItemId();
1364 // Get a handle for the shared preferences.
1365 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1367 // Get a handle for the cookie manager.
1368 CookieManager cookieManager = CookieManager.getInstance();
1370 // Run the commands that correlate to the selected menu item.
1371 switch (menuItemId) {
1372 case R.id.toggle_javascript:
1373 // Toggle the JavaScript status.
1374 currentWebView.getSettings().setJavaScriptEnabled(!currentWebView.getSettings().getJavaScriptEnabled());
1376 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1377 updatePrivacyIcons(true);
1379 // Display a `Snackbar`.
1380 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScrip is enabled.
1381 Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1382 } else if (cookieManager.acceptCookie()) { // JavaScript is disabled, but first-party cookies are enabled.
1383 Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1384 } else { // Privacy mode.
1385 Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1388 // Reload the current WebView.
1389 currentWebView.reload();
1392 case R.id.add_or_edit_domain:
1393 if (currentWebView.getDomainSettingsApplied()) { // Edit the current domain settings.
1394 // Reapply the domain settings on returning to `MainWebViewActivity`.
1395 reapplyDomainSettingsOnRestart = true;
1397 // Create an intent to launch the domains activity.
1398 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1400 // Add the extra information to the intent.
1401 domainsIntent.putExtra("load_domain", currentWebView.getDomainSettingsDatabaseId());
1402 domainsIntent.putExtra("close_on_back", true);
1403 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1405 // Get the current certificate.
1406 SslCertificate sslCertificate = currentWebView.getCertificate();
1408 // Check to see if the SSL certificate is populated.
1409 if (sslCertificate != null) {
1410 // Extract the certificate to strings.
1411 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1412 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1413 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1414 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1415 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1416 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1417 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1418 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1420 // Add the certificate to the intent.
1421 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1422 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1423 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1424 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1425 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1426 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1427 domainsIntent.putExtra("ssl_start_date", startDateLong);
1428 domainsIntent.putExtra("ssl_end_date", endDateLong);
1431 // Check to see if the current IP addresses have been received.
1432 if (currentWebView.hasCurrentIpAddresses()) {
1433 // Add the current IP addresses to the intent.
1434 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1438 startActivity(domainsIntent);
1439 } else { // Add a new domain.
1440 // Apply the new domain settings on returning to `MainWebViewActivity`.
1441 reapplyDomainSettingsOnRestart = true;
1443 // Get the current domain
1444 Uri currentUri = Uri.parse(currentWebView.getUrl());
1445 String currentDomain = currentUri.getHost();
1447 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1448 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1450 // Create the domain and store the database ID.
1451 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1453 // Create an intent to launch the domains activity.
1454 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1456 // Add the extra information to the intent.
1457 domainsIntent.putExtra("load_domain", newDomainDatabaseId);
1458 domainsIntent.putExtra("close_on_back", true);
1459 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1461 // Get the current certificate.
1462 SslCertificate sslCertificate = currentWebView.getCertificate();
1464 // Check to see if the SSL certificate is populated.
1465 if (sslCertificate != null) {
1466 // Extract the certificate to strings.
1467 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1468 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1469 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1470 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1471 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1472 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1473 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1474 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1476 // Add the certificate to the intent.
1477 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1478 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1479 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1480 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1481 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1482 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1483 domainsIntent.putExtra("ssl_start_date", startDateLong);
1484 domainsIntent.putExtra("ssl_end_date", endDateLong);
1487 // Check to see if the current IP addresses have been received.
1488 if (currentWebView.hasCurrentIpAddresses()) {
1489 // Add the current IP addresses to the intent.
1490 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1494 startActivity(domainsIntent);
1498 case R.id.toggle_first_party_cookies:
1499 // Switch the first-party cookie status.
1500 cookieManager.setAcceptCookie(!cookieManager.acceptCookie());
1502 // Store the first-party cookie status.
1503 currentWebView.setAcceptFirstPartyCookies(cookieManager.acceptCookie());
1505 // Update the menu checkbox.
1506 menuItem.setChecked(cookieManager.acceptCookie());
1508 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1509 updatePrivacyIcons(true);
1511 // Display a snackbar.
1512 if (cookieManager.acceptCookie()) { // First-party cookies are enabled.
1513 Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1514 } else if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is still enabled.
1515 Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1516 } else { // Privacy mode.
1517 Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1520 // Reload the current WebView.
1521 currentWebView.reload();
1524 case R.id.toggle_third_party_cookies:
1525 if (Build.VERSION.SDK_INT >= 21) {
1526 // Switch the status of thirdPartyCookiesEnabled.
1527 cookieManager.setAcceptThirdPartyCookies(currentWebView, !cookieManager.acceptThirdPartyCookies(currentWebView));
1529 // Update the menu checkbox.
1530 menuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
1532 // Display a snackbar.
1533 if (cookieManager.acceptThirdPartyCookies(currentWebView)) {
1534 Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1536 Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1539 // Reload the current WebView.
1540 currentWebView.reload();
1541 } // Else do nothing because SDK < 21.
1544 case R.id.toggle_dom_storage:
1545 // Toggle the status of domStorageEnabled.
1546 currentWebView.getSettings().setDomStorageEnabled(!currentWebView.getSettings().getDomStorageEnabled());
1548 // Update the menu checkbox.
1549 menuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1551 // Update the privacy icon. `true` refreshes the app bar icons.
1552 updatePrivacyIcons(true);
1554 // Display a snackbar.
1555 if (currentWebView.getSettings().getDomStorageEnabled()) {
1556 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1558 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1561 // Reload the current WebView.
1562 currentWebView.reload();
1565 // Form data can be removed once the minimum API >= 26.
1566 case R.id.toggle_save_form_data:
1567 // Switch the status of saveFormDataEnabled.
1568 currentWebView.getSettings().setSaveFormData(!currentWebView.getSettings().getSaveFormData());
1570 // Update the menu checkbox.
1571 menuItem.setChecked(currentWebView.getSettings().getSaveFormData());
1573 // Display a snackbar.
1574 if (currentWebView.getSettings().getSaveFormData()) {
1575 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1577 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1580 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1581 updatePrivacyIcons(true);
1583 // Reload the current WebView.
1584 currentWebView.reload();
1587 case R.id.clear_cookies:
1588 Snackbar.make(findViewById(R.id.webviewpager), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1589 .setAction(R.string.undo, v -> {
1590 // Do nothing because everything will be handled by `onDismissed()` below.
1592 .addCallback(new Snackbar.Callback() {
1593 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1595 public void onDismissed(Snackbar snackbar, int event) {
1596 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1597 // Delete the cookies, which command varies by SDK.
1598 if (Build.VERSION.SDK_INT < 21) {
1599 cookieManager.removeAllCookie();
1601 cookieManager.removeAllCookies(null);
1609 case R.id.clear_dom_storage:
1610 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1611 .setAction(R.string.undo, v -> {
1612 // Do nothing because everything will be handled by `onDismissed()` below.
1614 .addCallback(new Snackbar.Callback() {
1615 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1617 public void onDismissed(Snackbar snackbar, int event) {
1618 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1619 // Delete the DOM Storage.
1620 WebStorage webStorage = WebStorage.getInstance();
1621 webStorage.deleteAllData();
1623 // Initialize a handler to manually delete the DOM storage files and directories.
1624 Handler deleteDomStorageHandler = new Handler();
1626 // Setup a runnable to manually delete the DOM storage files and directories.
1627 Runnable deleteDomStorageRunnable = () -> {
1629 // Get a handle for the runtime.
1630 Runtime runtime = Runtime.getRuntime();
1632 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
1633 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
1634 String privateDataDirectoryString = getApplicationInfo().dataDir;
1636 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1637 Process deleteLocalStorageProcess = runtime.exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1639 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1640 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1641 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1642 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1643 Process deleteDatabasesProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1645 // Wait for the processes to finish.
1646 deleteLocalStorageProcess.waitFor();
1647 deleteIndexProcess.waitFor();
1648 deleteQuotaManagerProcess.waitFor();
1649 deleteQuotaManagerJournalProcess.waitFor();
1650 deleteDatabasesProcess.waitFor();
1651 } catch (Exception exception) {
1652 // Do nothing if an error is thrown.
1656 // Manually delete the DOM storage files after 200 milliseconds.
1657 deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200);
1664 // Form data can be remove once the minimum API >= 26.
1665 case R.id.clear_form_data:
1666 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1667 .setAction(R.string.undo, v -> {
1668 // Do nothing because everything will be handled by `onDismissed()` below.
1670 .addCallback(new Snackbar.Callback() {
1671 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1673 public void onDismissed(Snackbar snackbar, int event) {
1674 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1675 // Delete the form data.
1676 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1677 mainWebViewDatabase.clearFormData();
1685 // Toggle the EasyList status.
1686 currentWebView.enableBlocklist(NestedScrollWebView.EASY_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST));
1688 // Update the menu checkbox.
1689 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST));
1691 // Reload the current WebView.
1692 currentWebView.reload();
1695 case R.id.easyprivacy:
1696 // Toggle the EasyPrivacy status.
1697 currentWebView.enableBlocklist(NestedScrollWebView.EASY_PRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY));
1699 // Update the menu checkbox.
1700 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY));
1702 // Reload the current WebView.
1703 currentWebView.reload();
1706 case R.id.fanboys_annoyance_list:
1707 // Toggle Fanboy's Annoyance List status.
1708 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1710 // Update the menu checkbox.
1711 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1713 // Update the staus of Fanboy's Social Blocking List.
1714 MenuItem fanboysSocialBlockingListMenuItem = optionsMenu.findItem(R.id.fanboys_social_blocking_list);
1715 fanboysSocialBlockingListMenuItem.setEnabled(!currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1717 // Reload the current WebView.
1718 currentWebView.reload();
1721 case R.id.fanboys_social_blocking_list:
1722 // Toggle Fanboy's Social Blocking List status.
1723 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1725 // Update the menu checkbox.
1726 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1728 // Reload the current WebView.
1729 currentWebView.reload();
1732 case R.id.ultraprivacy:
1733 // Toggle the UltraPrivacy status.
1734 currentWebView.enableBlocklist(NestedScrollWebView.ULTRA_PRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY));
1736 // Update the menu checkbox.
1737 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY));
1739 // Reload the current WebView.
1740 currentWebView.reload();
1743 case R.id.block_all_third_party_requests:
1744 //Toggle the third-party requests blocker status.
1745 currentWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, !currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1747 // Update the menu checkbox.
1748 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1750 // Reload the current WebView.
1751 currentWebView.reload();
1754 case R.id.user_agent_privacy_browser:
1755 // Update the user agent.
1756 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
1758 // Reload the current WebView.
1759 currentWebView.reload();
1762 case R.id.user_agent_webview_default:
1763 // Update the user agent.
1764 currentWebView.getSettings().setUserAgentString("");
1766 // Reload the current WebView.
1767 currentWebView.reload();
1770 case R.id.user_agent_firefox_on_android:
1771 // Update the user agent.
1772 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
1774 // Reload the current WebView.
1775 currentWebView.reload();
1778 case R.id.user_agent_chrome_on_android:
1779 // Update the user agent.
1780 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
1782 // Reload the current WebView.
1783 currentWebView.reload();
1786 case R.id.user_agent_safari_on_ios:
1787 // Update the user agent.
1788 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
1790 // Reload the current WebView.
1791 currentWebView.reload();
1794 case R.id.user_agent_firefox_on_linux:
1795 // Update the user agent.
1796 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
1798 // Reload the current WebView.
1799 currentWebView.reload();
1802 case R.id.user_agent_chromium_on_linux:
1803 // Update the user agent.
1804 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
1806 // Reload the current WebView.
1807 currentWebView.reload();
1810 case R.id.user_agent_firefox_on_windows:
1811 // Update the user agent.
1812 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
1814 // Reload the current WebView.
1815 currentWebView.reload();
1818 case R.id.user_agent_chrome_on_windows:
1819 // Update the user agent.
1820 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
1822 // Reload the current WebView.
1823 currentWebView.reload();
1826 case R.id.user_agent_edge_on_windows:
1827 // Update the user agent.
1828 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
1830 // Reload the current WebView.
1831 currentWebView.reload();
1834 case R.id.user_agent_internet_explorer_on_windows:
1835 // Update the user agent.
1836 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
1838 // Reload the current WebView.
1839 currentWebView.reload();
1842 case R.id.user_agent_safari_on_macos:
1843 // Update the user agent.
1844 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
1846 // Reload the current WebView.
1847 currentWebView.reload();
1850 case R.id.user_agent_custom:
1851 // Update the user agent.
1852 currentWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
1854 // Reload the current WebView.
1855 currentWebView.reload();
1858 case R.id.font_size_twenty_five_percent:
1859 currentWebView.getSettings().setTextZoom(25);
1862 case R.id.font_size_fifty_percent:
1863 currentWebView.getSettings().setTextZoom(50);
1866 case R.id.font_size_seventy_five_percent:
1867 currentWebView.getSettings().setTextZoom(75);
1870 case R.id.font_size_one_hundred_percent:
1871 currentWebView.getSettings().setTextZoom(100);
1874 case R.id.font_size_one_hundred_twenty_five_percent:
1875 currentWebView.getSettings().setTextZoom(125);
1878 case R.id.font_size_one_hundred_fifty_percent:
1879 currentWebView.getSettings().setTextZoom(150);
1882 case R.id.font_size_one_hundred_seventy_five_percent:
1883 currentWebView.getSettings().setTextZoom(175);
1886 case R.id.font_size_two_hundred_percent:
1887 currentWebView.getSettings().setTextZoom(200);
1890 case R.id.swipe_to_refresh:
1891 // Toggle the stored status of swipe to refresh.
1892 currentWebView.setSwipeToRefresh(!currentWebView.getSwipeToRefresh());
1894 // Get a handle for the swipe refresh layout.
1895 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
1897 // Update the swipe refresh layout.
1898 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
1899 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.
1900 // Only enable the swipe refresh layout if the WebView is scrolled to the top.
1901 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
1902 } else { // For API < 23, the swipe refresh layout is always enabled.
1903 // Enable the swipe refresh layout.
1904 swipeRefreshLayout.setEnabled(true);
1906 } else { // Swipe to refresh is disabled.
1907 // Disable the swipe refresh layout.
1908 swipeRefreshLayout.setEnabled(false);
1912 case R.id.display_images:
1913 if (currentWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1914 // Disable loading of images.
1915 currentWebView.getSettings().setLoadsImagesAutomatically(false);
1917 // Reload the website to remove existing images.
1918 currentWebView.reload();
1919 } else { // Images are not currently loaded automatically.
1920 // Enable loading of images. Missing images will be loaded without the need for a reload.
1921 currentWebView.getSettings().setLoadsImagesAutomatically(true);
1925 case R.id.night_mode:
1926 // Toggle night mode.
1927 currentWebView.setNightMode(!currentWebView.getNightMode());
1929 // Enable or disable JavaScript according to night mode, the global preference, and any domain settings.
1930 if (currentWebView.getNightMode()) { // Night mode is enabled, which requires JavaScript.
1931 // Enable JavaScript.
1932 currentWebView.getSettings().setJavaScriptEnabled(true);
1933 } else if (currentWebView.getDomainSettingsApplied()) { // Night mode is disabled and domain settings are applied. Set JavaScript according to the domain settings.
1934 // Apply the JavaScript preference that was stored the last time domain settings were loaded.
1935 currentWebView.getSettings().setJavaScriptEnabled(currentWebView.getDomainSettingsJavaScriptEnabled());
1936 } else { // Night mode is disabled and domain settings are not applied. Set JavaScript according to the global preference.
1937 // Apply the JavaScript preference.
1938 currentWebView.getSettings().setJavaScriptEnabled(sharedPreferences.getBoolean("javascript", false));
1941 // Update the privacy icons.
1942 updatePrivacyIcons(false);
1944 // Reload the website.
1945 currentWebView.reload();
1948 case R.id.find_on_page:
1949 // Get a handle for the views.
1950 Toolbar toolbar = findViewById(R.id.toolbar);
1951 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
1952 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
1954 // Set the minimum height of the find on page linear layout to match the toolbar.
1955 findOnPageLinearLayout.setMinimumHeight(toolbar.getHeight());
1957 // Hide the toolbar.
1958 toolbar.setVisibility(View.GONE);
1960 // Show the find on page linear layout.
1961 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1963 // Display the keyboard. The app must wait 200 ms before running the command to work around a bug in Android.
1964 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1965 findOnPageEditText.postDelayed(() -> {
1966 // Set the focus on `findOnPageEditText`.
1967 findOnPageEditText.requestFocus();
1969 // Get a handle for the input method manager.
1970 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1972 // Remove the lint warning below that the input method manager might be null.
1973 assert inputMethodManager != null;
1975 // Display the keyboard. `0` sets no input flags.
1976 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1980 case R.id.view_source:
1981 // Create an intent to launch the view source activity.
1982 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
1984 // Add the variables to the intent.
1985 viewSourceIntent.putExtra("user_agent", currentWebView.getSettings().getUserAgentString());
1986 viewSourceIntent.putExtra("current_url", currentWebView.getUrl());
1989 startActivity(viewSourceIntent);
1992 case R.id.share_url:
1993 // Setup the share string.
1994 String shareString = currentWebView.getTitle() + " – " + currentWebView.getUrl();
1996 // Create the share intent.
1997 Intent shareIntent = new Intent(Intent.ACTION_SEND);
1998 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1999 shareIntent.setType("text/plain");
2002 startActivity(Intent.createChooser(shareIntent, getString(R.string.share_url)));
2006 // Get a print manager instance.
2007 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
2009 // Remove the lint error below that print manager might be null.
2010 assert printManager != null;
2012 // Create a print document adapter from the current WebView.
2013 PrintDocumentAdapter printDocumentAdapter = currentWebView.createPrintDocumentAdapter();
2015 // Print the document.
2016 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
2019 case R.id.open_with_app:
2020 openWithApp(currentWebView.getUrl());
2023 case R.id.open_with_browser:
2024 openWithBrowser(currentWebView.getUrl());
2027 case R.id.add_to_homescreen:
2028 // Instantiate the create home screen shortcut dialog.
2029 DialogFragment createHomeScreenShortcutDialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView.getTitle(), currentWebView.getUrl(),
2030 currentWebView.getFavoriteOrDefaultIcon());
2032 // Show the create home screen shortcut dialog.
2033 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2036 case R.id.proxy_through_orbot:
2037 // Toggle the proxy through Orbot variable.
2038 proxyThroughOrbot = !proxyThroughOrbot;
2040 // Apply the proxy through Orbot settings.
2041 applyProxyThroughOrbot(true);
2045 if (menuItem.getTitle().equals(getString(R.string.refresh))) { // The refresh button was pushed.
2046 // Reload the current WebView.
2047 currentWebView.reload();
2048 } else { // The stop button was pushed.
2049 // Stop the loading of the WebView.
2050 currentWebView.stopLoading();
2054 case R.id.ad_consent:
2055 // Display the ad consent dialog.
2056 DialogFragment adConsentDialogFragment = new AdConsentDialog();
2057 adConsentDialogFragment.show(getSupportFragmentManager(), getString(R.string.ad_consent));
2061 // Don't consume the event.
2062 return super.onOptionsItemSelected(menuItem);
2066 // removeAllCookies is deprecated, but it is required for API < 21.
2068 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2069 // Get the menu item ID.
2070 int menuItemId = menuItem.getItemId();
2072 // Get a handle for the shared preferences.
2073 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2075 // Run the commands that correspond to the selected menu item.
2076 switch (menuItemId) {
2077 case R.id.clear_and_exit:
2078 // Clear and exit Privacy Browser.
2083 // Select the homepage based on the proxy through Orbot status.
2084 if (proxyThroughOrbot) {
2085 // Load the Tor homepage.
2086 loadUrl(sharedPreferences.getString("tor_homepage", getString(R.string.tor_homepage_default_value)));
2088 // Load the normal homepage.
2089 loadUrl(sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
2094 if (currentWebView.canGoBack()) {
2095 // Reset the current domain name so that navigation works if third-party requests are blocked.
2096 currentWebView.resetCurrentDomainName();
2098 // Set navigating history so that the domain settings are applied when the new URL is loaded.
2099 currentWebView.setNavigatingHistory(true);
2101 // Load the previous website in the history.
2102 currentWebView.goBack();
2107 if (currentWebView.canGoForward()) {
2108 // Reset the current domain name so that navigation works if third-party requests are blocked.
2109 currentWebView.resetCurrentDomainName();
2111 // Set navigating history so that the domain settings are applied when the new URL is loaded.
2112 currentWebView.setNavigatingHistory(true);
2114 // Load the next website in the history.
2115 currentWebView.goForward();
2120 // Instantiate the URL history dialog.
2121 DialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(currentWebView.getWebViewFragmentId());
2123 // Show the URL history dialog.
2124 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2128 // Populate the resource requests.
2129 RequestsActivity.resourceRequests = currentWebView.getResourceRequests();
2131 // Create an intent to launch the Requests activity.
2132 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2134 // Add the block third-party requests status to the intent.
2135 requestsIntent.putExtra("block_all_third_party_requests", currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
2138 startActivity(requestsIntent);
2141 case R.id.downloads:
2142 // Launch the system Download Manager.
2143 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2145 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2146 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2148 startActivity(downloadManagerIntent);
2152 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2153 reapplyDomainSettingsOnRestart = true;
2155 // Launch the domains activity.
2156 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2158 // Add the extra information to the intent.
2159 domainsIntent.putExtra("current_url", currentWebView.getUrl());
2161 // Get the current certificate.
2162 SslCertificate sslCertificate = currentWebView.getCertificate();
2164 // Check to see if the SSL certificate is populated.
2165 if (sslCertificate != null) {
2166 // Extract the certificate to strings.
2167 String issuedToCName = sslCertificate.getIssuedTo().getCName();
2168 String issuedToOName = sslCertificate.getIssuedTo().getOName();
2169 String issuedToUName = sslCertificate.getIssuedTo().getUName();
2170 String issuedByCName = sslCertificate.getIssuedBy().getCName();
2171 String issuedByOName = sslCertificate.getIssuedBy().getOName();
2172 String issuedByUName = sslCertificate.getIssuedBy().getUName();
2173 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
2174 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
2176 // Add the certificate to the intent.
2177 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
2178 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
2179 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
2180 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
2181 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
2182 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
2183 domainsIntent.putExtra("ssl_start_date", startDateLong);
2184 domainsIntent.putExtra("ssl_end_date", endDateLong);
2187 // Check to see if the current IP addresses have been received.
2188 if (currentWebView.hasCurrentIpAddresses()) {
2189 // Add the current IP addresses to the intent.
2190 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
2194 startActivity(domainsIntent);
2198 // Set the flag to reapply app settings on restart when returning from Settings.
2199 reapplyAppSettingsOnRestart = true;
2201 // Set the flag to reapply the domain settings on restart when returning from Settings.
2202 reapplyDomainSettingsOnRestart = true;
2204 // Launch the settings activity.
2205 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2206 startActivity(settingsIntent);
2209 case R.id.import_export:
2210 // Launch the import/export activity.
2211 Intent importExportIntent = new Intent (this, ImportExportActivity.class);
2212 startActivity(importExportIntent);
2216 // Launch the logcat activity.
2217 Intent logcatIntent = new Intent(this, LogcatActivity.class);
2218 startActivity(logcatIntent);
2222 // Launch `GuideActivity`.
2223 Intent guideIntent = new Intent(this, GuideActivity.class);
2224 startActivity(guideIntent);
2228 // Create an intent to launch the about activity.
2229 Intent aboutIntent = new Intent(this, AboutActivity.class);
2231 // Create a string array for the blocklist versions.
2232 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],
2233 ultraPrivacy.get(0).get(0)[0]};
2235 // Add the blocklist versions to the intent.
2236 aboutIntent.putExtra("blocklist_versions", blocklistVersions);
2239 startActivity(aboutIntent);
2243 // Get a handle for the drawer layout.
2244 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
2246 // Close the navigation drawer.
2247 drawerLayout.closeDrawer(GravityCompat.START);
2252 public void onPostCreate(Bundle savedInstanceState) {
2253 // Run the default commands.
2254 super.onPostCreate(savedInstanceState);
2256 // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished. This creates the navigation drawer icon.
2257 actionBarDrawerToggle.syncState();
2261 public void onConfigurationChanged(Configuration newConfig) {
2262 // Run the default commands.
2263 super.onConfigurationChanged(newConfig);
2265 // Get the status bar pixel size.
2266 int statusBarResourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
2267 int statusBarPixelSize = getResources().getDimensionPixelSize(statusBarResourceId);
2269 // Get the resource density.
2270 float screenDensity = getResources().getDisplayMetrics().density;
2272 // Recalculate the drawer header padding.
2273 drawerHeaderPaddingLeftAndRight = (int) (15 * screenDensity);
2274 drawerHeaderPaddingTop = statusBarPixelSize + (int) (4 * screenDensity);
2275 drawerHeaderPaddingBottom = (int) (8 * screenDensity);
2277 // Reload the ad for the free flavor if not in full screen mode.
2278 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2279 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2280 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
2283 // `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:
2284 // https://code.google.com/p/android/issues/detail?id=20493#c8
2285 // ActivityCompat.invalidateOptionsMenu(this);
2289 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2290 // Store the hit test result.
2291 final WebView.HitTestResult hitTestResult = currentWebView.getHitTestResult();
2293 // Create the URL strings.
2294 final String imageUrl;
2295 final String linkUrl;
2297 // Get handles for the system managers.
2298 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2299 FragmentManager fragmentManager = getSupportFragmentManager();
2300 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2302 // Remove the lint errors below that the clipboard manager might be null.
2303 assert clipboardManager != null;
2305 // Process the link according to the type.
2306 switch (hitTestResult.getType()) {
2307 // `SRC_ANCHOR_TYPE` is a link.
2308 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2309 // Get the target URL.
2310 linkUrl = hitTestResult.getExtra();
2312 // Set the target URL as the title of the `ContextMenu`.
2313 menu.setHeaderTitle(linkUrl);
2315 // Add an Open in New Tab entry.
2316 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2317 // Load the link URL in a new tab.
2322 // Add an Open with App entry.
2323 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2324 openWithApp(linkUrl);
2328 // Add an Open with Browser entry.
2329 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2330 openWithBrowser(linkUrl);
2334 // Add a Copy URL entry.
2335 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2336 // Save the link URL in a `ClipData`.
2337 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2339 // Set the `ClipData` as the clipboard's primary clip.
2340 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2344 // Add a Download URL entry.
2345 menu.add(R.string.download_url).setOnMenuItemClickListener((MenuItem item) -> {
2346 // Check if the download should be processed by an external app.
2347 if (sharedPreferences.getBoolean("download_with_external_app", false)) { // Download with an external app.
2348 openUrlWithExternalApp(linkUrl);
2349 } else { // Download with Android's download manager.
2350 // Check to see if the storage permission has already been granted.
2351 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission needs to be requested.
2352 // Store the variables for future use by `onRequestPermissionsResult()`.
2353 downloadUrl = linkUrl;
2354 downloadContentDisposition = "none";
2355 downloadContentLength = -1;
2357 // Show a dialog if the user has previously denied the permission.
2358 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2359 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
2360 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
2362 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
2363 downloadLocationPermissionDialogFragment.show(fragmentManager, getString(R.string.download_location));
2364 } else { // Show the permission request directly.
2365 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
2366 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2368 } else { // The storage permission has already been granted.
2369 // Get a handle for the download file alert dialog.
2370 DialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(linkUrl, "none", -1);
2372 // Show the download file alert dialog.
2373 downloadFileDialogFragment.show(fragmentManager, getString(R.string.download));
2379 // Add a Cancel entry, which by default closes the context menu.
2380 menu.add(R.string.cancel);
2383 case WebView.HitTestResult.EMAIL_TYPE:
2384 // Get the target URL.
2385 linkUrl = hitTestResult.getExtra();
2387 // Set the target URL as the title of the `ContextMenu`.
2388 menu.setHeaderTitle(linkUrl);
2390 // Add a Write Email entry.
2391 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2392 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2393 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2395 // Parse the url and set it as the data for the `Intent`.
2396 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2398 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2399 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2402 startActivity(emailIntent);
2406 // Add a Copy Email Address entry.
2407 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2408 // Save the email address in a `ClipData`.
2409 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2411 // Set the `ClipData` as the clipboard's primary clip.
2412 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2416 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2417 menu.add(R.string.cancel);
2420 // `IMAGE_TYPE` is an image. `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link. Privacy Browser processes them the same.
2421 case WebView.HitTestResult.IMAGE_TYPE:
2422 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2423 // Get the image URL.
2424 imageUrl = hitTestResult.getExtra();
2426 // Set the image URL as the title of the context menu.
2427 menu.setHeaderTitle(imageUrl);
2429 // Add an Open in New Tab entry.
2430 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2431 // Load the image URL in a new tab.
2432 addNewTab(imageUrl);
2436 // Add a View Image entry.
2437 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2442 // Add a `Download Image` entry.
2443 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2444 // Check if the download should be processed by an external app.
2445 if (sharedPreferences.getBoolean("download_with_external_app", false)) { // Download with an external app.
2446 openUrlWithExternalApp(imageUrl);
2447 } else { // Download with Android's download manager.
2448 // Check to see if the storage permission has already been granted.
2449 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission needs to be requested.
2450 // Store the image URL for use by `onRequestPermissionResult()`.
2451 downloadImageUrl = imageUrl;
2453 // Show a dialog if the user has previously denied the permission.
2454 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2455 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2456 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2458 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
2459 downloadLocationPermissionDialogFragment.show(fragmentManager, getString(R.string.download_location));
2460 } else { // Show the permission request directly.
2461 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
2462 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2464 } else { // The storage permission has already been granted.
2465 // Get a handle for the download image alert dialog.
2466 DialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2468 // Show the download image alert dialog.
2469 downloadImageDialogFragment.show(fragmentManager, getString(R.string.download));
2475 // Add a `Copy URL` entry.
2476 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2477 // Save the image URL in a `ClipData`.
2478 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2480 // Set the `ClipData` as the clipboard's primary clip.
2481 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2485 // Add an Open with App entry.
2486 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2487 openWithApp(imageUrl);
2491 // Add an Open with Browser entry.
2492 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2493 openWithBrowser(imageUrl);
2497 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2498 menu.add(R.string.cancel);
2504 public void onCreateBookmark(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2505 // Get a handle for the bookmarks list view.
2506 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2508 // Get the views from the dialog fragment.
2509 EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
2510 EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
2512 // Extract the strings from the edit texts.
2513 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2514 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2516 // Create a favorite icon byte array output stream.
2517 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2519 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2520 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2522 // Convert the favorite icon byte array stream to a byte array.
2523 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2525 // Display the new bookmark below the current items in the (0 indexed) list.
2526 int newBookmarkDisplayOrder = bookmarksListView.getCount();
2528 // Create the bookmark.
2529 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2531 // Update the bookmarks cursor with the current contents of this folder.
2532 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2534 // Update the list view.
2535 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2537 // Scroll to the new bookmark.
2538 bookmarksListView.setSelection(newBookmarkDisplayOrder);
2542 public void onCreateBookmarkFolder(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2543 // Get a handle for the bookmarks list view.
2544 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2546 // Get handles for the views in the dialog fragment.
2547 EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
2548 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
2549 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
2551 // Get new folder name string.
2552 String folderNameString = createFolderNameEditText.getText().toString();
2554 // Create a folder icon bitmap.
2555 Bitmap folderIconBitmap;
2557 // Set the folder icon bitmap according to the dialog.
2558 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
2559 // Get the default folder icon drawable.
2560 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2562 // Convert the folder icon drawable to a bitmap drawable.
2563 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2565 // Convert the folder icon bitmap drawable to a bitmap.
2566 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2567 } else { // Use the WebView favorite icon.
2568 // Copy the favorite icon bitmap to the folder icon bitmap.
2569 folderIconBitmap = favoriteIconBitmap;
2572 // Create a folder icon byte array output stream.
2573 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2575 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2576 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2578 // Convert the folder icon byte array stream to a byte array.
2579 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2581 // Move all the bookmarks down one in the display order.
2582 for (int i = 0; i < bookmarksListView.getCount(); i++) {
2583 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2584 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2587 // Create the folder, which will be placed at the top of the `ListView`.
2588 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2590 // Update the bookmarks cursor with the current contents of this folder.
2591 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2593 // Update the `ListView`.
2594 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2596 // Scroll to the new folder.
2597 bookmarksListView.setSelection(0);
2601 public void onSaveBookmark(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, Bitmap favoriteIconBitmap) {
2602 // Get handles for the views from `dialogFragment`.
2603 EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
2604 EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
2605 RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
2607 // Store the bookmark strings.
2608 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
2609 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
2611 // Update the bookmark.
2612 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
2613 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
2614 } else { // Update the bookmark using the `WebView` favorite icon.
2615 // Create a favorite icon byte array output stream.
2616 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2618 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2619 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
2621 // Convert the favorite icon byte array stream to a byte array.
2622 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
2624 // Update the bookmark and the favorite icon.
2625 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
2628 // Update the bookmarks cursor with the current contents of this folder.
2629 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2631 // Update the list view.
2632 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2636 public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId, Bitmap favoriteIconBitmap) {
2637 // Get handles for the views from `dialogFragment`.
2638 EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
2639 RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
2640 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
2641 ImageView defaultFolderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
2643 // Get the new folder name.
2644 String newFolderNameString = editFolderNameEditText.getText().toString();
2646 // Check if the favorite icon has changed.
2647 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
2648 // Update the name in the database.
2649 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2650 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
2651 // Create the new folder icon Bitmap.
2652 Bitmap folderIconBitmap;
2654 // Populate the new folder icon bitmap.
2655 if (defaultFolderIconRadioButton.isChecked()) {
2656 // Get the default folder icon drawable.
2657 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2659 // Convert the folder icon drawable to a bitmap drawable.
2660 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2662 // Convert the folder icon bitmap drawable to a bitmap.
2663 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2664 } else { // Use the `WebView` favorite icon.
2665 // Copy the favorite icon bitmap to the folder icon bitmap.
2666 folderIconBitmap = favoriteIconBitmap;
2669 // Create a folder icon byte array output stream.
2670 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2672 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2673 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2675 // Convert the folder icon byte array stream to a byte array.
2676 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2678 // Update the folder icon in the database.
2679 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, newFolderIconByteArray);
2680 } else { // The folder icon and the name have changed.
2681 // Get the new folder icon `Bitmap`.
2682 Bitmap folderIconBitmap;
2683 if (defaultFolderIconRadioButton.isChecked()) {
2684 // Get the default folder icon drawable.
2685 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2687 // Convert the folder icon drawable to a bitmap drawable.
2688 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2690 // Convert the folder icon bitmap drawable to a bitmap.
2691 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2692 } else { // Use the `WebView` favorite icon.
2693 // Copy the favorite icon bitmap to the folder icon bitmap.
2694 folderIconBitmap = favoriteIconBitmap;
2697 // Create a folder icon byte array output stream.
2698 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2700 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2701 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2703 // Convert the folder icon byte array stream to a byte array.
2704 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2706 // Update the folder name and icon in the database.
2707 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, newFolderIconByteArray);
2710 // Update the bookmarks cursor with the current contents of this folder.
2711 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2713 // Update the `ListView`.
2714 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2718 public void onCloseDownloadLocationPermissionDialog(int downloadType) {
2719 switch (downloadType) {
2720 case DownloadLocationPermissionDialog.DOWNLOAD_FILE:
2721 // Request the WRITE_EXTERNAL_STORAGE permission with a file request code.
2722 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2725 case DownloadLocationPermissionDialog.DOWNLOAD_IMAGE:
2726 // Request the WRITE_EXTERNAL_STORAGE permission with an image request code.
2727 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2733 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
2734 // Get a handle for the fragment manager.
2735 FragmentManager fragmentManager = getSupportFragmentManager();
2737 switch (requestCode) {
2738 case DOWNLOAD_FILE_REQUEST_CODE:
2739 // Show the download file alert dialog. When the dialog closes, the correct command will be used based on the permission status.
2740 DialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(downloadUrl, downloadContentDisposition, downloadContentLength);
2742 // On API 23, displaying the fragment must be delayed or the app will crash.
2743 if (Build.VERSION.SDK_INT == 23) {
2744 new Handler().postDelayed(() -> downloadFileDialogFragment.show(fragmentManager, getString(R.string.download)), 500);
2746 downloadFileDialogFragment.show(fragmentManager, getString(R.string.download));
2749 // Reset the download variables.
2751 downloadContentDisposition = "";
2752 downloadContentLength = 0;
2755 case DOWNLOAD_IMAGE_REQUEST_CODE:
2756 // Show the download image alert dialog. When the dialog closes, the correct command will be used based on the permission status.
2757 DialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(downloadImageUrl);
2759 // On API 23, displaying the fragment must be delayed or the app will crash.
2760 if (Build.VERSION.SDK_INT == 23) {
2761 new Handler().postDelayed(() -> downloadImageDialogFragment.show(fragmentManager, getString(R.string.download)), 500);
2763 downloadImageDialogFragment.show(fragmentManager, getString(R.string.download));
2766 // Reset the image URL variable.
2767 downloadImageUrl = "";
2773 public void onDownloadImage(DialogFragment dialogFragment, String imageUrl) {
2774 // Download the image if it has an HTTP or HTTPS URI.
2775 if (imageUrl.startsWith("http")) {
2776 // Get a handle for the system `DOWNLOAD_SERVICE`.
2777 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2779 // Parse `imageUrl`.
2780 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
2782 // Get a handle for the cookie manager.
2783 CookieManager cookieManager = CookieManager.getInstance();
2785 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
2786 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2787 if (cookieManager.acceptCookie()) {
2788 // Get the cookies for `imageUrl`.
2789 String cookies = cookieManager.getCookie(imageUrl);
2791 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2792 downloadRequest.addRequestHeader("Cookie", cookies);
2795 // Get the file name from the dialog fragment.
2796 EditText downloadImageNameEditText = dialogFragment.getDialog().findViewById(R.id.download_image_name);
2797 String imageName = downloadImageNameEditText.getText().toString();
2799 // Specify the download location.
2800 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
2801 // Download to the public download directory.
2802 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, imageName);
2803 } else { // External write permission denied.
2804 // Download to the app's external download directory.
2805 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, imageName);
2808 // Allow `MediaScanner` to index the download if it is a media file.
2809 downloadRequest.allowScanningByMediaScanner();
2811 // Add the URL as the description for the download.
2812 downloadRequest.setDescription(imageUrl);
2814 // Show the download notification after the download is completed.
2815 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2817 // Remove the lint warning below that `downloadManager` might be `null`.
2818 assert downloadManager != null;
2820 // Initiate the download.
2821 downloadManager.enqueue(downloadRequest);
2822 } else { // The image is not an HTTP or HTTPS URI.
2823 Snackbar.make(currentWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
2828 public void onDownloadFile(DialogFragment dialogFragment, String downloadUrl) {
2829 // Download the file if it has an HTTP or HTTPS URI.
2830 if (downloadUrl.startsWith("http")) {
2831 // Get a handle for the system `DOWNLOAD_SERVICE`.
2832 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2834 // Parse `downloadUrl`.
2835 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
2837 // Get a handle for the cookie manager.
2838 CookieManager cookieManager = CookieManager.getInstance();
2840 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
2841 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2842 if (cookieManager.acceptCookie()) {
2843 // Get the cookies for `downloadUrl`.
2844 String cookies = cookieManager.getCookie(downloadUrl);
2846 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2847 downloadRequest.addRequestHeader("Cookie", cookies);
2850 // Get the file name from the dialog fragment.
2851 EditText downloadFileNameEditText = dialogFragment.getDialog().findViewById(R.id.download_file_name);
2852 String fileName = downloadFileNameEditText.getText().toString();
2854 // Specify the download location.
2855 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
2856 // Download to the public download directory.
2857 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
2858 } else { // External write permission denied.
2859 // Download to the app's external download directory.
2860 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, fileName);
2863 // Allow `MediaScanner` to index the download if it is a media file.
2864 downloadRequest.allowScanningByMediaScanner();
2866 // Add the URL as the description for the download.
2867 downloadRequest.setDescription(downloadUrl);
2869 // Show the download notification after the download is completed.
2870 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2872 // Remove the lint warning below that `downloadManager` might be `null`.
2873 assert downloadManager != null;
2875 // Initiate the download.
2876 downloadManager.enqueue(downloadRequest);
2877 } else { // The download is not an HTTP or HTTPS URI.
2878 Snackbar.make(currentWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
2882 // Override `onBackPressed` to handle the navigation drawer and and the WebView.
2884 public void onBackPressed() {
2885 // Get a handle for the drawer layout and the tab layout.
2886 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
2887 TabLayout tabLayout = findViewById(R.id.tablayout);
2889 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
2890 // Close the navigation drawer.
2891 drawerLayout.closeDrawer(GravityCompat.START);
2892 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
2893 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
2894 // close the bookmarks drawer.
2895 drawerLayout.closeDrawer(GravityCompat.END);
2896 } else { // A subfolder is displayed.
2897 // Place the former parent folder in `currentFolder`.
2898 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolderName(currentBookmarksFolder);
2900 // Load the new folder.
2901 loadBookmarksFolder();
2903 } else if (currentWebView.canGoBack()) { // There is at least one item in the current WebView history.
2904 // Reset the current domain name so that navigation works if third-party requests are blocked.
2905 currentWebView.resetCurrentDomainName();
2907 // Set navigating history so that the domain settings are applied when the new URL is loaded.
2908 currentWebView.setNavigatingHistory(true);
2911 currentWebView.goBack();
2912 } else if (tabLayout.getTabCount() > 1) { // There are at least two tabs.
2913 // Close the current tab.
2915 } else { // There isn't anything to do in Privacy Browser.
2916 // Run the default commands.
2917 super.onBackPressed();
2919 // Manually kill Privacy Browser. Otherwise, it is glitchy when restarted.
2924 // 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.
2926 public void onActivityResult(int requestCode, int resultCode, Intent data) {
2927 // File uploads only work on API >= 21.
2928 if (Build.VERSION.SDK_INT >= 21) {
2929 // Pass the file to the WebView.
2930 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
2934 private void loadUrlFromTextBox() {
2935 // Get a handle for the URL edit text.
2936 EditText urlEditText = findViewById(R.id.url_edittext);
2938 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
2939 String unformattedUrlString = urlEditText.getText().toString().trim();
2941 // Initialize the formatted URL string.
2944 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
2945 if (unformattedUrlString.startsWith("content://")) { // This is a Content URL.
2946 // Load the entire content URL.
2947 url = unformattedUrlString;
2948 } else if (Patterns.WEB_URL.matcher(unformattedUrlString).matches() || unformattedUrlString.startsWith("http://") || unformattedUrlString.startsWith("https://") ||
2949 unformattedUrlString.startsWith("file://")) { // This is a standard URL.
2950 // Add `https://` at the beginning if there is no protocol. Otherwise the app will segfault.
2951 if (!unformattedUrlString.startsWith("http") && !unformattedUrlString.startsWith("file://") && !unformattedUrlString.startsWith("content://")) {
2952 unformattedUrlString = "https://" + unformattedUrlString;
2955 // Initialize `unformattedUrl`.
2956 URL unformattedUrl = null;
2958 // 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.
2960 unformattedUrl = new URL(unformattedUrlString);
2961 } catch (MalformedURLException e) {
2962 e.printStackTrace();
2965 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2966 String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2967 String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2968 String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2969 String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2970 String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2973 Uri.Builder uri = new Uri.Builder();
2974 uri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2976 // Decode the URI as a UTF-8 string in.
2978 url = URLDecoder.decode(uri.build().toString(), "UTF-8");
2979 } catch (UnsupportedEncodingException exception) {
2980 // Do nothing. The formatted URL string will remain blank.
2982 } else if (!unformattedUrlString.isEmpty()){ // This is not a URL, but rather a search string.
2983 // Create an encoded URL String.
2984 String encodedUrlString;
2986 // Sanitize the search input.
2988 encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2989 } catch (UnsupportedEncodingException exception) {
2990 encodedUrlString = "";
2993 // Add the base search URL.
2994 url = searchURL + encodedUrlString;
2997 // 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.
2998 urlEditText.clearFocus();
3004 private void loadUrl(String url) {
3005 // Sanitize the URL.
3006 url = sanitizeUrl(url);
3008 // Apply the domain settings.
3009 applyDomainSettings(currentWebView, url, true, false);
3012 currentWebView.loadUrl(url, customHeaders);
3015 public void findPreviousOnPage(View view) {
3016 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
3017 currentWebView.findNext(false);
3020 public void findNextOnPage(View view) {
3021 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
3022 currentWebView.findNext(true);
3025 public void closeFindOnPage(View view) {
3026 // Get a handle for the views.
3027 Toolbar toolbar = findViewById(R.id.toolbar);
3028 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
3029 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
3031 // Delete the contents of `find_on_page_edittext`.
3032 findOnPageEditText.setText(null);
3034 // Clear the highlighted phrases if the WebView is not null.
3035 if (currentWebView != null) {
3036 currentWebView.clearMatches();
3039 // Hide the find on page linear layout.
3040 findOnPageLinearLayout.setVisibility(View.GONE);
3042 // Show the toolbar.
3043 toolbar.setVisibility(View.VISIBLE);
3045 // Get a handle for the input method manager.
3046 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
3048 // Remove the lint warning below that the input method manager might be null.
3049 assert inputMethodManager != null;
3051 // Hide the keyboard.
3052 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
3055 private void applyAppSettings() {
3056 // Get a handle for the shared preferences.
3057 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3059 // Store the values from the shared preferences in variables.
3060 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3061 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
3062 sanitizeGoogleAnalytics = sharedPreferences.getBoolean("google_analytics", true);
3063 proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
3064 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3065 hideAppBar = sharedPreferences.getBoolean("hide_app_bar", true);
3066 scrollAppBar = sharedPreferences.getBoolean("scroll_app_bar", true);
3068 // Get handles for the views that need to be modified.
3069 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
3070 AppBarLayout appBarLayout = findViewById(R.id.appbar_layout);
3071 ActionBar actionBar = getSupportActionBar();
3072 Toolbar toolbar = findViewById(R.id.toolbar);
3073 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
3074 LinearLayout tabsLinearLayout = findViewById(R.id.tabs_linearlayout);
3075 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
3077 // Remove the incorrect lint warning below that the action bar might be null.
3078 assert actionBar != null;
3080 // Apply the proxy through Orbot settings.
3081 applyProxyThroughOrbot(false);
3083 // Set Do Not Track status.
3084 if (doNotTrackEnabled) {
3085 customHeaders.put("DNT", "1");
3087 customHeaders.remove("DNT");
3090 // Get the current layout parameters. Using coordinator layout parameters allows the `setBehavior()` command and using app bar layout parameters allows the `setScrollFlags()` command.
3091 CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
3092 AppBarLayout.LayoutParams toolbarLayoutParams = (AppBarLayout.LayoutParams) toolbar.getLayoutParams();
3093 AppBarLayout.LayoutParams findOnPageLayoutParams = (AppBarLayout.LayoutParams) findOnPageLinearLayout.getLayoutParams();
3094 AppBarLayout.LayoutParams tabsLayoutParams = (AppBarLayout.LayoutParams) tabsLinearLayout.getLayoutParams();
3096 // Add the scrolling behavior to the layout parameters.
3098 // Enable scrolling of the app bar.
3099 swipeRefreshLayoutParams.setBehavior(new AppBarLayout.ScrollingViewBehavior());
3100 toolbarLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3101 findOnPageLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3102 tabsLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3104 // Disable scrolling of the app bar.
3105 swipeRefreshLayoutParams.setBehavior(null);
3106 toolbarLayoutParams.setScrollFlags(0);
3107 findOnPageLayoutParams.setScrollFlags(0);
3108 tabsLayoutParams.setScrollFlags(0);
3110 // Expand the app bar if it is currently collapsed.
3111 appBarLayout.setExpanded(true);
3114 // Apply the modified layout parameters.
3115 swipeRefreshLayout.setLayoutParams(swipeRefreshLayoutParams);
3116 toolbar.setLayoutParams(toolbarLayoutParams);
3117 findOnPageLinearLayout.setLayoutParams(findOnPageLayoutParams);
3118 tabsLinearLayout.setLayoutParams(tabsLayoutParams);
3120 // Set the app bar scrolling for each WebView.
3121 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3122 // Get the WebView tab fragment.
3123 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3125 // Get the fragment view.
3126 View fragmentView = webViewTabFragment.getView();
3128 // Only modify the WebViews if they exist.
3129 if (fragmentView != null) {
3130 // Get the nested scroll WebView from the tab fragment.
3131 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3133 // Set the app bar scrolling.
3134 nestedScrollWebView.setNestedScrollingEnabled(scrollAppBar);
3138 // Update the full screen browsing mode settings.
3139 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
3140 // Update the visibility of the app bar, which might have changed in the settings.
3142 // Hide the tab linear layout.
3143 tabsLinearLayout.setVisibility(View.GONE);
3145 // Hide the action bar.
3148 // Show the tab linear layout.
3149 tabsLinearLayout.setVisibility(View.VISIBLE);
3151 // Show the action bar.
3155 // Hide the banner ad in the free flavor.
3156 if (BuildConfig.FLAVOR.contentEquals("free")) {
3157 AdHelper.hideAd(findViewById(R.id.adview));
3160 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
3161 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3163 /* Hide the system bars.
3164 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3165 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
3166 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3167 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3169 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
3170 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3171 } else { // Privacy Browser is not in full screen browsing mode.
3172 // 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.
3173 inFullScreenBrowsingMode = false;
3175 // Show the tab linear layout.
3176 tabsLinearLayout.setVisibility(View.VISIBLE);
3178 // Show the action bar.
3181 // Show the banner ad in the free flavor.
3182 if (BuildConfig.FLAVOR.contentEquals("free")) {
3183 // Initialize the ads. If this isn't the first run, `loadAd()` will be automatically called instead.
3184 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getSupportFragmentManager(), getString(R.string.google_app_id), getString(R.string.ad_unit_id));
3187 // Remove the `SYSTEM_UI` flags from the root frame layout.
3188 rootFrameLayout.setSystemUiVisibility(0);
3190 // Add the translucent status flag.
3191 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3196 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
3197 @SuppressLint("SetJavaScriptEnabled")
3198 private boolean applyDomainSettings(NestedScrollWebView nestedScrollWebView, String url, boolean resetTab, boolean reloadWebsite) {
3199 // Store a copy of the current user agent to track changes for the return boolean.
3200 String initialUserAgent = nestedScrollWebView.getSettings().getUserAgentString();
3202 // Parse the URL into a URI.
3203 Uri uri = Uri.parse(url);
3205 // Extract the domain from `uri`.
3206 String newHostName = uri.getHost();
3208 // Strings don't like to be null.
3209 if (newHostName == null) {
3213 // 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.
3214 if (!nestedScrollWebView.getCurrentDomainName().equals(newHostName)) {
3215 // Set the new host name as the current domain name.
3216 nestedScrollWebView.setCurrentDomainName(newHostName);
3218 // Reset the ignoring of pinned domain information.
3219 nestedScrollWebView.setIgnorePinnedDomainInformation(false);
3221 // Clear any pinned SSL certificate or IP addresses.
3222 nestedScrollWebView.clearPinnedSslCertificate();
3223 nestedScrollWebView.clearPinnedIpAddresses();
3225 // Reset the favorite icon if specified.
3227 // Initialize the favorite icon.
3228 nestedScrollWebView.initializeFavoriteIcon();
3230 // Get the current page position.
3231 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
3233 // Get a handle for the tab layout.
3234 TabLayout tabLayout = findViewById(R.id.tablayout);
3236 // Get the corresponding tab.
3237 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
3239 // Update the tab if it isn't null, which sometimes happens when restarting from the background.
3241 // Get the tab custom view.
3242 View tabCustomView = tab.getCustomView();
3244 // Remove the warning below that the tab custom view might be null.
3245 assert tabCustomView != null;
3247 // Get the tab views.
3248 ImageView tabFavoriteIconImageView = tabCustomView.findViewById(R.id.favorite_icon_imageview);
3249 TextView tabTitleTextView = tabCustomView.findViewById(R.id.title_textview);
3251 // Set the default favorite icon as the favorite icon for this tab.
3252 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(nestedScrollWebView.getFavoriteOrDefaultIcon(), 64, 64, true));
3254 // Set the loading title text.
3255 tabTitleTextView.setText(R.string.loading);
3259 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3260 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3262 // Get a full cursor from `domainsDatabaseHelper`.
3263 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3265 // Initialize `domainSettingsSet`.
3266 Set<String> domainSettingsSet = new HashSet<>();
3268 // Get the domain name column index.
3269 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3271 // Populate `domainSettingsSet`.
3272 for (int i = 0; i < domainNameCursor.getCount(); i++) {
3273 // Move `domainsCursor` to the current row.
3274 domainNameCursor.moveToPosition(i);
3276 // Store the domain name in `domainSettingsSet`.
3277 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3280 // Close `domainNameCursor.
3281 domainNameCursor.close();
3283 // Initialize the domain name in database variable.
3284 String domainNameInDatabase = null;
3286 // Check the hostname against the domain settings set.
3287 if (domainSettingsSet.contains(newHostName)) { // The hostname is contained in the domain settings set.
3288 // Record the domain name in the database.
3289 domainNameInDatabase = newHostName;
3291 // Set the domain settings applied tracker to true.
3292 nestedScrollWebView.setDomainSettingsApplied(true);
3293 } else { // The hostname is not contained in the domain settings set.
3294 // Set the domain settings applied tracker to false.
3295 nestedScrollWebView.setDomainSettingsApplied(false);
3298 // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3299 while (!nestedScrollWebView.getDomainSettingsApplied() && newHostName.contains(".")) { // Stop checking if domain settings are already applied or there are no more `.` in the host name.
3300 if (domainSettingsSet.contains("*." + newHostName)) { // Check the host name prepended by `*.`.
3301 // Set the domain settings applied tracker to true.
3302 nestedScrollWebView.setDomainSettingsApplied(true);
3304 // Store the applied domain names as it appears in the database.
3305 domainNameInDatabase = "*." + newHostName;
3308 // Strip out the lowest subdomain of of the host name.
3309 newHostName = newHostName.substring(newHostName.indexOf(".") + 1);
3313 // Get a handle for the shared preferences.
3314 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3316 // Store the general preference information.
3317 String defaultFontSizeString = sharedPreferences.getString("font_size", getString(R.string.font_size_default_value));
3318 String defaultUserAgentName = sharedPreferences.getString("user_agent", getString(R.string.user_agent_default_value));
3319 boolean defaultSwipeToRefresh = sharedPreferences.getBoolean("swipe_to_refresh", true);
3320 boolean displayWebpageImages = sharedPreferences.getBoolean("display_webpage_images", true);
3321 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
3323 // Get a handle for the cookie manager.
3324 CookieManager cookieManager = CookieManager.getInstance();
3326 // Get handles for the views.
3327 RelativeLayout urlRelativeLayout = findViewById(R.id.url_relativelayout);
3328 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
3330 // Initialize the user agent array adapter and string array.
3331 ArrayAdapter<CharSequence> userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item);
3332 String[] userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
3334 if (nestedScrollWebView.getDomainSettingsApplied()) { // The url has custom domain settings.
3335 // Get a cursor for the current host and move it to the first position.
3336 Cursor currentDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3337 currentDomainSettingsCursor.moveToFirst();
3339 // Get the settings from the cursor.
3340 nestedScrollWebView.setDomainSettingsDatabaseId(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3341 nestedScrollWebView.setDomainSettingsJavaScriptEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3342 nestedScrollWebView.setAcceptFirstPartyCookies(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3343 boolean domainThirdPartyCookiesEnabled = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3344 nestedScrollWebView.getSettings().setDomStorageEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3345 // Form data can be removed once the minimum API >= 26.
3346 boolean saveFormData = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3347 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASY_LIST,
3348 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3349 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASY_PRIVACY,
3350 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3351 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST,
3352 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3353 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST,
3354 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3355 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRA_PRIVACY,
3356 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_ULTRAPRIVACY)) == 1);
3357 nestedScrollWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS,
3358 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
3359 String userAgentName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3360 int fontSize = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3361 int swipeToRefreshInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
3362 int nightModeInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
3363 int displayWebpageImagesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3364 boolean pinnedSslCertificate = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3365 String pinnedSslIssuedToCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3366 String pinnedSslIssuedToOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3367 String pinnedSslIssuedToUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3368 String pinnedSslIssuedByCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3369 String pinnedSslIssuedByOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3370 String pinnedSslIssuedByUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3371 boolean pinnedIpAddresses = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_IP_ADDRESSES)) == 1);
3372 String pinnedHostIpAddresses = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.IP_ADDRESSES));
3374 // Create the pinned SSL date variables.
3375 Date pinnedSslStartDate;
3376 Date pinnedSslEndDate;
3378 // 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.
3379 if (currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
3380 pinnedSslStartDate = null;
3382 pinnedSslStartDate = new Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
3385 // 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.
3386 if (currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
3387 pinnedSslEndDate = null;
3389 pinnedSslEndDate = new Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
3392 // If there is a pinned SSL certificate, store it in the WebView.
3393 if (pinnedSslCertificate) {
3394 nestedScrollWebView.setPinnedSslCertificate(pinnedSslIssuedToCName, pinnedSslIssuedToOName, pinnedSslIssuedToUName, pinnedSslIssuedByCName, pinnedSslIssuedByOName, pinnedSslIssuedByUName,
3395 pinnedSslStartDate, pinnedSslEndDate);
3398 // If there is a pinned IP address, store it in the WebView.
3399 if (pinnedIpAddresses) {
3400 nestedScrollWebView.setPinnedIpAddresses(pinnedHostIpAddresses);
3403 // Set night mode according to the night mode int.
3404 switch (nightModeInt) {
3405 case DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT:
3406 // Set night mode according to the current default.
3407 nestedScrollWebView.setNightMode(sharedPreferences.getBoolean("night_mode", false));
3410 case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
3411 // Enable night mode.
3412 nestedScrollWebView.setNightMode(true);
3415 case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
3416 // Disable night mode.
3417 nestedScrollWebView.setNightMode(false);
3421 // Enable JavaScript if night mode is enabled.
3422 if (nestedScrollWebView.getNightMode()) {
3423 // Enable JavaScript.
3424 nestedScrollWebView.getSettings().setJavaScriptEnabled(true);
3426 // Set JavaScript according to the domain settings.
3427 nestedScrollWebView.getSettings().setJavaScriptEnabled(nestedScrollWebView.getDomainSettingsJavaScriptEnabled());
3430 // Close the current host domain settings cursor.
3431 currentDomainSettingsCursor.close();
3433 // Apply the domain settings.
3434 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptFirstPartyCookies());
3436 // Set third-party cookies status if API >= 21.
3437 if (Build.VERSION.SDK_INT >= 21) {
3438 cookieManager.setAcceptThirdPartyCookies(nestedScrollWebView, domainThirdPartyCookiesEnabled);
3441 // Apply the form data setting if the API < 26.
3442 if (Build.VERSION.SDK_INT < 26) {
3443 nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
3446 // Apply the font size.
3447 if (fontSize == 0) { // Apply the default font size.
3448 nestedScrollWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3449 } else { // Apply the specified font size.
3450 nestedScrollWebView.getSettings().setTextZoom(fontSize);
3453 // 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.
3454 // <https://redmine.stoutner.com/issues/160>
3455 if (nestedScrollWebView.getProgress() == 100) { // A URL is not loading.
3456 // Set the user agent.
3457 if (userAgentName.equals(getString(R.string.system_default_user_agent))) { // Use the system default user agent.
3458 // Get the array position of the default user agent name.
3459 int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3461 // Set the user agent according to the system default.
3462 switch (defaultUserAgentArrayPosition) {
3463 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
3464 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3465 nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
3468 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3469 // Set the user agent to `""`, which uses the default value.
3470 nestedScrollWebView.getSettings().setUserAgentString("");
3473 case SETTINGS_CUSTOM_USER_AGENT:
3474 // Set the default custom user agent.
3475 nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
3479 // Get the user agent string from the user agent data array
3480 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
3482 } else { // Set the user agent according to the stored name.
3483 // Get the array position of the user agent name.
3484 int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
3486 switch (userAgentArrayPosition) {
3487 case UNRECOGNIZED_USER_AGENT: // The user agent name contains a custom user agent.
3488 nestedScrollWebView.getSettings().setUserAgentString(userAgentName);
3491 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3492 // Set the user agent to `""`, which uses the default value.
3493 nestedScrollWebView.getSettings().setUserAgentString("");
3497 // Get the user agent string from the user agent data array.
3498 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3503 // Set swipe to refresh.
3504 switch (swipeToRefreshInt) {
3505 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_SYSTEM_DEFAULT:
3506 // Store the swipe to refresh status in the nested scroll WebView.
3507 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
3509 // 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.
3510 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
3513 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_ENABLED:
3514 // Store the swipe to refresh status in the nested scroll WebView.
3515 nestedScrollWebView.setSwipeToRefresh(true);
3517 // Enable swipe to refresh. This can be removed once the minimum API >= 23 because it is continuously set by an on scroll change listener.
3518 swipeRefreshLayout.setEnabled(true);
3521 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_DISABLED:
3522 // Store the swipe to refresh status in the nested scroll WebView.
3523 nestedScrollWebView.setSwipeToRefresh(false);
3525 // Disable swipe to refresh. This can be removed once the minimum API >= 23 because it is continuously set by an on scroll change listener.
3526 swipeRefreshLayout.setEnabled(false);
3529 // Set the loading of webpage images.
3530 switch (displayWebpageImagesInt) {
3531 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
3532 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
3535 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
3536 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(true);
3539 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
3540 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(false);
3544 // 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.
3546 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
3548 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
3550 } else { // The new URL does not have custom domain settings. Load the defaults.
3551 // Store the values from the shared preferences.
3552 boolean defaultJavaScriptEnabled = sharedPreferences.getBoolean("javascript", false);
3553 nestedScrollWebView.setAcceptFirstPartyCookies(sharedPreferences.getBoolean("first_party_cookies", false));
3554 boolean defaultThirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies", false);
3555 nestedScrollWebView.getSettings().setDomStorageEnabled(sharedPreferences.getBoolean("dom_storage", false));
3556 boolean saveFormData = sharedPreferences.getBoolean("save_form_data", false); // Form data can be removed once the minimum API >= 26.
3557 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASY_LIST, sharedPreferences.getBoolean("easylist", true));
3558 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASY_PRIVACY, sharedPreferences.getBoolean("easyprivacy", true));
3559 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, sharedPreferences.getBoolean("fanboys_annoyance_list", true));
3560 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, sharedPreferences.getBoolean("fanboys_social_blocking_list", true));
3561 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRA_PRIVACY, sharedPreferences.getBoolean("ultraprivacy", true));
3562 nestedScrollWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, sharedPreferences.getBoolean("block_all_third_party_requests", false));
3563 nestedScrollWebView.setNightMode(sharedPreferences.getBoolean("night_mode", false));
3565 // Enable JavaScript if night mode is enabled.
3566 if (nestedScrollWebView.getNightMode()) {
3567 // Enable JavaScript.
3568 nestedScrollWebView.getSettings().setJavaScriptEnabled(true);
3570 // Set JavaScript according to the domain settings.
3571 nestedScrollWebView.getSettings().setJavaScriptEnabled(defaultJavaScriptEnabled);
3574 // Apply the default settings.
3575 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptFirstPartyCookies());
3576 nestedScrollWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3578 // Apply the form data setting if the API < 26.
3579 if (Build.VERSION.SDK_INT < 26) {
3580 nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
3583 // Store the swipe to refresh status in the nested scroll WebView.
3584 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
3586 // Apply swipe to refresh according to the default.
3587 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
3589 // Reset the pinned variables.
3590 nestedScrollWebView.setDomainSettingsDatabaseId(-1);
3592 // Set third-party cookies status if API >= 21.
3593 if (Build.VERSION.SDK_INT >= 21) {
3594 cookieManager.setAcceptThirdPartyCookies(nestedScrollWebView, defaultThirdPartyCookiesEnabled);
3597 // 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.
3598 // <https://redmine.stoutner.com/issues/160>
3599 if (nestedScrollWebView.getProgress() == 100) { // A URL is not loading.
3600 // Get the array position of the user agent name.
3601 int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3603 // Set the user agent.
3604 switch (userAgentArrayPosition) {
3605 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
3606 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3607 nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
3610 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3611 // Set the user agent to `""`, which uses the default value.
3612 nestedScrollWebView.getSettings().setUserAgentString("");
3615 case SETTINGS_CUSTOM_USER_AGENT:
3616 // Set the default custom user agent.
3617 nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
3621 // Get the user agent string from the user agent data array
3622 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3626 // Set the loading of webpage images.
3627 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
3629 // Set a transparent background on URL edit text. The deprecated `getResources().getDrawable()` must be used until the minimum API >= 21.
3630 urlRelativeLayout.setBackground(getResources().getDrawable(R.color.transparent));
3633 // Close the domains database helper.
3634 domainsDatabaseHelper.close();
3636 // Update the privacy icons.
3637 updatePrivacyIcons(true);
3640 // Reload the website if returning from the Domains activity.
3641 if (reloadWebsite) {
3642 nestedScrollWebView.reload();
3645 // Return the user agent changed status.
3646 return !nestedScrollWebView.getSettings().getUserAgentString().equals(initialUserAgent);
3649 private void applyProxyThroughOrbot(boolean reloadWebsite) {
3650 // Get a handle for the shared preferences.
3651 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3653 // Get the search and theme preferences.
3654 String torSearchString = sharedPreferences.getString("tor_search", getString(R.string.tor_search_default_value));
3655 String torSearchCustomUrlString = sharedPreferences.getString("tor_search_custom_url", getString(R.string.tor_search_custom_url_default_value));
3656 String searchString = sharedPreferences.getString("search", getString(R.string.search_default_value));
3657 String searchCustomUrlString = sharedPreferences.getString("search_custom_url", getString(R.string.search_custom_url_default_value));
3658 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
3660 // Get a handle for the app bar layout.
3661 AppBarLayout appBarLayout = findViewById(R.id.appbar_layout);
3663 // Set the homepage, search, and proxy options.
3664 if (proxyThroughOrbot) { // Set the Tor options.
3665 // Set the search URL.
3666 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
3667 searchURL = torSearchCustomUrlString;
3668 } else { // Use the string from the pre-built list.
3669 searchURL = torSearchString;
3672 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
3673 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
3675 // Set the app bar background to indicate proxying through Orbot is enabled.
3677 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
3679 appBarLayout.setBackgroundResource(R.color.blue_50);
3682 // Check to see if Orbot is ready.
3683 if (!orbotStatus.equals("ON")) { // Orbot is not ready.
3684 // Set `waitingForOrbot`.
3685 waitingForOrbot = true;
3687 // Disable the wide view port so that the waiting for Orbot text is displayed correctly.
3688 currentWebView.getSettings().setUseWideViewPort(false);
3690 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
3691 currentWebView.loadData("<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>", "text/html", null);
3692 } else if (reloadWebsite) { // Orbot is ready and the website should be reloaded.
3693 // Reload the website.
3694 currentWebView.reload();
3696 } else { // Set the non-Tor options.
3697 // Set the search URL.
3698 if (searchString.equals("Custom URL")) { // Get the custom URL string.
3699 searchURL = searchCustomUrlString;
3700 } else { // Use the string from the pre-built list.
3701 searchURL = searchString;
3704 // Reset the proxy to default. The host is `""` and the port is `"0"`.
3705 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
3707 // Set the default app bar layout background.
3709 appBarLayout.setBackgroundResource(R.color.gray_900);
3711 appBarLayout.setBackgroundResource(R.color.gray_100);
3714 // Reset `waitingForOrbot.
3715 waitingForOrbot = false;
3717 // Reload the WebViews if requested.
3718 if (reloadWebsite) {
3719 // Reload the WebViews.
3720 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3721 // Get the WebView tab fragment.
3722 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3724 // Get the fragment view.
3725 View fragmentView = webViewTabFragment.getView();
3727 // Only reload the WebViews if they exist.
3728 if (fragmentView != null) {
3729 // Get the nested scroll WebView from the tab fragment.
3730 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3732 // Reload the WebView.
3733 nestedScrollWebView.reload();
3740 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
3741 // Only update the privacy icons if the options menu and the current WebView have already been populated.
3742 if ((optionsMenu != null) && (currentWebView != null)) {
3743 // Get a handle for the shared preferences.
3744 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3746 // Get the theme and screenshot preferences.
3747 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
3749 // Get handles for the menu items.
3750 MenuItem privacyMenuItem = optionsMenu.findItem(R.id.toggle_javascript);
3751 MenuItem firstPartyCookiesMenuItem = optionsMenu.findItem(R.id.toggle_first_party_cookies);
3752 MenuItem domStorageMenuItem = optionsMenu.findItem(R.id.toggle_dom_storage);
3753 MenuItem refreshMenuItem = optionsMenu.findItem(R.id.refresh);
3755 // Update the privacy icon.
3756 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is enabled.
3757 privacyMenuItem.setIcon(R.drawable.javascript_enabled);
3758 } else if (currentWebView.getAcceptFirstPartyCookies()) { // JavaScript is disabled but cookies are enabled.
3759 privacyMenuItem.setIcon(R.drawable.warning);
3760 } else { // All the dangerous features are disabled.
3761 privacyMenuItem.setIcon(R.drawable.privacy_mode);
3764 // Update the first-party cookies icon.
3765 if (currentWebView.getAcceptFirstPartyCookies()) { // First-party cookies are enabled.
3766 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
3767 } else { // First-party cookies are disabled.
3769 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_dark);
3771 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_light);
3775 // Update the DOM storage icon.
3776 if (currentWebView.getSettings().getJavaScriptEnabled() && currentWebView.getSettings().getDomStorageEnabled()) { // Both JavaScript and DOM storage are enabled.
3777 domStorageMenuItem.setIcon(R.drawable.dom_storage_enabled);
3778 } else if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is enabled but DOM storage is disabled.
3780 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
3782 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
3784 } else { // JavaScript is disabled, so DOM storage is ghosted.
3786 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
3788 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
3792 // Update the refresh icon.
3794 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
3796 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
3799 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
3800 if (runInvalidateOptionsMenu) {
3801 invalidateOptionsMenu();
3806 private void openUrlWithExternalApp(String url) {
3807 // Create a download intent. Not specifying the action type will display the maximum number of options.
3808 Intent downloadIntent = new Intent();
3810 // Set the URI and the MIME type. Specifying `text/html` displays a good number of options.
3811 downloadIntent.setDataAndType(Uri.parse(url), "text/html");
3813 // Flag the intent to open in a new task.
3814 downloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3816 // Show the chooser.
3817 startActivity(Intent.createChooser(downloadIntent, getString(R.string.open_with)));
3820 private void highlightUrlText() {
3821 // Get a handle for the URL edit text.
3822 EditText urlEditText = findViewById(R.id.url_edittext);
3824 // Only highlight the URL text if the box is not currently selected.
3825 if (!urlEditText.hasFocus()) {
3826 // Get the URL string.
3827 String urlString = urlEditText.getText().toString();
3829 // Highlight the URL according to the protocol.
3830 if (urlString.startsWith("file://")) { // This is a file URL.
3831 // De-emphasize only the protocol.
3832 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3833 } else if (urlString.startsWith("content://")) {
3834 // De-emphasize only the protocol.
3835 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 10, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3836 } else { // This is a web URL.
3837 // Get the index of the `/` immediately after the domain name.
3838 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
3840 // Create a base URL string.
3843 // Get the base URL.
3844 if (endOfDomainName > 0) { // There is at least one character after the base URL.
3845 // Get the base URL.
3846 baseUrl = urlString.substring(0, endOfDomainName);
3847 } else { // There are no characters after the base URL.
3848 // Set the base URL to be the entire URL string.
3849 baseUrl = urlString;
3852 // Get the index of the last `.` in the domain.
3853 int lastDotIndex = baseUrl.lastIndexOf(".");
3855 // Get the index of the penultimate `.` in the domain.
3856 int penultimateDotIndex = baseUrl.lastIndexOf(".", lastDotIndex - 1);
3858 // Markup the beginning of the URL.
3859 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
3860 urlEditText.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3862 // De-emphasize subdomains.
3863 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
3864 urlEditText.getText().setSpan(initialGrayColorSpan, 7, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3866 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
3867 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
3868 // De-emphasize the protocol and the additional subdomains.
3869 urlEditText.getText().setSpan(initialGrayColorSpan, 0, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3870 } else { // There is only one subdomain in the domain name.
3871 // De-emphasize only the protocol.
3872 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3876 // De-emphasize the text after the domain name.
3877 if (endOfDomainName > 0) {
3878 urlEditText.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3884 private void loadBookmarksFolder() {
3885 // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
3886 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
3888 // Populate the bookmarks cursor adapter. `this` specifies the `Context`. `false` disables `autoRequery`.
3889 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
3891 public View newView(Context context, Cursor cursor, ViewGroup parent) {
3892 // Inflate the individual item layout. `false` does not attach it to the root.
3893 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
3897 public void bindView(View view, Context context, Cursor cursor) {
3898 // Get handles for the views.
3899 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
3900 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
3902 // Get the favorite icon byte array from the cursor.
3903 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
3905 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
3906 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
3908 // Display the bitmap in `bookmarkFavoriteIcon`.
3909 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
3911 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
3912 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
3913 bookmarkNameTextView.setText(bookmarkNameString);
3915 // Make the font bold for folders.
3916 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
3917 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
3918 } else { // Reset the font to default for normal bookmarks.
3919 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
3924 // Get a handle for the bookmarks list view.
3925 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
3927 // Populate the list view with the adapter.
3928 bookmarksListView.setAdapter(bookmarksCursorAdapter);
3930 // Get a handle for the bookmarks title text view.
3931 TextView bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
3933 // Set the bookmarks drawer title.
3934 if (currentBookmarksFolder.isEmpty()) {
3935 bookmarksTitleTextView.setText(R.string.bookmarks);
3937 bookmarksTitleTextView.setText(currentBookmarksFolder);
3941 private void openWithApp(String url) {
3942 // Create the open with intent with `ACTION_VIEW`.
3943 Intent openWithAppIntent = new Intent(Intent.ACTION_VIEW);
3945 // Set the URI but not the MIME type. This should open all available apps.
3946 openWithAppIntent.setData(Uri.parse(url));
3948 // Flag the intent to open in a new task.
3949 openWithAppIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3951 // Show the chooser.
3952 startActivity(openWithAppIntent);
3955 private void openWithBrowser(String url) {
3956 // Create the open with intent with `ACTION_VIEW`.
3957 Intent openWithBrowserIntent = new Intent(Intent.ACTION_VIEW);
3959 // Set the URI and the MIME type. `"text/html"` should load browser options.
3960 openWithBrowserIntent.setDataAndType(Uri.parse(url), "text/html");
3962 // Flag the intent to open in a new task.
3963 openWithBrowserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3965 // Show the chooser.
3966 startActivity(openWithBrowserIntent);
3969 private String sanitizeUrl(String url) {
3970 // Sanitize Google Analytics.
3971 if (sanitizeGoogleAnalytics) {
3973 if (url.contains("?utm_")) {
3974 url = url.substring(0, url.indexOf("?utm_"));
3978 if (url.contains("&utm_")) {
3979 url = url.substring(0, url.indexOf("&utm_"));
3983 // Return the sanitized URL.
3987 public void addTab(View view) {
3988 // Add a new tab with a blank URL.
3992 private void addNewTab(String url) {
3993 // Sanitize the URL.
3994 url = sanitizeUrl(url);
3996 // Get a handle for the tab layout and the view pager.
3997 TabLayout tabLayout = findViewById(R.id.tablayout);
3998 ViewPager webViewPager = findViewById(R.id.webviewpager);
4000 // Get the new page number. The page numbers are 0 indexed, so the new page number will match the current count.
4001 int newTabNumber = tabLayout.getTabCount();
4004 tabLayout.addTab(tabLayout.newTab());
4007 TabLayout.Tab newTab = tabLayout.getTabAt(newTabNumber);
4009 // Remove the lint warning below that the current tab might be null.
4010 assert newTab != null;
4012 // Set a custom view on the new tab.
4013 newTab.setCustomView(R.layout.tab_custom_view);
4015 // Add the new WebView page.
4016 webViewPagerAdapter.addPage(newTabNumber, webViewPager, url);
4019 public void closeTab(View view) {
4020 // Get a handle for the tab layout.
4021 TabLayout tabLayout = findViewById(R.id.tablayout);
4023 // Run the command according to the number of tabs.
4024 if (tabLayout.getTabCount() > 1) { // There is more than one tab open.
4025 // Close the current tab.
4027 } else { // There is only one tab open.
4032 private void closeCurrentTab() {
4033 // Get handles for the views.
4034 AppBarLayout appBarLayout = findViewById(R.id.appbar_layout);
4035 TabLayout tabLayout = findViewById(R.id.tablayout);
4036 ViewPager webViewPager = findViewById(R.id.webviewpager);
4038 // Get the current tab number.
4039 int currentTabNumber = tabLayout.getSelectedTabPosition();
4041 // Delete the current tab.
4042 tabLayout.removeTabAt(currentTabNumber);
4044 // 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.
4045 if (webViewPagerAdapter.deletePage(currentTabNumber, webViewPager)) {
4046 setCurrentWebView(currentTabNumber);
4049 // Expand the app bar if it is currently collapsed.
4050 appBarLayout.setExpanded(true);
4053 private void clearAndExit() {
4054 // Get a handle for the shared preferences.
4055 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4057 // Close the bookmarks cursor and database.
4058 bookmarksCursor.close();
4059 bookmarksDatabaseHelper.close();
4061 // Get the status of the clear everything preference.
4062 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
4064 // Get a handle for the runtime.
4065 Runtime runtime = Runtime.getRuntime();
4067 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
4068 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
4069 String privateDataDirectoryString = getApplicationInfo().dataDir;
4072 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
4073 // The command to remove cookies changed slightly in API 21.
4074 if (Build.VERSION.SDK_INT >= 21) {
4075 CookieManager.getInstance().removeAllCookies(null);
4077 CookieManager.getInstance().removeAllCookie();
4080 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4082 // Two commands must be used because `Runtime.exec()` does not like `*`.
4083 Process deleteCookiesProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
4084 Process deleteCookiesJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
4086 // Wait until the processes have finished.
4087 deleteCookiesProcess.waitFor();
4088 deleteCookiesJournalProcess.waitFor();
4089 } catch (Exception exception) {
4090 // Do nothing if an error is thrown.
4094 // Clear DOM storage.
4095 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
4096 // Ask `WebStorage` to clear the DOM storage.
4097 WebStorage webStorage = WebStorage.getInstance();
4098 webStorage.deleteAllData();
4100 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4102 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4103 Process deleteLocalStorageProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
4105 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
4106 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
4107 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
4108 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
4109 Process deleteDatabaseProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
4111 // Wait until the processes have finished.
4112 deleteLocalStorageProcess.waitFor();
4113 deleteIndexProcess.waitFor();
4114 deleteQuotaManagerProcess.waitFor();
4115 deleteQuotaManagerJournalProcess.waitFor();
4116 deleteDatabaseProcess.waitFor();
4117 } catch (Exception exception) {
4118 // Do nothing if an error is thrown.
4122 // Clear form data if the API < 26.
4123 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
4124 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
4125 webViewDatabase.clearFormData();
4127 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4129 // A string array must be used because the database contains a space and `Runtime.exec` will not otherwise escape the string correctly.
4130 Process deleteWebDataProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
4131 Process deleteWebDataJournalProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
4133 // Wait until the processes have finished.
4134 deleteWebDataProcess.waitFor();
4135 deleteWebDataJournalProcess.waitFor();
4136 } catch (Exception exception) {
4137 // Do nothing if an error is thrown.
4142 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
4143 // Clear the cache from each WebView.
4144 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4145 // Get the WebView tab fragment.
4146 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4148 // Get the fragment view.
4149 View fragmentView = webViewTabFragment.getView();
4151 // Only clear the cache if the WebView exists.
4152 if (fragmentView != null) {
4153 // Get the nested scroll WebView from the tab fragment.
4154 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4156 // Clear the cache for this WebView.
4157 nestedScrollWebView.clearCache(true);
4161 // Manually delete the cache directories.
4163 // Delete the main cache directory.
4164 Process deleteCacheProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/cache");
4166 // Delete the secondary `Service Worker` cache directory.
4167 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4168 Process deleteServiceWorkerProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
4170 // Wait until the processes have finished.
4171 deleteCacheProcess.waitFor();
4172 deleteServiceWorkerProcess.waitFor();
4173 } catch (Exception exception) {
4174 // Do nothing if an error is thrown.
4178 // Wipe out each WebView.
4179 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4180 // Get the WebView tab fragment.
4181 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4183 // Get the fragment view.
4184 View fragmentView = webViewTabFragment.getView();
4186 // Only wipe out the WebView if it exists.
4187 if (fragmentView != null) {
4188 // Get the nested scroll WebView from the tab fragment.
4189 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4191 // Clear SSL certificate preferences for this WebView.
4192 nestedScrollWebView.clearSslPreferences();
4194 // Clear the back/forward history for this WebView.
4195 nestedScrollWebView.clearHistory();
4197 // Destroy the internal state of `mainWebView`.
4198 nestedScrollWebView.destroy();
4202 // Clear the custom headers.
4203 customHeaders.clear();
4205 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
4206 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
4207 if (clearEverything) {
4209 // Delete the folder.
4210 Process deleteAppWebviewProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
4212 // Wait until the process has finished.
4213 deleteAppWebviewProcess.waitFor();
4214 } catch (Exception exception) {
4215 // Do nothing if an error is thrown.
4219 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
4220 if (Build.VERSION.SDK_INT >= 21) {
4221 finishAndRemoveTask();
4226 // Remove the terminated program from RAM. The status code is `0`.
4230 private void setCurrentWebView(int pageNumber) {
4231 // Get a handle for the shared preferences.
4232 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4234 // Get the theme preference.
4235 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
4237 // Get handles for the URL views.
4238 RelativeLayout urlRelativeLayout = findViewById(R.id.url_relativelayout);
4239 EditText urlEditText = findViewById(R.id.url_edittext);
4240 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
4242 //Stop the swipe to refresh indicator if it is running
4243 swipeRefreshLayout.setRefreshing(false);
4245 // Get the WebView tab fragment.
4246 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(pageNumber);
4248 // Get the fragment view.
4249 View fragmentView = webViewTabFragment.getView();
4251 // Set the current WebView if the fragment view is not null.
4252 if (fragmentView != null) {
4253 // Store the current WebView.
4254 currentWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4256 // Update the status of swipe to refresh.
4257 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
4258 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.
4259 // Enable the swipe refresh layout if the WebView is scrolled all the way to the top.
4260 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
4262 // Enable the swipe refresh layout.
4263 swipeRefreshLayout.setEnabled(true);
4265 } else { // Swipe to refresh is disabled.
4266 // Disable the swipe refresh layout.
4267 swipeRefreshLayout.setEnabled(false);
4270 // Get a handle for the cookie manager.
4271 CookieManager cookieManager = CookieManager.getInstance();
4273 // Set the first-party cookie status.
4274 cookieManager.setAcceptCookie(currentWebView.getAcceptFirstPartyCookies());
4276 // Update the privacy icons. `true` redraws the icons in the app bar.
4277 updatePrivacyIcons(true);
4279 // Get a handle for the input method manager.
4280 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
4282 // Remove the lint warning below that the input method manager might be null.
4283 assert inputMethodManager != null;
4285 // Get the current URL.
4286 String url = currentWebView.getUrl();
4288 // Update the URL edit text if not loading a new intent. Otherwise, this will be handled by `onPageStarted()` (if called) and `onPageFinished()`.
4289 if (!loadingNewIntent) { // A new intent is not being loaded.
4290 if ((url == null) || url.equals("about:blank")) { // The WebView is blank.
4291 // Display the hint in the URL edit text.
4292 urlEditText.setText("");
4294 // Request focus for the URL text box.
4295 urlEditText.requestFocus();
4297 // Display the keyboard.
4298 inputMethodManager.showSoftInput(urlEditText, 0);
4299 } else { // The WebView has a loaded URL.
4300 // Clear the focus from the URL text box.
4301 urlEditText.clearFocus();
4303 // Hide the soft keyboard.
4304 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
4306 // Display the current URL in the URL text box.
4307 urlEditText.setText(url);
4309 // Highlight the URL text.
4312 } else { // A new intent is being loaded.
4313 // Reset the loading new intent tracker.
4314 loadingNewIntent = false;
4317 // Set the background to indicate the domain settings status.
4318 if (currentWebView.getDomainSettingsApplied()) {
4319 // 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.
4321 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
4323 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
4326 urlRelativeLayout.setBackground(getResources().getDrawable(R.color.transparent));
4332 public void initializeWebView(NestedScrollWebView nestedScrollWebView, int pageNumber, ProgressBar progressBar, String url) {
4333 // Get handles for the activity views.
4334 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
4335 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
4336 RelativeLayout mainContentRelativeLayout = findViewById(R.id.main_content_relativelayout);
4337 ActionBar actionBar = getSupportActionBar();
4338 LinearLayout tabsLinearLayout = findViewById(R.id.tabs_linearlayout);
4339 EditText urlEditText = findViewById(R.id.url_edittext);
4340 TabLayout tabLayout = findViewById(R.id.tablayout);
4341 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
4343 // Remove the incorrect lint warning below that the action bar might be null.
4344 assert actionBar != null;
4346 // Get a handle for the activity
4347 Activity activity = this;
4349 // Get a handle for the input method manager.
4350 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
4352 // Instantiate the blocklist helper.
4353 BlockListHelper blockListHelper = new BlockListHelper();
4355 // Remove the lint warning below that the input method manager might be null.
4356 assert inputMethodManager != null;
4358 // Get a handle for the shared preferences.
4359 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4361 // Get the relevant preferences.
4362 boolean downloadWithExternalApp = sharedPreferences.getBoolean("download_with_external_app", false);
4364 // Initialize the favorite icon.
4365 nestedScrollWebView.initializeFavoriteIcon();
4367 // Set the app bar scrolling.
4368 nestedScrollWebView.setNestedScrollingEnabled(sharedPreferences.getBoolean("scroll_app_bar", true));
4370 // Allow pinch to zoom.
4371 nestedScrollWebView.getSettings().setBuiltInZoomControls(true);
4373 // Hide zoom controls.
4374 nestedScrollWebView.getSettings().setDisplayZoomControls(false);
4376 // Don't allow mixed content (HTTP and HTTPS) on the same website.
4377 if (Build.VERSION.SDK_INT >= 21) {
4378 nestedScrollWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW);
4381 // Set the WebView to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
4382 nestedScrollWebView.getSettings().setUseWideViewPort(true);
4384 // Set the WebView to load in overview mode (zoomed out to the maximum width).
4385 nestedScrollWebView.getSettings().setLoadWithOverviewMode(true);
4387 // Explicitly disable geolocation.
4388 nestedScrollWebView.getSettings().setGeolocationEnabled(false);
4390 // Create a double-tap gesture detector to toggle full-screen mode.
4391 GestureDetector doubleTapGestureDetector = new GestureDetector(getApplicationContext(), new GestureDetector.SimpleOnGestureListener() {
4392 // Override `onDoubleTap()`. All other events are handled using the default settings.
4394 public boolean onDoubleTap(MotionEvent event) {
4395 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
4396 // Toggle the full screen browsing mode tracker.
4397 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
4399 // Toggle the full screen browsing mode.
4400 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
4401 // Store the swipe refresh layout top padding.
4402 swipeRefreshLayoutPaddingTop = swipeRefreshLayout.getPaddingTop();
4404 // Hide the app bar if specified.
4406 // Close the find on page bar if it is visible.
4407 closeFindOnPage(null);
4409 // Hide the tab linear layout.
4410 tabsLinearLayout.setVisibility(View.GONE);
4412 // Hide the action bar.
4415 // Check to see if app bar scrolling is disabled.
4416 if (!scrollAppBar) {
4417 // Remove the padding from the top of the swipe refresh layout.
4418 swipeRefreshLayout.setPadding(0, 0, 0, 0);
4422 // Hide the banner ad in the free flavor.
4423 if (BuildConfig.FLAVOR.contentEquals("free")) {
4424 AdHelper.hideAd(findViewById(R.id.adview));
4427 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
4428 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4430 /* Hide the system bars.
4431 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4432 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4433 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4434 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4436 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
4437 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
4438 } else { // Switch to normal viewing mode.
4439 // Show the tab linear layout.
4440 tabsLinearLayout.setVisibility(View.VISIBLE);
4442 // Show the action bar.
4445 // Check to see if app bar scrolling is disabled.
4446 if (!scrollAppBar) {
4447 // Add the padding from the top of the swipe refresh layout.
4448 swipeRefreshLayout.setPadding(0, swipeRefreshLayoutPaddingTop, 0, 0);
4451 // Show the banner ad in the free flavor.
4452 if (BuildConfig.FLAVOR.contentEquals("free")) {
4454 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
4457 // Remove the `SYSTEM_UI` flags from the root frame layout.
4458 rootFrameLayout.setSystemUiVisibility(0);
4460 // Add the translucent status flag.
4461 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4464 // Consume the double-tap.
4466 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
4472 // Pass all touch events on the WebView through the double-tap gesture detector.
4473 nestedScrollWebView.setOnTouchListener((View view, MotionEvent event) -> {
4474 // Call `performClick()` on the view, which is required for accessibility.
4475 view.performClick();
4477 // Send the event to the gesture detector.
4478 return doubleTapGestureDetector.onTouchEvent(event);
4481 // Register the WebView for a context menu. This is used to see link targets and download images.
4482 registerForContextMenu(nestedScrollWebView);
4484 // Allow the downloading of files.
4485 nestedScrollWebView.setDownloadListener((String downloadUrl, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
4486 // Check if the download should be processed by an external app.
4487 if (downloadWithExternalApp) { // Download with an external app.
4488 // Create a download intent. Not specifying the action type will display the maximum number of options.
4489 Intent downloadIntent = new Intent();
4491 // Set the URI and the MIME type. Specifying `text/html` displays a good number of options.
4492 downloadIntent.setDataAndType(Uri.parse(downloadUrl), "text/html");
4494 // Flag the intent to open in a new task.
4495 downloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4497 // Show the chooser.
4498 startActivity(Intent.createChooser(downloadIntent, getString(R.string.open_with)));
4499 } else { // Download with Android's download manager.
4500 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
4501 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission has not been granted.
4502 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
4504 // Store the variables for future use by `onRequestPermissionsResult()`.
4505 this.downloadUrl = downloadUrl;
4506 downloadContentDisposition = contentDisposition;
4507 downloadContentLength = contentLength;
4509 // Show a dialog if the user has previously denied the permission.
4510 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
4511 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
4512 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
4514 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
4515 downloadLocationPermissionDialogFragment.show(getSupportFragmentManager(), getString(R.string.download_location));
4516 } else { // Show the permission request directly.
4517 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
4518 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
4520 } else { // The storage permission has already been granted.
4521 // Get a handle for the download file alert dialog.
4522 DialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(downloadUrl, contentDisposition, contentLength);
4524 // Show the download file alert dialog.
4525 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
4530 // Update the find on page count.
4531 nestedScrollWebView.setFindListener(new WebView.FindListener() {
4532 // Get a handle for `findOnPageCountTextView`.
4533 final TextView findOnPageCountTextView = findViewById(R.id.find_on_page_count_textview);
4536 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
4537 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
4538 // Set `findOnPageCountTextView` to `0/0`.
4539 findOnPageCountTextView.setText(R.string.zero_of_zero);
4540 } else if (isDoneCounting) { // There are matches.
4541 // `activeMatchOrdinal` is zero-based.
4542 int activeMatch = activeMatchOrdinal + 1;
4544 // Build the match string.
4545 String matchString = activeMatch + "/" + numberOfMatches;
4547 // Set `findOnPageCountTextView`.
4548 findOnPageCountTextView.setText(matchString);
4553 // Update the status of swipe to refresh based on the scroll position of the nested scroll WebView.
4554 // Once the minimum API >= 23 this can be replaced with `nestedScrollWebView.setOnScrollChangeListener()`.
4555 nestedScrollWebView.getViewTreeObserver().addOnScrollChangedListener(() -> {
4556 if (nestedScrollWebView.getSwipeToRefresh()) {
4557 // Only enable swipe to refresh if the WebView is scrolled to the top.
4558 swipeRefreshLayout.setEnabled(nestedScrollWebView.getScrollY() == 0);
4562 // Set the web chrome client.
4563 nestedScrollWebView.setWebChromeClient(new WebChromeClient() {
4564 // Update the progress bar when a page is loading.
4566 public void onProgressChanged(WebView view, int progress) {
4567 // Inject the night mode CSS if night mode is enabled.
4568 if (nestedScrollWebView.getNightMode()) { // Night mode is enabled.
4569 // `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
4570 // used by WordPress. `text-decoration: none` removes all text underlines. `text-shadow: none` removes text shadows, which usually have a hard coded color.
4571 // `border: none` removes all borders, which can also be used to underline text. `a {color: #1565C0}` sets links to be a dark blue.
4572 // `::selection {background: #0D47A1}' sets the text selection highlight color to be a dark blue. `!important` takes precedent over any existing sub-settings.
4573 nestedScrollWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; " +
4574 "style.innerHTML = '* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important;" +
4575 "text-shadow: none !important; border: none !important;} a {color: #1565C0 !important;} ::selection {background: #0D47A1 !important;}'; parent.appendChild(style)})()", value -> {
4576 // Initialize a handler to display `mainWebView`.
4577 Handler displayWebViewHandler = new Handler();
4579 // Setup a runnable to display `mainWebView` after a delay to allow the CSS to be applied.
4580 Runnable displayWebViewRunnable = () -> {
4581 // Only display `mainWebView` if the progress bar is gone. This prevents the display of the `WebView` while it is still loading.
4582 if (progressBar.getVisibility() == View.GONE) {
4583 nestedScrollWebView.setVisibility(View.VISIBLE);
4587 // Display the WebView after 500 milliseconds.
4588 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
4590 } else { // Night mode is disabled.
4591 // Display the nested scroll WebView if night mode is disabled.
4592 // Because of a race condition between `applyDomainSettings` and `onPageStarted`,
4593 // when night mode is set by domain settings the WebView may be hidden even if night mode is not currently enabled.
4594 nestedScrollWebView.setVisibility(View.VISIBLE);
4597 // Update the progress bar.
4598 progressBar.setProgress(progress);
4600 // Set the visibility of the progress bar.
4601 if (progress < 100) {
4602 // Show the progress bar.
4603 progressBar.setVisibility(View.VISIBLE);
4605 // Hide the progress bar.
4606 progressBar.setVisibility(View.GONE);
4608 //Stop the swipe to refresh indicator if it is running
4609 swipeRefreshLayout.setRefreshing(false);
4613 // Set the favorite icon when it changes.
4615 public void onReceivedIcon(WebView view, Bitmap icon) {
4616 // Only update the favorite icon if the website has finished loading.
4617 if (progressBar.getVisibility() == View.GONE) {
4618 // Store the new favorite icon.
4619 nestedScrollWebView.setFavoriteOrDefaultIcon(icon);
4621 // Get the current page position.
4622 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
4624 // Get the current tab.
4625 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
4627 // Check to see if the tab has been populated.
4629 // Get the custom view from the tab.
4630 View tabView = tab.getCustomView();
4632 // Check to see if the custom tab view has been populated.
4633 if (tabView != null) {
4634 // Get the favorite icon image view from the tab.
4635 ImageView tabFavoriteIconImageView = tabView.findViewById(R.id.favorite_icon_imageview);
4637 // Display the favorite icon in the tab.
4638 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
4644 // Save a copy of the title when it changes.
4646 public void onReceivedTitle(WebView view, String title) {
4647 // Get the current page position.
4648 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
4650 // Get the current tab.
4651 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
4653 // Only populate the title text view if the tab has been fully created.
4655 // Get the custom view from the tab.
4656 View tabView = tab.getCustomView();
4658 // Remove the incorrect warning below that the current tab view might be null.
4659 assert tabView != null;
4661 // Get the title text view from the tab.
4662 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
4664 // Set the title as the tab text.
4665 tabTitleTextView.setText(title);
4669 // Enter full screen video.
4671 public void onShowCustomView(View video, CustomViewCallback callback) {
4672 // Get a handle for the full screen video frame layout.
4673 FrameLayout fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
4675 // Set the full screen video flag.
4676 displayingFullScreenVideo = true;
4678 // Pause the ad if this is the free flavor.
4679 if (BuildConfig.FLAVOR.contentEquals("free")) {
4680 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
4681 AdHelper.pauseAd(findViewById(R.id.adview));
4684 // Hide the keyboard.
4685 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
4687 // Hide the main content relative layout.
4688 mainContentRelativeLayout.setVisibility(View.GONE);
4690 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
4691 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
4693 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
4694 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4696 /* Hide the system bars.
4697 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4698 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4699 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4700 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4702 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
4703 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
4705 // Disable the sliding drawers.
4706 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
4708 // Add the video view to the full screen video frame layout.
4709 fullScreenVideoFrameLayout.addView(video);
4711 // Show the full screen video frame layout.
4712 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
4715 // Exit full screen video.
4717 public void onHideCustomView() {
4718 // Get a handle for the full screen video frame layout.
4719 FrameLayout fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
4721 // Unset the full screen video flag.
4722 displayingFullScreenVideo = false;
4724 // Remove all the views from the full screen video frame layout.
4725 fullScreenVideoFrameLayout.removeAllViews();
4727 // Hide the full screen video frame layout.
4728 fullScreenVideoFrameLayout.setVisibility(View.GONE);
4730 // Enable the sliding drawers.
4731 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
4733 // Show the main content relative layout.
4734 mainContentRelativeLayout.setVisibility(View.VISIBLE);
4736 // Apply the appropriate full screen mode flags.
4737 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
4738 // Hide the app bar if specified.
4740 // Hide the tab linear layout.
4741 tabsLinearLayout.setVisibility(View.GONE);
4743 // Hide the action bar.
4747 // Hide the banner ad in the free flavor.
4748 if (BuildConfig.FLAVOR.contentEquals("free")) {
4749 AdHelper.hideAd(findViewById(R.id.adview));
4752 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
4753 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4755 /* Hide the system bars.
4756 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4757 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4758 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4759 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4761 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
4762 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
4763 } else { // Switch to normal viewing mode.
4764 // Remove the `SYSTEM_UI` flags from the root frame layout.
4765 rootFrameLayout.setSystemUiVisibility(0);
4767 // Add the translucent status flag.
4768 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4771 // Reload the ad for the free flavor if not in full screen mode.
4772 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
4774 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
4780 public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
4781 // Show the file chooser if the device is running API >= 21.
4782 if (Build.VERSION.SDK_INT >= 21) {
4783 // Store the file path callback.
4784 fileChooserCallback = filePathCallback;
4786 // Create an intent to open a chooser based ont the file chooser parameters.
4787 Intent fileChooserIntent = fileChooserParams.createIntent();
4789 // Open the file chooser. Currently only one `startActivityForResult` exists in this activity, so the request code, used to differentiate them, is simply `0`.
4790 startActivityForResult(fileChooserIntent, 0);
4796 nestedScrollWebView.setWebViewClient(new WebViewClient() {
4797 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
4798 // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
4800 public boolean shouldOverrideUrlLoading(WebView view, String url) {
4801 // Sanitize the url.
4802 url = sanitizeUrl(url);
4804 if (url.startsWith("http")) { // Load the URL in Privacy Browser.
4805 // Apply the domain settings for the new URL. This doesn't do anything if the domain has not changed.
4806 boolean userAgentChanged = applyDomainSettings(nestedScrollWebView, url, true, false);
4808 // Check if the user agent has changed.
4809 if (userAgentChanged) {
4810 // Manually load the URL. The changing of the user agent will cause WebView to reload the previous URL.
4811 nestedScrollWebView.loadUrl(url, customHeaders);
4813 // Returning true indicates that Privacy Browser is manually handling the loading of the URL.
4816 // Returning false causes the current WebView to handle the URL and prevents it from adding redirects to the history list.
4819 } else if (url.startsWith("mailto:")) { // Load the email address in an external email program.
4820 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
4821 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
4823 // Parse the url and set it as the data for the intent.
4824 emailIntent.setData(Uri.parse(url));
4826 // Open the email program in a new task instead of as part of Privacy Browser.
4827 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4830 startActivity(emailIntent);
4832 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
4834 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
4835 // Open the dialer and load the phone number, but wait for the user to place the call.
4836 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
4838 // Add the phone number to the intent.
4839 dialIntent.setData(Uri.parse(url));
4841 // Open the dialer in a new task instead of as part of Privacy Browser.
4842 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4845 startActivity(dialIntent);
4847 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
4849 } else { // Load a system chooser to select an app that can handle the URL.
4850 // Open an app that can handle the URL.
4851 Intent genericIntent = new Intent(Intent.ACTION_VIEW);
4853 // Add the URL to the intent.
4854 genericIntent.setData(Uri.parse(url));
4856 // List all apps that can handle the URL instead of just opening the first one.
4857 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
4859 // Open the app in a new task instead of as part of Privacy Browser.
4860 genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4862 // Start the app or display a snackbar if no app is available to handle the URL.
4864 startActivity(genericIntent);
4865 } catch (ActivityNotFoundException exception) {
4866 Snackbar.make(nestedScrollWebView, getString(R.string.unrecognized_url) + " " + url, Snackbar.LENGTH_SHORT).show();
4869 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
4874 // Check requests against the block lists. The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
4876 public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
4877 // Get a handle for the navigation view.
4878 NavigationView navigationView = findViewById(R.id.navigationview);
4880 // Get a handle for the navigation menu.
4881 Menu navigationMenu = navigationView.getMenu();
4883 // Get a handle for the navigation requests menu item. The menu is 0 based.
4884 MenuItem navigationRequestsMenuItem = navigationMenu.getItem(5);
4886 // Create an empty web resource response to be used if the resource request is blocked.
4887 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
4889 // Reset the whitelist results tracker.
4890 String[] whitelistResultStringArray = null;
4892 // Initialize the third party request tracker.
4893 boolean isThirdPartyRequest = false;
4895 // Get the current URL. `.getUrl()` throws an error because operations on the WebView cannot be made from this thread.
4896 String currentBaseDomain = nestedScrollWebView.getCurrentDomainName();
4898 // Store a copy of the current domain for use in later requests.
4899 String currentDomain = currentBaseDomain;
4901 // Nobody is happy when comparing null strings.
4902 if ((currentBaseDomain != null) && (url != null)) {
4903 // Convert the request URL to a URI.
4904 Uri requestUri = Uri.parse(url);
4906 // Get the request host name.
4907 String requestBaseDomain = requestUri.getHost();
4909 // Only check for third-party requests if the current base domain is not empty and the request domain is not null.
4910 if (!currentBaseDomain.isEmpty() && (requestBaseDomain != null)) {
4911 // Determine the current base domain.
4912 while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
4913 // Remove the first subdomain.
4914 currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
4917 // Determine the request base domain.
4918 while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
4919 // Remove the first subdomain.
4920 requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
4923 // Update the third party request tracker.
4924 isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
4928 // Get the current WebView page position.
4929 int webViewPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
4931 // Determine if the WebView is currently displayed.
4932 boolean webViewDisplayed = (webViewPagePosition == tabLayout.getSelectedTabPosition());
4934 // Block third-party requests if enabled.
4935 if (isThirdPartyRequest && nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS)) {
4936 // Add the result to the resource requests.
4937 nestedScrollWebView.addResourceRequest(new String[]{BlockListHelper.REQUEST_THIRD_PARTY, url});
4939 // Increment the blocked requests counters.
4940 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
4941 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS);
4943 // Update the titles of the blocklist menu items if the WebView is currently displayed.
4944 if (webViewDisplayed) {
4945 // Updating the UI must be run from the UI thread.
4946 activity.runOnUiThread(() -> {
4947 // Update the menu item titles.
4948 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
4950 // Update the options menu if it has been populated.
4951 if (optionsMenu != null) {
4952 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
4953 optionsMenu.findItem(R.id.block_all_third_party_requests).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " +
4954 getString(R.string.block_all_third_party_requests));
4959 // Return an empty web resource response.
4960 return emptyWebResourceResponse;
4963 // Check UltraPrivacy if it is enabled.
4964 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY)) {
4965 // Check the URL against UltraPrivacy.
4966 String[] ultraPrivacyResults = blockListHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraPrivacy);
4968 // Process the UltraPrivacy results.
4969 if (ultraPrivacyResults[0].equals(BlockListHelper.REQUEST_BLOCKED)) { // The resource request matched UltraPrivacy's blacklist.
4970 // Add the result to the resource requests.
4971 nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
4972 ultraPrivacyResults[5]});
4974 // Increment the blocked requests counters.
4975 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
4976 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRA_PRIVACY);
4978 // Update the titles of the blocklist menu items if the WebView is currently displayed.
4979 if (webViewDisplayed) {
4980 // Updating the UI must be run from the UI thread.
4981 activity.runOnUiThread(() -> {
4982 // Update the menu item titles.
4983 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
4985 // Update the options menu if it has been populated.
4986 if (optionsMenu != null) {
4987 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
4988 optionsMenu.findItem(R.id.ultraprivacy).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRA_PRIVACY) + " - " + getString(R.string.ultraprivacy));
4993 // The resource request was blocked. Return an empty web resource response.
4994 return emptyWebResourceResponse;
4995 } else if (ultraPrivacyResults[0].equals(BlockListHelper.REQUEST_ALLOWED)) { // The resource request matched UltraPrivacy's whitelist.
4996 // Add a whitelist entry to the resource requests array.
4997 nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
4998 ultraPrivacyResults[5]});
5000 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
5005 // Check EasyList if it is enabled.
5006 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST)) {
5007 // Check the URL against EasyList.
5008 String[] easyListResults = blockListHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyList);
5010 // Process the EasyList results.
5011 if (easyListResults[0].equals(BlockListHelper.REQUEST_BLOCKED)) { // The resource request matched EasyList's blacklist.
5012 // Add the result to the resource requests.
5013 nestedScrollWebView.addResourceRequest(new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]});
5015 // Increment the blocked requests counters.
5016 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5017 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASY_LIST);
5019 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5020 if (webViewDisplayed) {
5021 // Updating the UI must be run from the UI thread.
5022 activity.runOnUiThread(() -> {
5023 // Update the menu item titles.
5024 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5026 // Update the options menu if it has been populated.
5027 if (optionsMenu != null) {
5028 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5029 optionsMenu.findItem(R.id.easylist).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASY_LIST) + " - " + getString(R.string.easylist));
5034 // The resource request was blocked. Return an empty web resource response.
5035 return emptyWebResourceResponse;
5036 } else if (easyListResults[0].equals(BlockListHelper.REQUEST_ALLOWED)) { // The resource request matched EasyList's whitelist.
5037 // Update the whitelist result string array tracker.
5038 whitelistResultStringArray = new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]};
5042 // Check EasyPrivacy if it is enabled.
5043 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY)) {
5044 // Check the URL against EasyPrivacy.
5045 String[] easyPrivacyResults = blockListHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyPrivacy);
5047 // Process the EasyPrivacy results.
5048 if (easyPrivacyResults[0].equals(BlockListHelper.REQUEST_BLOCKED)) { // The resource request matched EasyPrivacy's blacklist.
5049 // Add the result to the resource requests.
5050 nestedScrollWebView.addResourceRequest(new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4],
5051 easyPrivacyResults[5]});
5053 // Increment the blocked requests counters.
5054 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5055 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASY_PRIVACY);
5057 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5058 if (webViewDisplayed) {
5059 // Updating the UI must be run from the UI thread.
5060 activity.runOnUiThread(() -> {
5061 // Update the menu item titles.
5062 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5064 // Update the options menu if it has been populated.
5065 if (optionsMenu != null) {
5066 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5067 optionsMenu.findItem(R.id.easyprivacy).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASY_PRIVACY) + " - " + getString(R.string.easyprivacy));
5072 // The resource request was blocked. Return an empty web resource response.
5073 return emptyWebResourceResponse;
5074 } else if (easyPrivacyResults[0].equals(BlockListHelper.REQUEST_ALLOWED)) { // The resource request matched EasyPrivacy's whitelist.
5075 // Update the whitelist result string array tracker.
5076 whitelistResultStringArray = new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5]};
5080 // Check Fanboy’s Annoyance List if it is enabled.
5081 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST)) {
5082 // Check the URL against Fanboy's Annoyance List.
5083 String[] fanboysAnnoyanceListResults = blockListHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList);
5085 // Process the Fanboy's Annoyance List results.
5086 if (fanboysAnnoyanceListResults[0].equals(BlockListHelper.REQUEST_BLOCKED)) { // The resource request matched Fanboy's Annoyance List's blacklist.
5087 // Add the result to the resource requests.
5088 nestedScrollWebView.addResourceRequest(new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5089 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]});
5091 // Increment the blocked requests counters.
5092 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5093 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST);
5095 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5096 if (webViewDisplayed) {
5097 // Updating the UI must be run from the UI thread.
5098 activity.runOnUiThread(() -> {
5099 // Update the menu item titles.
5100 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5102 // Update the options menu if it has been populated.
5103 if (optionsMenu != null) {
5104 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5105 optionsMenu.findItem(R.id.fanboys_annoyance_list).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " +
5106 getString(R.string.fanboys_annoyance_list));
5111 // The resource request was blocked. Return an empty web resource response.
5112 return emptyWebResourceResponse;
5113 } else if (fanboysAnnoyanceListResults[0].equals(BlockListHelper.REQUEST_ALLOWED)){ // The resource request matched Fanboy's Annoyance List's whitelist.
5114 // Update the whitelist result string array tracker.
5115 whitelistResultStringArray = new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5116 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]};
5118 } else if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST)) { // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
5119 // Check the URL against Fanboy's Annoyance List.
5120 String[] fanboysSocialListResults = blockListHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysSocialList);
5122 // Process the Fanboy's Social Blocking List results.
5123 if (fanboysSocialListResults[0].equals(BlockListHelper.REQUEST_BLOCKED)) { // The resource request matched Fanboy's Social Blocking List's blacklist.
5124 // Add the result to the resource requests.
5125 nestedScrollWebView.addResourceRequest(new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5126 fanboysSocialListResults[4], fanboysSocialListResults[5]});
5128 // Increment the blocked requests counters.
5129 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5130 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST);
5132 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5133 if (webViewDisplayed) {
5134 // Updating the UI must be run from the UI thread.
5135 activity.runOnUiThread(() -> {
5136 // Update the menu item titles.
5137 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5139 // Update the options menu if it has been populated.
5140 if (optionsMenu != null) {
5141 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5142 optionsMenu.findItem(R.id.fanboys_social_blocking_list).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " +
5143 getString(R.string.fanboys_social_blocking_list));
5148 // The resource request was blocked. Return an empty web resource response.
5149 return emptyWebResourceResponse;
5150 } else if (fanboysSocialListResults[0].equals(BlockListHelper.REQUEST_ALLOWED)) { // The resource request matched Fanboy's Social Blocking List's whitelist.
5151 // Update the whitelist result string array tracker.
5152 whitelistResultStringArray = new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5153 fanboysSocialListResults[4], fanboysSocialListResults[5]};
5157 // Add the request to the log because it hasn't been processed by any of the previous checks.
5158 if (whitelistResultStringArray != null) { // The request was processed by a whitelist.
5159 nestedScrollWebView.addResourceRequest(whitelistResultStringArray);
5160 } else { // The request didn't match any blocklist entry. Log it as a default request.
5161 nestedScrollWebView.addResourceRequest(new String[]{BlockListHelper.REQUEST_DEFAULT, url});
5164 // The resource request has not been blocked. `return null` loads the requested resource.
5168 // Handle HTTP authentication requests.
5170 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
5171 // Store the handler.
5172 nestedScrollWebView.setHttpAuthHandler(handler);
5174 // Instantiate an HTTP authentication dialog.
5175 DialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm, nestedScrollWebView.getWebViewFragmentId());
5177 // Show the HTTP authentication dialog.
5178 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
5182 public void onPageStarted(WebView view, String url, Bitmap favicon) {
5183 // Get the preferences.
5184 boolean scrollAppBar = sharedPreferences.getBoolean("scroll_app_bar", true);
5185 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
5187 // Get a handler for the app bar layout.
5188 AppBarLayout appBarLayout = findViewById(R.id.appbar_layout);
5190 // Set the top padding of the swipe refresh layout according to the app bar scrolling preference.
5192 // No padding is needed because it will automatically be placed below the app bar layout due to the scrolling layout behavior.
5193 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5195 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5196 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10, defaultProgressViewEndOffset);
5198 // Get the app bar layout height. This can't be done in `applyAppSettings()` because the app bar is not yet populated.
5199 int appBarHeight = appBarLayout.getHeight();
5201 // The swipe refresh layout must be manually moved below the app bar layout.
5202 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0);
5204 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5205 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight);
5208 // Reset the list of resource requests.
5209 nestedScrollWebView.clearResourceRequests();
5211 // Reset the requests counters.
5212 nestedScrollWebView.resetRequestsCounters();
5214 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
5215 if (nestedScrollWebView.getNightMode()) {
5216 nestedScrollWebView.setVisibility(View.INVISIBLE);
5218 nestedScrollWebView.setVisibility(View.VISIBLE);
5221 // Hide the keyboard.
5222 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
5224 // Check to see if Privacy Browser is waiting on Orbot.
5225 if (!waitingForOrbot) { // Process the URL.
5226 // Get the current page position.
5227 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5229 // Update the URL text bar if the page is currently selected.
5230 if (tabLayout.getSelectedTabPosition() == currentPagePosition) {
5231 // Clear the focus from the URL edit text.
5232 urlEditText.clearFocus();
5234 // Display the formatted URL text.
5235 urlEditText.setText(url);
5237 // Apply text highlighting to `urlTextBox`.
5241 // Reset the list of host IP addresses.
5242 nestedScrollWebView.clearCurrentIpAddresses();
5244 // Get a URI for the current URL.
5245 Uri currentUri = Uri.parse(url);
5247 // Get the IP addresses for the host.
5248 new GetHostIpAddresses(activity, getSupportFragmentManager(), nestedScrollWebView).execute(currentUri.getHost());
5250 // Apply any custom domain settings if the URL was loaded by navigating history.
5251 if (nestedScrollWebView.getNavigatingHistory()) {
5252 // Reset navigating history.
5253 nestedScrollWebView.setNavigatingHistory(false);
5255 // Apply the domain settings.
5256 boolean userAgentChanged = applyDomainSettings(nestedScrollWebView, url, true, false);
5258 // Manually load the URL if the user agent has changed, which will have caused the previous URL to be reloaded.
5259 if (userAgentChanged) {
5264 // Replace Refresh with Stop if the options menu has been created. (The WebView typically begins loading before the menu items are instantiated.)
5265 if (optionsMenu != null) {
5266 // Get a handle for the refresh menu item.
5267 MenuItem refreshMenuItem = optionsMenu.findItem(R.id.refresh);
5270 refreshMenuItem.setTitle(R.string.stop);
5272 // Get the app bar and theme preferences.
5273 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
5275 // If the icon is displayed in the AppBar, set it according to the theme.
5276 if (displayAdditionalAppBarIcons) {
5278 refreshMenuItem.setIcon(R.drawable.close_dark);
5280 refreshMenuItem.setIcon(R.drawable.close_light);
5288 public void onPageFinished(WebView view, String url) {
5289 // Reset the wide view port if it has been turned off by the waiting for Orbot message.
5290 if (!waitingForOrbot) {
5291 // Only use a wide view port if the URL starts with `http`, not for `file://` and `content://`.
5292 nestedScrollWebView.getSettings().setUseWideViewPort(url.startsWith("http"));
5295 // Flush any cookies to persistent storage. The cookie manager has become very lazy about flushing cookies in recent versions.
5296 if (nestedScrollWebView.getAcceptFirstPartyCookies() && Build.VERSION.SDK_INT >= 21) {
5297 CookieManager.getInstance().flush();
5300 // Update the Refresh menu item if the options menu has been created.
5301 if (optionsMenu != null) {
5302 // Get a handle for the refresh menu item.
5303 MenuItem refreshMenuItem = optionsMenu.findItem(R.id.refresh);
5305 // Reset the Refresh title.
5306 refreshMenuItem.setTitle(R.string.refresh);
5308 // Get the app bar and theme preferences.
5309 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
5310 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
5312 // If the icon is displayed in the AppBar, reset it according to the theme.
5313 if (displayAdditionalAppBarIcons) {
5315 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
5317 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
5322 // Clear the cache and history if Incognito Mode is enabled.
5323 if (incognitoModeEnabled) {
5324 // Clear the cache. `true` includes disk files.
5325 nestedScrollWebView.clearCache(true);
5327 // Clear the back/forward history.
5328 nestedScrollWebView.clearHistory();
5330 // Manually delete cache folders.
5332 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
5333 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
5334 String privateDataDirectoryString = getApplicationInfo().dataDir;
5336 // Delete the main cache directory.
5337 Runtime.getRuntime().exec("rm -rf " + privateDataDirectoryString + "/cache");
5339 // Delete the secondary `Service Worker` cache directory.
5340 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
5341 Runtime.getRuntime().exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
5342 } catch (IOException e) {
5343 // Do nothing if an error is thrown.
5347 // Update the URL text box and apply domain settings if not waiting on Orbot.
5348 if (!waitingForOrbot) {
5349 // Get the current page position.
5350 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5352 // Check the current website information against any pinned domain information if the current IP addresses have been loaded.
5353 if ((nestedScrollWebView.hasPinnedSslCertificate() || nestedScrollWebView.hasPinnedIpAddresses()) && nestedScrollWebView.hasCurrentIpAddresses() &&
5354 !nestedScrollWebView.ignorePinnedDomainInformation()) {
5355 CheckPinnedMismatchHelper.checkPinnedMismatch(getSupportFragmentManager(), nestedScrollWebView);
5358 // Get the current URL from the nested scroll WebView. This is more accurate than using the URL passed into the method, which is sometimes not the final one.
5359 String currentUrl = nestedScrollWebView.getUrl();
5361 // Update the URL text bar if the page is currently selected and the user is not currently typing in the URL edit text.
5362 // Crash records show that, in some crazy way, it is possible for the current URL to be blank at this point.
5363 // Probably some sort of race condition when Privacy Browser is being resumed.
5364 if ((tabLayout.getSelectedTabPosition() == currentPagePosition) && !urlEditText.hasFocus() && (currentUrl != null)) {
5365 // Check to see if the URL is `about:blank`.
5366 if (currentUrl.equals("about:blank")) { // The WebView is blank.
5367 // Display the hint in the URL edit text.
5368 urlEditText.setText("");
5370 // Request focus for the URL text box.
5371 urlEditText.requestFocus();
5373 // Display the keyboard.
5374 inputMethodManager.showSoftInput(urlEditText, 0);
5376 // Hide the WebView, which causes the default background color to be displayed according to the theme.
5377 nestedScrollWebView.setVisibility(View.INVISIBLE);
5379 // Apply the domain settings. This clears any settings from the previous domain.
5380 applyDomainSettings(nestedScrollWebView, "", true, false);
5381 } else { // The WebView has loaded a webpage.
5382 // Display the final URL. Getting the URL from the WebView instead of using the one provided by `onPageFinished()` makes websites like YouTube function correctly.
5383 urlEditText.setText(currentUrl);
5385 // Apply text highlighting to the URL.
5390 // Get the current tab.
5391 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
5393 // Only populate the title text view if the tab has been fully created.
5395 // Get the custom view from the tab.
5396 View tabView = tab.getCustomView();
5398 // Remove the incorrect warning below that the current tab view might be null.
5399 assert tabView != null;
5401 // Get the title text view from the tab.
5402 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
5404 // Set the title as the tab text. Sometimes `onReceivedTitle()` is not called, especially when navigating history.
5405 tabTitleTextView.setText(nestedScrollWebView.getTitle());
5410 // Handle SSL Certificate errors.
5412 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
5413 // Get the current website SSL certificate.
5414 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
5416 // Extract the individual pieces of information from the current website SSL certificate.
5417 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
5418 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
5419 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
5420 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
5421 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
5422 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
5423 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
5424 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
5426 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
5427 if (nestedScrollWebView.hasPinnedSslCertificate()) {
5428 // Get the pinned SSL certificate.
5429 ArrayList<Object> pinnedSslCertificateArrayList = nestedScrollWebView.getPinnedSslCertificate();
5431 // Extract the arrays from the array list.
5432 String[] pinnedSslCertificateStringArray = (String[]) pinnedSslCertificateArrayList.get(0);
5433 Date[] pinnedSslCertificateDateArray = (Date[]) pinnedSslCertificateArrayList.get(1);
5435 // Check if the current SSL certificate matches the pinned certificate.
5436 if (currentWebsiteIssuedToCName.equals(pinnedSslCertificateStringArray[0]) && currentWebsiteIssuedToOName.equals(pinnedSslCertificateStringArray[1]) &&
5437 currentWebsiteIssuedToUName.equals(pinnedSslCertificateStringArray[2]) && currentWebsiteIssuedByCName.equals(pinnedSslCertificateStringArray[3]) &&
5438 currentWebsiteIssuedByOName.equals(pinnedSslCertificateStringArray[4]) && currentWebsiteIssuedByUName.equals(pinnedSslCertificateStringArray[5]) &&
5439 currentWebsiteSslStartDate.equals(pinnedSslCertificateDateArray[0]) && currentWebsiteSslEndDate.equals(pinnedSslCertificateDateArray[1])) {
5441 // An SSL certificate is pinned and matches the current domain certificate. Proceed to the website without displaying an error.
5444 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
5445 // Store the SSL error handler.
5446 nestedScrollWebView.setSslErrorHandler(handler);
5448 // Instantiate an SSL certificate error alert dialog.
5449 DialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error, nestedScrollWebView.getWebViewFragmentId());
5451 // Show the SSL certificate error dialog.
5452 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
5457 // Check to see if this is the first page.
5458 if (pageNumber == 0) {
5459 // Set this nested scroll WebView as the current WebView.
5460 currentWebView = nestedScrollWebView;
5462 // Apply the app settings from the shared preferences.
5465 // Load the website if not waiting for Orbot to connect.
5466 if (!waitingForOrbot) {
5467 // Get the intent that started the app.
5468 Intent launchingIntent = getIntent();
5470 // Get the information from the intent.
5471 String launchingIntentAction = launchingIntent.getAction();
5472 Uri launchingIntentUriData = launchingIntent.getData();
5474 // If the intent action is a web search, perform the search.
5475 if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) {
5476 // Create an encoded URL string.
5477 String encodedUrlString;
5479 // Sanitize the search input and convert it to a search.
5481 encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
5482 } catch (UnsupportedEncodingException exception) {
5483 encodedUrlString = "";
5486 // Load the completed search URL.
5487 loadUrl(searchURL + encodedUrlString);
5488 } else if (launchingIntentUriData != null){ // Check to see if the intent contains a new URL.
5489 // Load the URL from the intent.
5490 loadUrl(launchingIntentUriData.toString());
5491 } else { // The is no URL in the intent.
5492 // Select the homepage based on the proxy through Orbot status.
5493 if (proxyThroughOrbot) {
5494 // Load the Tor homepage.
5495 loadUrl(sharedPreferences.getString("tor_homepage", getString(R.string.tor_homepage_default_value)));
5497 // Load the normal homepage.
5498 loadUrl(sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
5502 } else { // This is not the first tab.
5503 // Apply the domain settings.
5504 applyDomainSettings(nestedScrollWebView, url, false, false);
5507 nestedScrollWebView.loadUrl(url, customHeaders);
5509 // Display the keyboard if the URL is blank.
5510 if (url.equals("")) {
5511 inputMethodManager.showSoftInput(urlEditText, 0);