+ @Override
+ public boolean onOptionsItemSelected(MenuItem menuItem) {
+ // Get a handle for the shared preferences.
+ SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
+
+ // Get a handle for the cookie manager.
+ CookieManager cookieManager = CookieManager.getInstance();
+
+ // Get the selected menu item ID.
+ int menuItemId = menuItem.getItemId();
+
+ // Run the commands that correlate to the selected menu item.
+ if (menuItemId == R.id.javascript) { // JavaScript.
+ // Toggle the JavaScript status.
+ currentWebView.getSettings().setJavaScriptEnabled(!currentWebView.getSettings().getJavaScriptEnabled());
+
+ // Update the privacy icon.
+ updatePrivacyIcons(true);
+
+ // Display a `Snackbar`.
+ if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScrip is enabled.
+ Snackbar.make(webViewPager, R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
+ } else if (cookieManager.acceptCookie()) { // JavaScript is disabled, but first-party cookies are enabled.
+ Snackbar.make(webViewPager, R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
+ } else { // Privacy mode.
+ Snackbar.make(webViewPager, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
+ }
+
+ // Reload the current WebView.
+ currentWebView.reload();
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.refresh) { // Refresh.
+ // Run the command that correlates to the current status of the menu item.
+ if (menuItem.getTitle().equals(getString(R.string.refresh))) { // The refresh button was pushed.
+ // Reload the current WebView.
+ currentWebView.reload();
+ } else { // The stop button was pushed.
+ // Stop the loading of the WebView.
+ currentWebView.stopLoading();
+ }
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.bookmarks) { // Bookmarks.
+ // Open the bookmarks drawer.
+ drawerLayout.openDrawer(GravityCompat.END);
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.cookies) { // Cookies.
+ // Switch the first-party cookie status.
+ cookieManager.setAcceptCookie(!cookieManager.acceptCookie());
+
+ // Store the cookie status.
+ currentWebView.setAcceptCookies(cookieManager.acceptCookie());
+
+ // Update the menu checkbox.
+ menuItem.setChecked(cookieManager.acceptCookie());
+
+ // Update the privacy icon.
+ updatePrivacyIcons(true);
+
+ // Display a snackbar.
+ if (cookieManager.acceptCookie()) { // Cookies are enabled.
+ Snackbar.make(webViewPager, R.string.cookies_enabled, Snackbar.LENGTH_SHORT).show();
+ } else if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is still enabled.
+ Snackbar.make(webViewPager, R.string.cookies_disabled, Snackbar.LENGTH_SHORT).show();
+ } else { // Privacy mode.
+ Snackbar.make(webViewPager, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
+ }
+
+ // Reload the current WebView.
+ currentWebView.reload();
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.dom_storage) { // DOM storage.
+ // Toggle the status of domStorageEnabled.
+ currentWebView.getSettings().setDomStorageEnabled(!currentWebView.getSettings().getDomStorageEnabled());
+
+ // Update the menu checkbox.
+ menuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
+
+ // Update the privacy icon.
+ updatePrivacyIcons(true);
+
+ // Display a snackbar.
+ if (currentWebView.getSettings().getDomStorageEnabled()) {
+ Snackbar.make(webViewPager, R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
+ } else {
+ Snackbar.make(webViewPager, R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
+ }
+
+ // Reload the current WebView.
+ currentWebView.reload();
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.save_form_data) { // Form data. This can be removed once the minimum API >= 26.
+ // Switch the status of saveFormDataEnabled.
+ currentWebView.getSettings().setSaveFormData(!currentWebView.getSettings().getSaveFormData());
+
+ // Update the menu checkbox.
+ menuItem.setChecked(currentWebView.getSettings().getSaveFormData());
+
+ // Display a snackbar.
+ if (currentWebView.getSettings().getSaveFormData()) {
+ Snackbar.make(webViewPager, R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
+ } else {
+ Snackbar.make(webViewPager, R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
+ }
+
+ // Update the privacy icon.
+ updatePrivacyIcons(true);
+
+ // Reload the current WebView.
+ currentWebView.reload();
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.clear_cookies) { // Clear cookies.
+ // Create a snackbar.
+ Snackbar.make(webViewPager, R.string.cookies_deleted, Snackbar.LENGTH_LONG)
+ .setAction(R.string.undo, v -> {
+ // Do nothing because everything will be handled by `onDismissed()` below.
+ })
+ .addCallback(new Snackbar.Callback() {
+ @Override
+ public void onDismissed(Snackbar snackbar, int event) {
+ if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
+ // Delete the cookies.
+ cookieManager.removeAllCookies(null);
+ }
+ }
+ })
+ .show();
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.clear_dom_storage) { // Clear DOM storage.
+ // Create a snackbar.
+ Snackbar.make(webViewPager, R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
+ .setAction(R.string.undo, v -> {
+ // Do nothing because everything will be handled by `onDismissed()` below.
+ })
+ .addCallback(new Snackbar.Callback() {
+ @Override
+ public void onDismissed(Snackbar snackbar, int event) {
+ if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
+ // Delete the DOM Storage.
+ WebStorage webStorage = WebStorage.getInstance();
+ webStorage.deleteAllData();
+
+ // Initialize a handler to manually delete the DOM storage files and directories.
+ Handler deleteDomStorageHandler = new Handler();
+
+ // Setup a runnable to manually delete the DOM storage files and directories.
+ Runnable deleteDomStorageRunnable = () -> {
+ try {
+ // Get a handle for the runtime.
+ Runtime runtime = Runtime.getRuntime();
+
+ // 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`.
+ String privateDataDirectoryString = getApplicationInfo().dataDir;
+
+ // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
+ Process deleteLocalStorageProcess = runtime.exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
+
+ // Multiple commands must be used because `Runtime.exec()` does not like `*`.
+ Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
+ Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
+ Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
+ Process deleteDatabasesProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
+
+ // Wait for the processes to finish.
+ deleteLocalStorageProcess.waitFor();
+ deleteIndexProcess.waitFor();
+ deleteQuotaManagerProcess.waitFor();
+ deleteQuotaManagerJournalProcess.waitFor();
+ deleteDatabasesProcess.waitFor();
+ } catch (Exception exception) {
+ // Do nothing if an error is thrown.
+ }
+ };
+
+ // Manually delete the DOM storage files after 200 milliseconds.
+ deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200);
+ }
+ }
+ })
+ .show();
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.clear_form_data) { // Clear form data. This can be remove once the minimum API >= 26.
+ // Create a snackbar.
+ Snackbar.make(webViewPager, R.string.form_data_deleted, Snackbar.LENGTH_LONG)
+ .setAction(R.string.undo, v -> {
+ // Do nothing because everything will be handled by `onDismissed()` below.
+ })
+ .addCallback(new Snackbar.Callback() {
+ @Override
+ public void onDismissed(Snackbar snackbar, int event) {
+ if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
+ // Get a handle for the webView database.
+ WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
+
+ // Delete the form data.
+ webViewDatabase.clearFormData();
+ }
+ }
+ })
+ .show();
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.easylist) { // EasyList.
+ // Toggle the EasyList status.
+ currentWebView.setEasyListEnabled(!currentWebView.getEasyListEnabled());
+
+ // Update the menu checkbox.
+ menuItem.setChecked(currentWebView.getEasyListEnabled());
+
+ // Reload the current WebView.
+ currentWebView.reload();
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.easyprivacy) { // EasyPrivacy.
+ // Toggle the EasyPrivacy status.
+ currentWebView.setEasyPrivacyEnabled(!currentWebView.getEasyPrivacyEnabled());
+
+ // Update the menu checkbox.
+ menuItem.setChecked(currentWebView.getEasyPrivacyEnabled());
+
+ // Reload the current WebView.
+ currentWebView.reload();
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.fanboys_annoyance_list) { // Fanboy's Annoyance List.
+ // Toggle Fanboy's Annoyance List status.
+ currentWebView.setFanboysAnnoyanceListEnabled(!currentWebView.getFanboysAnnoyanceListEnabled());
+
+ // Update the menu checkbox.
+ menuItem.setChecked(currentWebView.getFanboysAnnoyanceListEnabled());
+
+ // Update the status of Fanboy's Social Blocking List.
+ optionsFanboysSocialBlockingListMenuItem.setEnabled(!currentWebView.getFanboysAnnoyanceListEnabled());
+
+ // Reload the current WebView.
+ currentWebView.reload();
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.fanboys_social_blocking_list) { // Fanboy's Social Blocking List.
+ // Toggle Fanboy's Social Blocking List status.
+ currentWebView.setFanboysSocialBlockingListEnabled(!currentWebView.getFanboysSocialBlockingListEnabled());
+
+ // Update the menu checkbox.
+ menuItem.setChecked(currentWebView.getFanboysSocialBlockingListEnabled());
+
+ // Reload the current WebView.
+ currentWebView.reload();
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.ultralist) { // UltraList.
+ // Toggle the UltraList status.
+ currentWebView.setUltraListEnabled(!currentWebView.getUltraListEnabled());
+
+ // Update the menu checkbox.
+ menuItem.setChecked(currentWebView.getUltraListEnabled());
+
+ // Reload the current WebView.
+ currentWebView.reload();
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.ultraprivacy) { // UltraPrivacy.
+ // Toggle the UltraPrivacy status.
+ currentWebView.setUltraPrivacyEnabled(!currentWebView.getUltraPrivacyEnabled());
+
+ // Update the menu checkbox.
+ menuItem.setChecked(currentWebView.getUltraPrivacyEnabled());
+
+ // Reload the current WebView.
+ currentWebView.reload();
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.block_all_third_party_requests) { // Block all third-party requests.
+ //Toggle the third-party requests blocker status.
+ currentWebView.setBlockAllThirdPartyRequests(!currentWebView.getBlockAllThirdPartyRequests());
+
+ // Update the menu checkbox.
+ menuItem.setChecked(currentWebView.getBlockAllThirdPartyRequests());
+
+ // Reload the current WebView.
+ currentWebView.reload();
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.proxy_none) { // Proxy - None.
+ // Update the proxy mode.
+ proxyMode = ProxyHelper.NONE;
+
+ // Apply the proxy mode.
+ applyProxy(true);
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.proxy_tor) { // Proxy - Tor.
+ // Update the proxy mode.
+ proxyMode = ProxyHelper.TOR;
+
+ // Apply the proxy mode.
+ applyProxy(true);
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.proxy_i2p) { // Proxy - I2P.
+ // Update the proxy mode.
+ proxyMode = ProxyHelper.I2P;
+
+ // Apply the proxy mode.
+ applyProxy(true);
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.proxy_custom) { // Proxy - Custom.
+ // Update the proxy mode.
+ proxyMode = ProxyHelper.CUSTOM;
+
+ // Apply the proxy mode.
+ applyProxy(true);
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.user_agent_privacy_browser) { // User Agent - Privacy Browser.
+ // Update the user agent.
+ currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
+
+ // Reload the current WebView.
+ currentWebView.reload();
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.user_agent_webview_default) { // User Agent - WebView Default.
+ // Update the user agent.
+ currentWebView.getSettings().setUserAgentString("");
+
+ // Reload the current WebView.
+ currentWebView.reload();
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.user_agent_firefox_on_android) { // User Agent - Firefox on Android.
+ // Update the user agent.
+ currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
+
+ // Reload the current WebView.
+ currentWebView.reload();
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.user_agent_chrome_on_android) { // User Agent - Chrome on Android.
+ // Update the user agent.
+ currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
+
+ // Reload the current WebView.
+ currentWebView.reload();
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.user_agent_safari_on_ios) { // User Agent - Safari on iOS.
+ // Update the user agent.
+ currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
+
+ // Reload the current WebView.
+ currentWebView.reload();
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.user_agent_firefox_on_linux) { // User Agent - Firefox on Linux.
+ // Update the user agent.
+ currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
+
+ // Reload the current WebView.
+ currentWebView.reload();
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.user_agent_chromium_on_linux) { // User Agent - Chromium on Linux.
+ // Update the user agent.
+ currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
+
+ // Reload the current WebView.
+ currentWebView.reload();
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.user_agent_firefox_on_windows) { // User Agent - Firefox on Windows.
+ // Update the user agent.
+ currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
+
+ // Reload the current WebView.
+ currentWebView.reload();
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.user_agent_chrome_on_windows) { // User Agent - Chrome on Windows.
+ // Update the user agent.
+ currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
+
+ // Reload the current WebView.
+ currentWebView.reload();
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.user_agent_edge_on_windows) { // User Agent - Edge on Windows.
+ // Update the user agent.
+ currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
+
+ // Reload the current WebView.
+ currentWebView.reload();
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.user_agent_internet_explorer_on_windows) { // User Agent - Internet Explorer on Windows.
+ // Update the user agent.
+ currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
+
+ // Reload the current WebView.
+ currentWebView.reload();
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.user_agent_safari_on_macos) { // User Agent - Safari on macOS.
+ // Update the user agent.
+ currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
+
+ // Reload the current WebView.
+ currentWebView.reload();
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.user_agent_custom) { // User Agent - Custom.
+ // Update the user agent.
+ currentWebView.getSettings().setUserAgentString(sharedPreferences.getString(getString(R.string.custom_user_agent_key), getString(R.string.custom_user_agent_default_value)));
+
+ // Reload the current WebView.
+ currentWebView.reload();
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.font_size) { // Font size.
+ // Instantiate the font size dialog.
+ DialogFragment fontSizeDialogFragment = FontSizeDialog.displayDialog(currentWebView.getSettings().getTextZoom());
+
+ // Show the font size dialog.
+ fontSizeDialogFragment.show(getSupportFragmentManager(), getString(R.string.font_size));
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.swipe_to_refresh) { // Swipe to refresh.
+ // Toggle the stored status of swipe to refresh.
+ currentWebView.setSwipeToRefresh(!currentWebView.getSwipeToRefresh());
+
+ // Update the swipe refresh layout.
+ if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
+ // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
+ swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
+ } else { // Swipe to refresh is disabled.
+ // Disable the swipe refresh layout.
+ swipeRefreshLayout.setEnabled(false);
+ }
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.wide_viewport) { // Wide viewport.
+ // Toggle the viewport.
+ currentWebView.getSettings().setUseWideViewPort(!currentWebView.getSettings().getUseWideViewPort());
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.display_images) { // Display images.
+ // Toggle the displaying of images.
+ if (currentWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
+ // Disable loading of images.
+ currentWebView.getSettings().setLoadsImagesAutomatically(false);
+
+ // Reload the website to remove existing images.
+ currentWebView.reload();
+ } else { // Images are not currently loaded automatically.
+ // Enable loading of images. Missing images will be loaded without the need for a reload.
+ currentWebView.getSettings().setLoadsImagesAutomatically(true);
+ }
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.dark_webview) { // Dark WebView.
+ // Toggle dark WebView if supported.
+ if ((Build.VERSION.SDK_INT >= 29) && WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING))
+ WebSettingsCompat.setAlgorithmicDarkeningAllowed(currentWebView.getSettings(), !WebSettingsCompat.isAlgorithmicDarkeningAllowed(currentWebView.getSettings()));
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.find_on_page) { // Find on page.
+ // Get a handle for the views.
+ Toolbar toolbar = findViewById(R.id.toolbar);
+ LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
+ EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
+
+ // Set the minimum height of the find on page linear layout to match the toolbar.
+ findOnPageLinearLayout.setMinimumHeight(toolbar.getHeight());
+
+ // Hide the toolbar.
+ toolbar.setVisibility(View.GONE);
+
+ // Show the find on page linear layout.
+ findOnPageLinearLayout.setVisibility(View.VISIBLE);
+
+ // Display the keyboard. The app must wait 200 ms before running the command to work around a bug in Android.
+ // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
+ findOnPageEditText.postDelayed(() -> {
+ // Set the focus on the find on page edit text.
+ findOnPageEditText.requestFocus();
+
+ // Get a handle for the input method manager.
+ InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
+
+ // Remove the lint warning below that the input method manager might be null.
+ assert inputMethodManager != null;
+
+ // Display the keyboard. `0` sets no input flags.
+ inputMethodManager.showSoftInput(findOnPageEditText, 0);
+ }, 200);
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.print) { // Print.
+ // Get a print manager instance.
+ PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
+
+ // Remove the lint error below that print manager might be null.
+ assert printManager != null;
+
+ // Create a print document adapter from the current WebView.
+ PrintDocumentAdapter printDocumentAdapter = currentWebView.createPrintDocumentAdapter(getString(R.string.print));
+
+ // Print the document.
+ printManager.print(getString(R.string.privacy_browser_webpage), printDocumentAdapter, null);
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.save_url) { // Save URL.
+ // Check the download preference.
+ if (downloadWithExternalApp) { // Download with an external app.
+ downloadUrlWithExternalApp(currentWebView.getCurrentUrl());
+ } else { // Handle the download inside of Privacy Browser.
+ // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
+ PrepareSaveDialogCoroutine.prepareSaveDialog(this, getSupportFragmentManager(), currentWebView.getCurrentUrl(), currentWebView.getSettings().getUserAgentString(),
+ currentWebView.getAcceptCookies());
+ }
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.save_archive) {
+ // Open the file picker with a default file name built from the current domain name.
+ saveWebpageArchiveActivityResultLauncher.launch(currentWebView.getCurrentDomainName() + ".mht");
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.save_image) { // Save image.
+ // Open the file picker with a default file name built from the current domain name.
+ saveWebpageImageActivityResultLauncher.launch(currentWebView.getCurrentDomainName() + ".png");
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.add_to_homescreen) { // Add to homescreen.
+ // Instantiate the create home screen shortcut dialog.
+ DialogFragment createHomeScreenShortcutDialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView.getTitle(), currentWebView.getUrl(),
+ currentWebView.getFavoriteIcon());
+
+ // Show the create home screen shortcut dialog.
+ createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.view_source) { // View source.
+ // Create an intent to launch the view source activity.
+ Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
+
+ // Add the variables to the intent.
+ viewSourceIntent.putExtra(ViewSourceActivityKt.CURRENT_URL, currentWebView.getUrl());
+ viewSourceIntent.putExtra(ViewSourceActivityKt.USER_AGENT, currentWebView.getSettings().getUserAgentString());
+
+ // Make it so.
+ startActivity(viewSourceIntent);
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.share_message) { // Share a message.
+ // Prepare the share string.
+ String shareString = currentWebView.getTitle() + " – " + currentWebView.getUrl();
+
+ // Create the share intent.
+ Intent shareMessageIntent = new Intent(Intent.ACTION_SEND);
+
+ // Add the share string to the intent.
+ shareMessageIntent.putExtra(Intent.EXTRA_TEXT, shareString);
+
+ // Set the MIME type.
+ shareMessageIntent.setType("text/plain");
+
+ // Set the intent to open in a new task.
+ shareMessageIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+
+ // Make it so.
+ startActivity(Intent.createChooser(shareMessageIntent, getString(R.string.share_message)));
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.share_url) { // Share URL.
+ // Create the share intent.
+ Intent shareUrlIntent = new Intent(Intent.ACTION_SEND);
+
+ // Add the URL to the intent.
+ shareUrlIntent.putExtra(Intent.EXTRA_TEXT, currentWebView.getUrl());
+
+ // Add the title to the intent.
+ shareUrlIntent.putExtra(Intent.EXTRA_SUBJECT, currentWebView.getTitle());
+
+ // Set the MIME type.
+ shareUrlIntent.setType("text/plain");
+
+ // Set the intent to open in a new task.
+ shareUrlIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+
+ //Make it so.
+ startActivity(Intent.createChooser(shareUrlIntent, getString(R.string.share_url)));
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.open_with_app) { // Open with app.
+ // Open the URL with an outside app.
+ openWithApp(currentWebView.getUrl());
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.open_with_browser) { // Open with browser.
+ // Open the URL with an outside browser.
+ openWithBrowser(currentWebView.getUrl());
+
+ // Consume the event.
+ return true;
+ } else if (menuItemId == R.id.add_or_edit_domain) { // Add or edit domain.
+ // Reapply the domain settings on returning to `MainWebViewActivity`.
+ reapplyDomainSettingsOnRestart = true;
+
+ // Check if domain settings currently exist.
+ if (currentWebView.getDomainSettingsApplied()) { // Edit the current domain settings.
+ // Create an intent to launch the domains activity.
+ Intent domainsIntent = new Intent(this, DomainsActivity.class);
+
+ // Add the extra information to the intent.
+ domainsIntent.putExtra(DomainsActivity.LOAD_DOMAIN, currentWebView.getDomainSettingsDatabaseId());
+ domainsIntent.putExtra(DomainsActivity.CLOSE_ON_BACK, true);
+ domainsIntent.putExtra(DomainsActivity.CURRENT_URL, currentWebView.getUrl());
+ domainsIntent.putExtra(DomainsActivity.CURRENT_IP_ADDRESSES, currentWebView.getCurrentIpAddresses());
+
+ // Get the current certificate.
+ SslCertificate sslCertificate = currentWebView.getCertificate();
+
+ // Check to see if the SSL certificate is populated.
+ if (sslCertificate != null) {
+ // Extract the certificate to strings.
+ String issuedToCName = sslCertificate.getIssuedTo().getCName();
+ String issuedToOName = sslCertificate.getIssuedTo().getOName();
+ String issuedToUName = sslCertificate.getIssuedTo().getUName();
+ String issuedByCName = sslCertificate.getIssuedBy().getCName();
+ String issuedByOName = sslCertificate.getIssuedBy().getOName();
+ String issuedByUName = sslCertificate.getIssuedBy().getUName();
+ long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
+ long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
+
+ // Add the certificate to the intent.
+ domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_TO_CNAME, issuedToCName);
+ domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_TO_ONAME, issuedToOName);
+ domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_TO_UNAME, issuedToUName);
+ domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_BY_CNAME, issuedByCName);
+ domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_BY_ONAME, issuedByOName);
+ domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_BY_UNAME, issuedByUName);
+ domainsIntent.putExtra(DomainsActivity.SSL_START_DATE, startDateLong);
+ domainsIntent.putExtra(DomainsActivity.SSL_END_DATE, endDateLong);
+ }
+
+ // Make it so.
+ startActivity(domainsIntent);
+ } else { // Add a new domain.
+ // Get the current URI.
+ Uri currentUri = Uri.parse(currentWebView.getUrl());
+
+ // Get the current domain from the URI.
+ String currentDomain = currentUri.getHost();
+
+ // Set an empty domain if it is null.
+ if (currentDomain == null)
+ currentDomain = "";
+
+ // Create the domain and store the database ID.
+ int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
+
+ // Create an intent to launch the domains activity.
+ Intent domainsIntent = new Intent(this, DomainsActivity.class);
+
+ // Add the extra information to the intent.
+ domainsIntent.putExtra(DomainsActivity.LOAD_DOMAIN, newDomainDatabaseId);
+ domainsIntent.putExtra(DomainsActivity.CLOSE_ON_BACK, true);
+ domainsIntent.putExtra(DomainsActivity.CURRENT_URL, currentWebView.getUrl());
+ domainsIntent.putExtra(DomainsActivity.CURRENT_IP_ADDRESSES, currentWebView.getCurrentIpAddresses());
+
+ // Get the current certificate.
+ SslCertificate sslCertificate = currentWebView.getCertificate();
+
+ // Check to see if the SSL certificate is populated.
+ if (sslCertificate != null) {
+ // Extract the certificate to strings.
+ String issuedToCName = sslCertificate.getIssuedTo().getCName();
+ String issuedToOName = sslCertificate.getIssuedTo().getOName();
+ String issuedToUName = sslCertificate.getIssuedTo().getUName();
+ String issuedByCName = sslCertificate.getIssuedBy().getCName();
+ String issuedByOName = sslCertificate.getIssuedBy().getOName();
+ String issuedByUName = sslCertificate.getIssuedBy().getUName();
+ long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
+ long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
+
+ // Add the certificate to the intent.
+ domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_TO_CNAME, issuedToCName);
+ domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_TO_ONAME, issuedToOName);
+ domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_TO_UNAME, issuedToUName);
+ domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_BY_CNAME, issuedByCName);
+ domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_BY_ONAME, issuedByOName);
+ domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_BY_UNAME, issuedByUName);
+ domainsIntent.putExtra(DomainsActivity.SSL_START_DATE, startDateLong);
+ domainsIntent.putExtra(DomainsActivity.SSL_END_DATE, endDateLong);
+ }
+
+ // Make it so.
+ startActivity(domainsIntent);
+ }
+
+ // Consume the event.
+ return true;
+ } else { // There is no match with the options menu. Pass the event up to the parent method.
+ // Don't consume the event.
+ return super.onOptionsItemSelected(menuItem);
+ }
+ }
+
+ // removeAllCookies is deprecated, but it is required for API < 21.
+ @Override
+ public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
+ // Get a handle for the shared preferences.
+ SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
+
+ // Get the menu item ID.
+ int menuItemId = menuItem.getItemId();
+
+ // Run the commands that correspond to the selected menu item.
+ if (menuItemId == R.id.clear_and_exit) { // Clear and exit.
+ // Clear and exit Privacy Browser.
+ clearAndExit();
+ } else if (menuItemId == R.id.home) { // Home.
+ // Load the homepage.
+ loadUrl(currentWebView, sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
+ } else if (menuItemId == R.id.back) { // Back.
+ // Check if the WebView can go back.
+ if (currentWebView.canGoBack()) {
+ // Get the current web back forward list.
+ WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
+
+ // Get the previous entry URL.
+ String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
+
+ // Apply the domain settings.
+ applyDomainSettings(currentWebView, previousUrl, false, false, false);
+
+ // Load the previous website in the history.
+ currentWebView.goBack();
+ }
+ } else if (menuItemId == R.id.forward) { // Forward.
+ // Check if the WebView can go forward.
+ if (currentWebView.canGoForward()) {
+ // Get the current web back forward list.
+ WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
+
+ // Get the next entry URL.
+ String nextUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() + 1).getUrl();
+
+ // Apply the domain settings.
+ applyDomainSettings(currentWebView, nextUrl, false, false, false);
+
+ // Load the next website in the history.
+ currentWebView.goForward();
+ }
+ } else if (menuItemId == R.id.history) { // History.
+ // Instantiate the URL history dialog.
+ DialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(currentWebView.getWebViewFragmentId());
+
+ // Show the URL history dialog.
+ urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
+ } else if (menuItemId == R.id.open) { // Open.
+ // Instantiate the open file dialog.
+ DialogFragment openDialogFragment = new OpenDialog();
+
+ // Show the open file dialog.
+ openDialogFragment.show(getSupportFragmentManager(), getString(R.string.open));
+ } else if (menuItemId == R.id.requests) { // Requests.
+ // Populate the resource requests.
+ RequestsActivity.resourceRequests = currentWebView.getResourceRequests();
+
+ // Create an intent to launch the Requests activity.
+ Intent requestsIntent = new Intent(this, RequestsActivity.class);
+
+ // Add the block third-party requests status to the intent.
+ requestsIntent.putExtra("block_all_third_party_requests", currentWebView.getBlockAllThirdPartyRequests());
+
+ // Make it so.
+ startActivity(requestsIntent);
+ } else if (menuItemId == R.id.downloads) { // Downloads.
+ // Try the default system download manager.
+ try {
+ // Launch the default system Download Manager.
+ Intent defaultDownloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
+
+ // Launch as a new task so that the download manager and Privacy Browser show as separate windows in the recent tasks list.
+ defaultDownloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+
+ // Make it so.
+ startActivity(defaultDownloadManagerIntent);
+ } catch (Exception defaultDownloadManagerException) {
+ // Try a generic file manager.
+ try {
+ // Create a generic file manager intent.
+ Intent genericFileManagerIntent = new Intent(Intent.ACTION_VIEW);
+
+ // Open the download directory.
+ genericFileManagerIntent.setDataAndType(Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()), DocumentsContract.Document.MIME_TYPE_DIR);
+
+ // Launch as a new task so that the file manager and Privacy Browser show as separate windows in the recent tasks list.
+ genericFileManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+
+ // Make it so.
+ startActivity(genericFileManagerIntent);
+ } catch (Exception genericFileManagerException) {
+ // Try an alternate file manager.
+ try {
+ // Create an alternate file manager intent.
+ Intent alternateFileManagerIntent = new Intent(Intent.ACTION_VIEW);
+
+ // Open the download directory.
+ alternateFileManagerIntent.setDataAndType(Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()), "resource/folder");
+
+ // Launch as a new task so that the file manager and Privacy Browser show as separate windows in the recent tasks list.
+ alternateFileManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+
+ // Open the alternate file manager.
+ startActivity(alternateFileManagerIntent);
+ } catch (Exception alternateFileManagerException) {
+ // Display a snackbar.
+ Snackbar.make(currentWebView, R.string.no_file_manager_detected, Snackbar.LENGTH_INDEFINITE).show();
+ }
+ }
+ }
+ } else if (menuItemId == R.id.domains) { // Domains.
+ // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
+ reapplyDomainSettingsOnRestart = true;
+
+ // Launch the domains activity.
+ Intent domainsIntent = new Intent(this, DomainsActivity.class);
+
+ // Add the extra information to the intent.
+ domainsIntent.putExtra(DomainsActivity.CURRENT_URL, currentWebView.getUrl());
+ domainsIntent.putExtra(DomainsActivity.CURRENT_IP_ADDRESSES, currentWebView.getCurrentIpAddresses());
+
+ // Get the current certificate.
+ SslCertificate sslCertificate = currentWebView.getCertificate();
+
+ // Check to see if the SSL certificate is populated.
+ if (sslCertificate != null) {
+ // Extract the certificate to strings.
+ String issuedToCName = sslCertificate.getIssuedTo().getCName();
+ String issuedToOName = sslCertificate.getIssuedTo().getOName();
+ String issuedToUName = sslCertificate.getIssuedTo().getUName();
+ String issuedByCName = sslCertificate.getIssuedBy().getCName();
+ String issuedByOName = sslCertificate.getIssuedBy().getOName();
+ String issuedByUName = sslCertificate.getIssuedBy().getUName();
+ long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
+ long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
+
+ // Add the certificate to the intent.
+ domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
+ domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
+ domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
+ domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
+ domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
+ domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
+ domainsIntent.putExtra("ssl_start_date", startDateLong);
+ domainsIntent.putExtra("ssl_end_date", endDateLong);
+ }
+
+ // Make it so.
+ startActivity(domainsIntent);
+ } else if (menuItemId == R.id.settings) { // Settings.
+ // Set the flag to reapply app settings on restart when returning from Settings.
+ reapplyAppSettingsOnRestart = true;
+
+ // Set the flag to reapply the domain settings on restart when returning from Settings.
+ reapplyDomainSettingsOnRestart = true;
+
+ // Launch the settings activity.
+ Intent settingsIntent = new Intent(this, SettingsActivity.class);
+ startActivity(settingsIntent);
+ } else if (menuItemId == R.id.import_export) { // Import/Export.
+ // Create an intent to launch the import/export activity.
+ Intent importExportIntent = new Intent(this, ImportExportActivity.class);
+
+ // Make it so.
+ startActivity(importExportIntent);
+ } else if (menuItemId == R.id.logcat) { // Logcat.
+ // Create an intent to launch the logcat activity.
+ Intent logcatIntent = new Intent(this, LogcatActivity.class);
+
+ // Make it so.
+ startActivity(logcatIntent);
+ } else if (menuItemId == R.id.webview_devtools) { // WebView Dev.
+ // Create a WebView DevTools intent.
+ Intent webViewDevToolsIntent = new Intent("com.android.webview.SHOW_DEV_UI");
+
+ // Launch as a new task so that the WebView DevTools and Privacy Browser show as a separate windows in the recent tasks list.
+ webViewDevToolsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+
+ // Make it so.
+ startActivity(webViewDevToolsIntent);
+ } else if (menuItemId == R.id.guide) { // Guide.
+ // Create an intent to launch the guide activity.
+ Intent guideIntent = new Intent(this, GuideActivity.class);
+
+ // Make it so.
+ startActivity(guideIntent);
+ } else if (menuItemId == R.id.about) { // About
+ // Create an intent to launch the about activity.
+ Intent aboutIntent = new Intent(this, AboutActivity.class);
+
+ // Create a string array for the blocklist versions.
+ 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],
+ ultraList.get(0).get(0)[0], ultraPrivacy.get(0).get(0)[0]};
+
+ // Add the blocklist versions to the intent.
+ aboutIntent.putExtra(AboutActivity.BLOCKLIST_VERSIONS, blocklistVersions);
+
+ // Make it so.
+ startActivity(aboutIntent);
+ }
+
+ // Close the navigation drawer.
+ drawerLayout.closeDrawer(GravityCompat.START);
+ return true;
+ }
+
+ @Override
+ public void onPostCreate(Bundle savedInstanceState) {
+ // Run the default commands.
+ super.onPostCreate(savedInstanceState);
+
+ // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished. This creates the navigation drawer icon.
+ actionBarDrawerToggle.syncState();
+ }
+
+ @Override
+ public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
+ // Get the hit test result.
+ final WebView.HitTestResult hitTestResult = currentWebView.getHitTestResult();
+
+ // Define the URL strings.
+ final String imageUrl;
+ final String linkUrl;
+
+ // Get handles for the system managers.
+ final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
+
+ // Remove the lint errors below that the clipboard manager might be null.
+ assert clipboardManager != null;
+
+ // Process the link according to the type.
+ switch (hitTestResult.getType()) {
+ // `SRC_ANCHOR_TYPE` is a link.
+ case WebView.HitTestResult.SRC_ANCHOR_TYPE:
+ // Get the target URL.
+ linkUrl = hitTestResult.getExtra();
+
+ // Set the target URL as the title of the `ContextMenu`.
+ menu.setHeaderTitle(linkUrl);
+
+ // Add an Open in New Tab entry.
+ menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
+ // Load the link URL in a new tab and move to it.
+ addNewTab(linkUrl, true);
+
+ // Consume the event.
+ return true;
+ });
+
+ // Add an Open in Background entry.
+ menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
+ // Load the link URL in a new tab but do not move to it.
+ addNewTab(linkUrl, false);
+
+ // Consume the event.
+ return true;
+ });
+
+ // Add an Open with App entry.
+ menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
+ openWithApp(linkUrl);
+
+ // Consume the event.
+ return true;
+ });
+
+ // Add an Open with Browser entry.
+ menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
+ openWithBrowser(linkUrl);
+
+ // Consume the event.
+ return true;
+ });
+
+ // Add a Copy URL entry.
+ menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
+ // Save the link URL in a `ClipData`.
+ ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
+
+ // Set the `ClipData` as the clipboard's primary clip.
+ clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
+
+ // Consume the event.
+ return true;
+ });
+
+ // Add a Save URL entry.
+ menu.add(R.string.save_url).setOnMenuItemClickListener((MenuItem item) -> {
+ // Check the download preference.
+ if (downloadWithExternalApp) { // Download with an external app.
+ downloadUrlWithExternalApp(linkUrl);
+ } else { // Handle the download inside of Privacy Browser.
+ // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
+ PrepareSaveDialogCoroutine.prepareSaveDialog(this, getSupportFragmentManager(), linkUrl, currentWebView.getSettings().getUserAgentString(), currentWebView.getAcceptCookies());
+ }
+
+ // Consume the event.
+ return true;
+ });
+
+ // Add an empty Cancel entry, which by default closes the context menu.
+ menu.add(R.string.cancel);
+ break;
+
+ // `IMAGE_TYPE` is an image.
+ case WebView.HitTestResult.IMAGE_TYPE:
+ // Get the image URL.
+ imageUrl = hitTestResult.getExtra();
+
+ // Remove the incorrect lint warning below that the image URL might be null.
+ assert imageUrl != null;
+
+ // Set the context menu title.
+ if (imageUrl.startsWith("data:")) { // The image data is contained in within the URL, making it exceedingly long.
+ // Truncate the image URL before making it the title.
+ menu.setHeaderTitle(imageUrl.substring(0, 100));
+ } else { // The image URL does not contain the full image data.
+ // Set the image URL as the title of the context menu.
+ menu.setHeaderTitle(imageUrl);
+ }
+
+ // Add an Open in New Tab entry.
+ menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
+ // Load the image in a new tab.
+ addNewTab(imageUrl, true);
+
+ // Consume the event.
+ return true;
+ });
+
+ // Add an Open with App entry.
+ menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
+ // Open the image URL with an external app.
+ openWithApp(imageUrl);
+
+ // Consume the event.
+ return true;
+ });
+
+ // Add an Open with Browser entry.
+ menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
+ // Open the image URL with an external browser.
+ openWithBrowser(imageUrl);
+
+ // Consume the event.
+ return true;
+ });
+
+ // Add a View Image entry.
+ menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
+ // Load the image in the current tab.
+ loadUrl(currentWebView, imageUrl);
+
+ // Consume the event.
+ return true;
+ });
+
+ // Add a Save Image entry.
+ menu.add(R.string.save_image).setOnMenuItemClickListener((MenuItem item) -> {
+ // Check the download preference.
+ if (downloadWithExternalApp) { // Download with an external app.
+ downloadUrlWithExternalApp(imageUrl);
+ } else { // Handle the download inside of Privacy Browser.
+ // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
+ PrepareSaveDialogCoroutine.prepareSaveDialog(this, getSupportFragmentManager(), imageUrl, currentWebView.getSettings().getUserAgentString(), currentWebView.getAcceptCookies());
+ }
+
+ // Consume the event.
+ return true;
+ });
+
+ // Add a Copy URL entry.
+ menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
+ // Save the image URL in a clip data.
+ ClipData imageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
+
+ // Set the clip data as the clipboard's primary clip.
+ clipboardManager.setPrimaryClip(imageTypeClipData);
+
+ // Consume the event.
+ return true;
+ });
+
+ // Add an empty Cancel entry, which by default closes the context menu.
+ menu.add(R.string.cancel);
+ break;
+
+ // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
+ case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
+ // Get the image URL.
+ imageUrl = hitTestResult.getExtra();
+
+ // Instantiate a handler.
+ Handler handler = new Handler();
+
+ // Get a message from the handler.
+ Message message = handler.obtainMessage();
+
+ // Request the image details from the last touched node be returned in the message.
+ currentWebView.requestFocusNodeHref(message);
+
+ // Get the link URL from the message data.
+ linkUrl = message.getData().getString("url");
+
+ // Set the link URL as the title of the context menu.
+ menu.setHeaderTitle(linkUrl);
+
+ // Add an Open in New Tab entry.
+ menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
+ // Load the link URL in a new tab and move to it.
+ addNewTab(linkUrl, true);
+
+ // Consume the event.
+ return true;
+ });
+
+ // Add an Open in Background entry.
+ menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
+ // Lod the link URL in a new tab but do not move to it.
+ addNewTab(linkUrl, false);
+
+ // Consume the event.
+ return true;
+ });
+
+ // Add an Open Image in New Tab entry.
+ menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
+ // Load the image in a new tab and move to it.
+ addNewTab(imageUrl, true);
+
+ // Consume the event.
+ return true;
+ });
+
+ // Add an Open with App entry.
+ menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
+ // Open the link URL with an external app.
+ openWithApp(linkUrl);
+
+ // Consume the event.
+ return true;
+ });
+
+ // Add an Open with Browser entry.
+ menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
+ // Open the link URL with an external browser.
+ openWithBrowser(linkUrl);
+
+ // Consume the event.
+ return true;
+ });
+
+ // Add a View Image entry.
+ menu.add(R.string.view_image).setOnMenuItemClickListener((MenuItem item) -> {
+ // View the image in the current tab.
+ loadUrl(currentWebView, imageUrl);
+
+ // Consume the event.
+ return true;
+ });
+
+ // Add a Save Image entry.
+ menu.add(R.string.save_image).setOnMenuItemClickListener((MenuItem item) -> {
+ // Check the download preference.
+ if (downloadWithExternalApp) { // Download with an external app.
+ downloadUrlWithExternalApp(imageUrl);
+ } else { // Handle the download inside of Privacy Browser.
+ // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
+ PrepareSaveDialogCoroutine.prepareSaveDialog(this, getSupportFragmentManager(), imageUrl, currentWebView.getSettings().getUserAgentString(), currentWebView.getAcceptCookies());
+ }
+
+ // Consume the event.
+ return true;
+ });
+
+ // Add a Copy URL entry.
+ menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
+ // Save the link URL in a clip data.
+ ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
+
+ // Set the clip data as the clipboard's primary clip.
+ clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
+
+ // Consume the event.
+ return true;
+ });
+
+ // Add a Save URL entry.
+ menu.add(R.string.save_url).setOnMenuItemClickListener((MenuItem item) -> {
+ // Check the download preference.
+ if (downloadWithExternalApp) { // Download with an external app.
+ downloadUrlWithExternalApp(linkUrl);
+ } else { // Handle the download inside of Privacy Browser.
+ // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
+ PrepareSaveDialogCoroutine.prepareSaveDialog(this, getSupportFragmentManager(), linkUrl, currentWebView.getSettings().getUserAgentString(), currentWebView.getAcceptCookies());
+ }
+
+ // Consume the event.
+ return true;
+ });
+
+ // Add an empty Cancel entry, which by default closes the context menu.
+ menu.add(R.string.cancel);
+ break;
+
+ case WebView.HitTestResult.EMAIL_TYPE:
+ // Get the target URL.
+ linkUrl = hitTestResult.getExtra();
+
+ // Set the target URL as the title of the `ContextMenu`.
+ menu.setHeaderTitle(linkUrl);
+
+ // Add a Write Email entry.
+ menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
+ // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
+ Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
+
+ // Parse the url and set it as the data for the `Intent`.
+ emailIntent.setData(Uri.parse("mailto:" + linkUrl));
+
+ // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
+ emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+
+ try {
+ // Make it so.
+ startActivity(emailIntent);
+ } catch (ActivityNotFoundException exception) {
+ // Display a snackbar.
+ Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
+ }
+
+ // Consume the event.
+ return true;
+ });
+
+ // Add a Copy Email Address entry.
+ menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
+ // Save the email address in a `ClipData`.
+ ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
+
+ // Set the `ClipData` as the clipboard's primary clip.
+ clipboardManager.setPrimaryClip(srcEmailTypeClipData);
+
+ // Consume the event.
+ return true;
+ });
+
+ // Add an empty Cancel entry, which by default closes the context menu.
+ menu.add(R.string.cancel);
+ break;
+ }
+ }
+
+ @Override
+ public void onCreateBookmark(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
+ // Get a handle for the bookmarks list view.
+ ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
+
+ // Get the dialog.
+ Dialog dialog = dialogFragment.getDialog();
+
+ // Remove the incorrect lint warning below that the dialog might be null.
+ assert dialog != null;
+
+ // Get the views from the dialog fragment.
+ EditText createBookmarkNameEditText = dialog.findViewById(R.id.create_bookmark_name_edittext);
+ EditText createBookmarkUrlEditText = dialog.findViewById(R.id.create_bookmark_url_edittext);
+
+ // Extract the strings from the edit texts.
+ String bookmarkNameString = createBookmarkNameEditText.getText().toString();
+ String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
+
+ // Create a favorite icon byte array output stream.
+ ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
+
+ // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
+ favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
+
+ // Convert the favorite icon byte array stream to a byte array.
+ byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
+
+ // Display the new bookmark below the current items in the (0 indexed) list.
+ int newBookmarkDisplayOrder = bookmarksListView.getCount();
+
+ // Create the bookmark.
+ bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
+
+ // Update the bookmarks cursor with the current contents of this folder.
+ bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
+
+ // Update the list view.
+ bookmarksCursorAdapter.changeCursor(bookmarksCursor);
+
+ // Scroll to the new bookmark.
+ bookmarksListView.setSelection(newBookmarkDisplayOrder);
+ }
+
+ @Override
+ public void onCreateBookmarkFolder(DialogFragment dialogFragment, @NonNull Bitmap favoriteIconBitmap) {
+ // Get a handle for the bookmarks list view.
+ ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
+
+ // Get the dialog.
+ Dialog dialog = dialogFragment.getDialog();
+
+ // Remove the incorrect lint warning below that the dialog might be null.
+ assert dialog != null;
+
+ // Get handles for the views in the dialog fragment.
+ EditText folderNameEditText = dialog.findViewById(R.id.folder_name_edittext);
+ RadioButton defaultIconRadioButton = dialog.findViewById(R.id.default_icon_radiobutton);
+ ImageView defaultIconImageView = dialog.findViewById(R.id.default_icon_imageview);
+
+ // Get new folder name string.
+ String folderNameString = folderNameEditText.getText().toString();
+
+ // Create a folder icon bitmap.
+ Bitmap folderIconBitmap;
+
+ // Set the folder icon bitmap according to the dialog.
+ if (defaultIconRadioButton.isChecked()) { // Use the default folder icon.
+ // Get the default folder icon drawable.
+ Drawable folderIconDrawable = defaultIconImageView.getDrawable();
+
+ // Convert the folder icon drawable to a bitmap drawable.
+ BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
+
+ // Convert the folder icon bitmap drawable to a bitmap.
+ folderIconBitmap = folderIconBitmapDrawable.getBitmap();
+ } else { // Use the WebView favorite icon.
+ // Copy the favorite icon bitmap to the folder icon bitmap.
+ folderIconBitmap = favoriteIconBitmap;
+ }
+
+ // Create a folder icon byte array output stream.
+ ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
+
+ // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
+ folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
+
+ // Convert the folder icon byte array stream to a byte array.
+ byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
+
+ // Move all the bookmarks down one in the display order.
+ for (int i = 0; i < bookmarksListView.getCount(); i++) {
+ int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
+ bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
+ }
+
+ // Create the folder, which will be placed at the top of the `ListView`.
+ bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
+
+ // Update the bookmarks cursor with the current contents of this folder.
+ bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
+
+ // Update the list view.
+ bookmarksCursorAdapter.changeCursor(bookmarksCursor);
+
+ // Scroll to the new folder.
+ bookmarksListView.setSelection(0);
+ }
+
+ private void loadUrlFromTextBox() {
+ // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
+ String unformattedUrlString = urlEditText.getText().toString().trim();
+
+ // Initialize the formatted URL string.
+ String url = "";
+
+ // Check to see if the unformatted URL string is a valid URL. Otherwise, convert it into a search.
+ if (unformattedUrlString.startsWith("content://")) { // This is a Content URL.
+ // Load the entire content URL.
+ url = unformattedUrlString;
+ } else if (Patterns.WEB_URL.matcher(unformattedUrlString).matches() || unformattedUrlString.startsWith("http://") || unformattedUrlString.startsWith("https://") ||
+ unformattedUrlString.startsWith("file://")) { // This is a standard URL.
+ // Add `https://` at the beginning if there is no protocol. Otherwise the app will segfault.
+ if (!unformattedUrlString.startsWith("http") && !unformattedUrlString.startsWith("file://")) {
+ unformattedUrlString = "https://" + unformattedUrlString;
+ }
+
+ // Initialize the unformatted URL.
+ URL unformattedUrl = null;
+
+ // Convert the unformatted URL string to a URL, then to a URI, and then back to a string, which sanitizes the input and adds in any missing components.
+ try {
+ unformattedUrl = new URL(unformattedUrlString);
+ } catch (MalformedURLException e) {
+ e.printStackTrace();
+ }
+
+ // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
+ String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
+ String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
+ String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
+ String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
+ String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
+
+ // Build the URI.
+ Uri.Builder uri = new Uri.Builder();
+ uri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
+
+ // Decode the URI as a UTF-8 string in.
+ try {
+ url = URLDecoder.decode(uri.build().toString(), "UTF-8");
+ } catch (UnsupportedEncodingException exception) {
+ // Do nothing. The formatted URL string will remain blank.
+ }
+ } else if (!unformattedUrlString.isEmpty()){ // This is not a URL, but rather a search string.
+ // Create an encoded URL String.
+ String encodedUrlString;
+
+ // Sanitize the search input.
+ try {
+ encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
+ } catch (UnsupportedEncodingException exception) {
+ encodedUrlString = "";
+ }
+
+ // Add the base search URL.
+ url = searchURL + encodedUrlString;
+ }
+
+ // 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.
+ urlEditText.clearFocus();
+
+ // Make it so.
+ loadUrl(currentWebView, url);
+ }
+
+ private void loadUrl(NestedScrollWebView nestedScrollWebView, String url) {
+ // Sanitize the URL.
+ url = sanitizeUrl(url);
+
+ // Apply the domain settings and load the URL.
+ applyDomainSettings(nestedScrollWebView, url, true, false, true);
+ }
+
+ public void findPreviousOnPage(View view) {
+ // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
+ currentWebView.findNext(false);
+ }
+
+ public void findNextOnPage(View view) {
+ // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
+ currentWebView.findNext(true);
+ }
+
+ public void closeFindOnPage(View view) {
+ // Get a handle for the views.
+ Toolbar toolbar = findViewById(R.id.toolbar);
+ LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
+ EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
+
+ // Delete the contents of `find_on_page_edittext`.
+ findOnPageEditText.setText(null);
+
+ // Clear the highlighted phrases if the WebView is not null.
+ if (currentWebView != null) {
+ currentWebView.clearMatches();
+ }
+
+ // Hide the find on page linear layout.
+ findOnPageLinearLayout.setVisibility(View.GONE);
+
+ // Show the toolbar.
+ toolbar.setVisibility(View.VISIBLE);
+
+ // Get a handle for the input method manager.
+ InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
+
+ // Remove the lint warning below that the input method manager might be null.
+ assert inputMethodManager != null;
+
+ // Hide the keyboard.
+ inputMethodManager.hideSoftInputFromWindow(toolbar.getWindowToken(), 0);
+ }
+
+ @Override
+ public void onApplyNewFontSize(DialogFragment dialogFragment) {
+ // Remove the incorrect lint warning below that the dialog fragment might be null.
+ assert dialogFragment != null;
+
+ // Get the dialog.
+ Dialog dialog = dialogFragment.getDialog();
+
+ // Remove the incorrect lint warning below tha the dialog might be null.
+ assert dialog != null;
+
+ // Get a handle for the font size edit text.
+ EditText fontSizeEditText = dialog.findViewById(R.id.font_size_edittext);
+
+ // Initialize the new font size variable with the current font size.
+ int newFontSize = currentWebView.getSettings().getTextZoom();
+
+ // Get the font size from the edit text.
+ try {
+ newFontSize = Integer.parseInt(fontSizeEditText.getText().toString());
+ } catch (Exception exception) {
+ // If the edit text does not contain a valid font size do nothing.
+ }
+
+ // Apply the new font size.
+ currentWebView.getSettings().setTextZoom(newFontSize);
+ }
+
+ @Override
+ public void onOpen(DialogFragment dialogFragment) {
+ // Get the dialog.
+ Dialog dialog = dialogFragment.getDialog();
+
+ // Remove the incorrect lint warning below that the dialog might be null.
+ assert dialog != null;
+
+ // Get handles for the views.
+ EditText fileNameEditText = dialog.findViewById(R.id.file_name_edittext);
+ CheckBox mhtCheckBox = dialog.findViewById(R.id.mht_checkbox);
+
+ // Get the file path string.
+ String openFilePath = fileNameEditText.getText().toString();
+
+ // Apply the domain settings. This resets the favorite icon and removes any domain settings.
+ applyDomainSettings(currentWebView, openFilePath, true, false, false);
+
+ // Open the file according to the type.
+ if (mhtCheckBox.isChecked()) { // Force opening of an MHT file.
+ try {
+ // Get the MHT file input stream.
+ InputStream mhtFileInputStream = getContentResolver().openInputStream(Uri.parse(openFilePath));
+
+ // Create a temporary MHT file.
+ File temporaryMhtFile = File.createTempFile("temporary_mht_file", ".mht", getCacheDir());
+
+ // Get a file output stream for the temporary MHT file.
+ FileOutputStream temporaryMhtFileOutputStream = new FileOutputStream(temporaryMhtFile);
+
+ // Create a transfer byte array.
+ byte[] transferByteArray = new byte[1024];
+
+ // Create an integer to track the number of bytes read.
+ int bytesRead;
+
+ // Copy the temporary MHT file input stream to the MHT output stream.
+ while ((bytesRead = mhtFileInputStream.read(transferByteArray)) > 0) {
+ temporaryMhtFileOutputStream.write(transferByteArray, 0, bytesRead);