2 * Copyright 2015-2017 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.annotation.SuppressLint;
25 import android.app.DialogFragment;
26 import android.app.DownloadManager;
27 import android.content.BroadcastReceiver;
28 import android.content.ClipData;
29 import android.content.ClipboardManager;
30 import android.content.Context;
31 import android.content.Intent;
32 import android.content.IntentFilter;
33 import android.content.SharedPreferences;
34 import android.content.res.Configuration;
35 import android.database.Cursor;
36 import android.graphics.Bitmap;
37 import android.graphics.drawable.BitmapDrawable;
38 import android.graphics.drawable.Drawable;
39 import android.net.Uri;
40 import android.net.http.SslCertificate;
41 import android.net.http.SslError;
42 import android.os.Build;
43 import android.os.Bundle;
44 import android.preference.PreferenceManager;
45 import android.print.PrintDocumentAdapter;
46 import android.print.PrintManager;
47 import android.support.annotation.NonNull;
48 import android.support.design.widget.CoordinatorLayout;
49 import android.support.design.widget.NavigationView;
50 import android.support.design.widget.Snackbar;
51 import android.support.v4.app.ActivityCompat;
52 import android.support.v4.content.ContextCompat;
53 import android.support.v4.view.GravityCompat;
54 import android.support.v4.widget.DrawerLayout;
55 import android.support.v4.widget.SwipeRefreshLayout;
56 import android.support.v7.app.ActionBar;
57 import android.support.v7.app.ActionBarDrawerToggle;
58 import android.support.v7.app.AppCompatActivity;
59 import android.support.v7.app.AppCompatDialogFragment;
60 import android.support.v7.widget.Toolbar;
61 import android.text.Editable;
62 import android.text.TextWatcher;
63 import android.util.Patterns;
64 import android.view.ContextMenu;
65 import android.view.GestureDetector;
66 import android.view.KeyEvent;
67 import android.view.Menu;
68 import android.view.MenuItem;
69 import android.view.MotionEvent;
70 import android.view.View;
71 import android.view.WindowManager;
72 import android.view.inputmethod.InputMethodManager;
73 import android.webkit.CookieManager;
74 import android.webkit.DownloadListener;
75 import android.webkit.SslErrorHandler;
76 import android.webkit.WebBackForwardList;
77 import android.webkit.WebChromeClient;
78 import android.webkit.WebResourceResponse;
79 import android.webkit.WebStorage;
80 import android.webkit.WebView;
81 import android.webkit.WebViewClient;
82 import android.webkit.WebViewDatabase;
83 import android.widget.EditText;
84 import android.widget.FrameLayout;
85 import android.widget.ImageView;
86 import android.widget.LinearLayout;
87 import android.widget.ProgressBar;
88 import android.widget.RelativeLayout;
89 import android.widget.TextView;
91 import com.stoutner.privacybrowser.BannerAd;
92 import com.stoutner.privacybrowser.BuildConfig;
93 import com.stoutner.privacybrowser.R;
94 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
95 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
96 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
97 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
98 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
99 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
100 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
101 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
103 import java.io.BufferedReader;
104 import java.io.ByteArrayInputStream;
105 import java.io.IOException;
106 import java.io.InputStreamReader;
107 import java.io.UnsupportedEncodingException;
108 import java.net.MalformedURLException;
110 import java.net.URLEncoder;
111 import java.util.HashMap;
112 import java.util.HashSet;
113 import java.util.Map;
114 import java.util.Set;
116 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
117 public class MainWebViewActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, CreateHomeScreenShortcutDialog.CreateHomeScreenSchortcutListener,
118 SslCertificateErrorDialog.SslCertificateErrorListener, DownloadFileDialog.DownloadFileListener, DownloadImageDialog.DownloadImageListener, UrlHistoryDialog.UrlHistoryListener {
120 // `appBar` is public static so it can be accessed from `OrbotProxyHelper`.
121 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applySettings()`.
122 public static ActionBar appBar;
124 // `favoriteIcon` is public static so it can be accessed from `CreateHomeScreenShortcutDialog`, `BookmarksActivity`, `CreateBookmarkDialog`, `CreateBookmarkFolderDialog`, and `EditBookmarkDialog`.
125 // It is also used in `onCreate()` and `onCreateHomeScreenShortcutCreate()`.
126 public static Bitmap favoriteIcon;
128 // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`, `CreateBookmarkDialog`, and `AddDomainDialog`.
129 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
130 public static String formattedUrlString;
132 // `sslCertificate` is public static so it can be accessed from `ViewSslCertificateDialog`. It is also used in `onCreate()`.
133 public static SslCertificate sslCertificate;
135 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`.
136 public static String orbotStatus;
138 // `webViewTitle` is public static so it can be accessed from `CreateBookmarkDialog` and `CreateHomeScreenShortcutDialog`. It is also used in `onCreate()`.
139 public static String webViewTitle;
142 // `navigatingHistory` is used in `onCreate()` and `onNavigationItemSelected()`.
143 private boolean navigatingHistory;
145 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, and `onBackPressed()`.
146 private DrawerLayout drawerLayout;
148 // `rootCoordinatorLayout` is used in `onCreate()` and `applySettings()`.
149 private CoordinatorLayout rootCoordinatorLayout;
151 // 'mainWebView' is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`, `findNextOnPage()`, `closeFindOnPage()`, and `loadUrlFromTextBox()`.
152 private WebView mainWebView;
154 // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
155 private FrameLayout fullScreenVideoFrameLayout;
157 // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu`, and `onRestart()`.
158 private SwipeRefreshLayout swipeRefreshLayout;
160 // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `loadUrlFromTextBox()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
161 private CookieManager cookieManager;
163 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
164 private final Map<String, String> customHeaders = new HashMap<>();
166 // `javaScriptEnabled` is also used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `applySettings()`.
167 // It is `Boolean` instead of `boolean` because `applySettings()` needs to know if it is `null`.
168 private Boolean javaScriptEnabled;
170 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applySettings()`.
171 private boolean firstPartyCookiesEnabled;
173 // `thirdPartyCookiesEnabled` used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
174 private boolean thirdPartyCookiesEnabled;
176 // `domStorageEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
177 private boolean domStorageEnabled;
179 // `saveFormDataEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
180 private boolean saveFormDataEnabled;
182 // `swipeToRefreshEnabled` is used in `onPrepareOptionsMenu()` and `applySettings()`.
183 private boolean swipeToRefreshEnabled;
185 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applySettings()`.
186 private String homepage;
188 // `javaScriptDisabledSearchURL` is used in `loadURLFromTextBox()` and `applySettings()`.
189 private String javaScriptDisabledSearchURL;
191 // `javaScriptEnabledSearchURL` is used in `loadURLFromTextBox()` and `applySettings()`.
192 private String javaScriptEnabledSearchURL;
194 // `adBlockerEnabled` is used in `onCreate()` and `applySettings()`.
195 private boolean adBlockerEnabled;
197 // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applySettings()`.
198 private boolean fullScreenBrowsingModeEnabled;
200 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applySettings()`.
201 private boolean inFullScreenBrowsingMode;
203 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applySettings()`.
204 private boolean hideSystemBarsOnFullscreen;
206 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applySettings()`.
207 private boolean translucentNavigationBarOnFullscreen;
209 // `proxyThroughOrbot` is used in `onCreate()` and `applySettings()`
210 private boolean proxyThroughOrbot;
212 // `pendingUrl` is used in `onCreate()` and `applySettings()`
213 private static String pendingUrl;
215 // `waitingForOrbotData` is used in `onCreate()` and `applySettings()`.
216 private String waitingForOrbotHTMLString;
218 // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
219 private LinearLayout findOnPageLinearLayout;
221 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
222 private EditText findOnPageEditText;
224 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
225 private Menu mainMenu;
227 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
228 private ActionBarDrawerToggle drawerToggle;
230 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
231 private Toolbar supportAppBar;
233 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `loadUrl()`.
234 private EditText urlTextBox;
236 // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
239 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
240 private SslErrorHandler sslErrorHandler;
242 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
243 private InputMethodManager inputMethodManager;
245 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
246 private RelativeLayout mainWebViewRelativeLayout;
249 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled. The whole premise of Privacy Browser is built around an understanding of these dangers.
250 @SuppressLint("SetJavaScriptEnabled")
251 protected void onCreate(Bundle savedInstanceState) {
252 super.onCreate(savedInstanceState);
253 setContentView(R.layout.drawerlayout);
255 // Get a handle for `inputMethodManager`.
256 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
258 // We need to use the `SupportActionBar` from `android.support.v7.app.ActionBar` until the minimum API is >= 21.
259 supportAppBar = (Toolbar) findViewById(R.id.app_bar);
260 setSupportActionBar(supportAppBar);
261 appBar = getSupportActionBar();
263 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
264 assert appBar != null;
266 // Add the custom url_app_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
267 appBar.setCustomView(R.layout.url_app_bar);
268 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
270 // Set the "go" button on the keyboard to load the URL in urlTextBox.
271 urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.urlTextBox);
272 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
274 public boolean onKey(View v, int keyCode, KeyEvent event) {
275 // If the event is a key-down event on the `enter` button, load the URL.
276 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
277 // Load the URL into the mainWebView and consume the event.
279 loadUrlFromTextBox();
280 } catch (UnsupportedEncodingException e) {
283 // If the enter key was pressed, consume the event.
286 // If any other key was pressed, do not consume the event.
292 // Set `waitingForOrbotHTMLString`.
293 waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
295 // Initialize `pendingUrl`.
298 // Set the initial Orbot status.
299 orbotStatus = "unknown";
301 // Create an Orbot status `BroadcastReceiver`.
302 BroadcastReceiver orbotStatusBroadcastReceiver = new BroadcastReceiver() {
304 public void onReceive(Context context, Intent intent) {
305 // Store the content of the status message in `orbotStatus`.
306 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
308 // If we are waiting on `pendingUrl`, load it now that Orbot is connected.
309 if (orbotStatus.equals("ON") && !pendingUrl.isEmpty()) {
311 // Wait 500 milliseconds, because Orbot isn't really ready yet.
314 } catch (InterruptedException exception) {
318 // Copy `pendingUrl` to `formattedUrlString` and reset `pendingUrl` to be empty.
319 formattedUrlString = pendingUrl;
322 // Load `formattedUrlString
323 loadUrl(formattedUrlString);
328 // Register `orbotStatusBroadcastReceiver` on `this` context.
329 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
331 // Get handles for views that need to be accessed.
332 drawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout);
333 rootCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.root_coordinatorlayout);
334 mainWebViewRelativeLayout = (RelativeLayout) findViewById(R.id.main_webview_relativelayout);
335 mainWebView = (WebView) findViewById(R.id.mainWebView);
336 findOnPageLinearLayout = (LinearLayout) findViewById(R.id.find_on_page_linearlayout);
337 findOnPageEditText = (EditText) findViewById(R.id.find_on_page_edittext);
338 fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.full_screen_video_framelayout);
340 // Create a double-tap listener to toggle full-screen mode.
341 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
342 // Override `onDoubleTap()`. All other events are handled using the default settings.
344 public boolean onDoubleTap(MotionEvent event) {
345 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
346 // Toggle `inFullScreenBrowsingMode`.
347 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
349 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
350 // Hide the `appBar`.
353 // Hide the `BannerAd` in the free flavor.
354 if (BuildConfig.FLAVOR.contentEquals("free")) {
355 BannerAd.hideAd(adView);
358 // Modify the system bars.
359 if (hideSystemBarsOnFullscreen) { // Hide everything.
360 // Remove the translucent overlays.
361 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
363 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
364 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
366 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
367 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
368 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
370 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
372 // Set `rootCoordinatorLayout` to fill the whole screen.
373 rootCoordinatorLayout.setFitsSystemWindows(false);
374 } else { // Hide everything except the status and navigation bars.
375 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
376 rootCoordinatorLayout.setFitsSystemWindows(false);
378 if (translucentNavigationBarOnFullscreen) { // There is an Android Support Library bug that causes a scrim to print on the right side of the `Drawer Layout` when the navigation bar is displayed on the right of the screen.
379 // Set the navigation bar to be translucent.
380 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
383 } else { // Switch to normal viewing mode.
384 // Show the `appBar`.
387 // Show the `BannerAd` in the free flavor.
388 if (BuildConfig.FLAVOR.contentEquals("free")) {
389 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
390 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
392 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
393 adView = findViewById(R.id.adView);
396 // Remove the translucent navigation bar flag if it is set.
397 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
399 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
400 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
402 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
403 rootCoordinatorLayout.setSystemUiVisibility(0);
405 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
406 rootCoordinatorLayout.setFitsSystemWindows(true);
409 // Consume the double-tap.
411 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
417 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
418 mainWebView.setOnTouchListener(new View.OnTouchListener() {
420 public boolean onTouch(View v, MotionEvent event) {
421 // Send the `event` to `gestureDetector`.
422 return gestureDetector.onTouchEvent(event);
426 // Update `findOnPageCountTextView`.
427 mainWebView.setFindListener(new WebView.FindListener() {
428 // Get a handle for `findOnPageCountTextView`.
429 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
432 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
433 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
434 // Set `findOnPageCountTextView` to `0/0`.
435 findOnPageCountTextView.setText(R.string.zero_of_zero);
436 } else if (isDoneCounting) { // There are matches.
437 // `activeMatchOrdinal` is zero-based.
438 int activeMatch = activeMatchOrdinal + 1;
440 // Set `findOnPageCountTextView`.
441 findOnPageCountTextView.setText(activeMatch + "/" + numberOfMatches);
446 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
447 findOnPageEditText.addTextChangedListener(new TextWatcher() {
449 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
454 public void onTextChanged(CharSequence s, int start, int before, int count) {
459 public void afterTextChanged(Editable s) {
460 // Search for the text in `mainWebView`.
461 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
465 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
466 findOnPageEditText.setOnKeyListener(new View.OnKeyListener() {
468 public boolean onKey(View v, int keyCode, KeyEvent event) {
469 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
470 // Hide the soft keyboard. `0` indicates no additional flags.
471 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
473 // Consume the event.
475 } else { // A different key was pressed.
476 // Do not consume the event.
482 // Implement swipe to refresh
483 swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
484 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
485 swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
487 public void onRefresh() {
488 mainWebView.reload();
492 // `DrawerTitle` identifies the `DrawerLayout` in accessibility mode.
493 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
495 // Listen for touches on the navigation menu.
496 final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationview);
497 navigationView.setNavigationItemSelectedListener(this);
499 // Get handles for `navigationMenu` and the back and forward menu items. The menu is zero-based, so items 1, 2, and 3 are the second, third, and fourth entries in the menu.
500 final Menu navigationMenu = navigationView.getMenu();
501 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
502 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
503 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
505 // The `DrawerListener` allows us to update the Navigation Menu.
506 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
508 public void onDrawerSlide(View drawerView, float slideOffset) {
512 public void onDrawerOpened(View drawerView) {
516 public void onDrawerClosed(View drawerView) {
520 public void onDrawerStateChanged(int newState) {
521 // Update the `Back`, `Forward`, and `History` menu items every time the drawer opens.
522 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
523 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
524 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
526 // Hide the keyboard so we can see the navigation menu. `0` indicates no additional flags.
527 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
531 // drawerToggle creates the hamburger icon at the start of the AppBar.
532 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
534 // Initialize `adServerSet`.
535 final Set<String> adServersSet = new HashSet<>();
537 // Load the list of ad servers into memory.
539 // Load `pgl.yoyo.org_adservers.txt` into a `BufferedReader`.
540 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(getAssets().open("pgl.yoyo.org_adservers.txt")));
542 // Create a string for storing each ad server.
545 // Populate `adServersSet`.
546 while ((adServer = bufferedReader.readLine()) != null) {
547 adServersSet.add(adServer);
550 // Close `bufferedReader`.
551 bufferedReader.close();
552 } catch (IOException ioException) {
553 // We're pretty sure the asset exists, so we don't need to worry about the `IOException` ever being thrown.
556 mainWebView.setWebViewClient(new WebViewClient() {
557 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
558 // We have to use the deprecated `shouldOverrideUrlLoading` until API >= 24.
559 @SuppressWarnings("deprecation")
561 public boolean shouldOverrideUrlLoading(WebView view, String url) {
562 // Use an external email program if the link begins with `mailto:`.
563 if (url.startsWith("mailto:")) {
564 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
565 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
567 // Parse the url and set it as the data for the `Intent`.
568 emailIntent.setData(Uri.parse(url));
570 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
571 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
574 startActivity(emailIntent);
576 } else { // Load the URL in Privacy Browser.
582 // Block ads. We have to use the deprecated `shouldInterceptRequest` until minimum API >= 21.
583 @SuppressWarnings("deprecation")
585 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
586 if (adBlockerEnabled) { // Block ads.
587 // Extract the host from `url`.
588 Uri requestUri = Uri.parse(url);
589 String requestHost = requestUri.getHost();
591 // Initialize a variable to track if this is an ad server.
592 boolean requestHostIsAdServer = false;
594 // Check all the subdomains of `requestHost` if it is not `null` against the ad server database.
595 if (requestHost != null) {
596 while (requestHost.contains(".") && !requestHostIsAdServer) { // Stop checking if we run out of `.` or if we already know that `requestHostIsAdServer` is `true`.
597 if (adServersSet.contains(requestHost)) {
598 requestHostIsAdServer = true;
601 // Strip out the lowest subdomain of `requestHost`.
602 requestHost = requestHost.substring(requestHost.indexOf(".") + 1);
606 if (requestHostIsAdServer) { // It is an ad server.
607 // Return an empty `WebResourceResponse`.
608 return new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
609 } else { // It is not an ad server.
610 // `return null` loads the requested resource.
613 } else { // Ad blocking is disabled.
614 // `return null` loads the requested resource.
619 // Update the URL in urlTextBox when the page starts to load.
621 public void onPageStarted(WebView view, String url, Bitmap favicon) {
622 // Check to see if we are waiting on Orbot.
623 if (pendingUrl.isEmpty()) { // We are not waiting on Orbot, so we need to process the URL.
624 // We need to update `formattedUrlString` at the beginning of the load, so that if the user toggles JavaScript during the load the new website is reloaded.
625 formattedUrlString = url;
627 // Display the loading URL is the URL text box.
628 urlTextBox.setText(url);
630 // Apply any custom domain settings if the URL was loaded by navigating history.
631 if (navigatingHistory) {
632 applyDomainSettings(url);
637 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
639 public void onPageFinished(WebView view, String url) {
640 // Check to see if we are waiting on Orbot.
641 if (pendingUrl.isEmpty()) { // we are not waiting on Orbot, so we need to process the URL.
642 formattedUrlString = url;
644 // Only update urlTextBox if the user is not typing in it.
645 if (!urlTextBox.hasFocus()) {
646 urlTextBox.setText(formattedUrlString);
649 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog`.
650 sslCertificate = mainWebView.getCertificate();
654 // Handle SSL Certificate errors.
656 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
657 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
658 sslErrorHandler = handler;
660 // Display the SSL error `AlertDialog`.
661 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
662 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.ssl_certificate_error));
666 mainWebView.setWebChromeClient(new WebChromeClient() {
667 // Update the progress bar when a page is loading.
669 public void onProgressChanged(WebView view, int progress) {
670 ProgressBar progressBar = (ProgressBar) appBar.getCustomView().findViewById(R.id.progressBar);
671 progressBar.setProgress(progress);
672 if (progress < 100) {
673 progressBar.setVisibility(View.VISIBLE);
675 progressBar.setVisibility(View.GONE);
677 //Stop the `SwipeToRefresh` indicator if it is running
678 swipeRefreshLayout.setRefreshing(false);
682 // Set the favorite icon when it changes.
684 public void onReceivedIcon(WebView view, Bitmap icon) {
685 // Save a copy of the favorite icon.
688 // Place the favorite icon in the appBar.
689 ImageView imageViewFavoriteIcon = (ImageView) appBar.getCustomView().findViewById(R.id.favoriteIcon);
690 imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
693 // Save a copy of the title when it changes.
695 public void onReceivedTitle(WebView view, String title) {
696 // Save a copy of the title.
697 webViewTitle = title;
700 // Enter full screen video
702 public void onShowCustomView(View view, CustomViewCallback callback) {
703 // Pause the ad if this is the free flavor.
704 if (BuildConfig.FLAVOR.contentEquals("free")) {
705 BannerAd.pauseAd(adView);
708 // Remove the translucent overlays.
709 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
711 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
712 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
714 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
715 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
716 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
718 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
720 // Set `rootCoordinatorLayout` to fill the entire screen.
721 rootCoordinatorLayout.setFitsSystemWindows(false);
723 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
724 fullScreenVideoFrameLayout.addView(view);
725 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
728 // Exit full screen video
729 public void onHideCustomView() {
730 // Hide `fullScreenVideoFrameLayout`.
731 fullScreenVideoFrameLayout.removeAllViews();
732 fullScreenVideoFrameLayout.setVisibility(View.GONE);
734 // Add the translucent status flag. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
735 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
737 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars. This also clears the `SYSTEM_UI` flags.
738 rootCoordinatorLayout.setFitsSystemWindows(true);
740 // Show the ad if this is the free flavor.
741 if (BuildConfig.FLAVOR.contentEquals("free")) {
742 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
743 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
745 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
746 adView = findViewById(R.id.adView);
751 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
752 registerForContextMenu(mainWebView);
754 // Allow the downloading of files.
755 mainWebView.setDownloadListener(new DownloadListener() {
757 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
758 // Show the `DownloadFileDialog` `AlertDialog` and name this instance `@string/download`.
759 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
760 downloadFileDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
764 // Allow pinch to zoom.
765 mainWebView.getSettings().setBuiltInZoomControls(true);
767 // Hide zoom controls.
768 mainWebView.getSettings().setDisplayZoomControls(false);
770 // Initialize cookieManager.
771 cookieManager = CookieManager.getInstance();
773 // 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).
774 customHeaders.put("X-Requested-With", "");
776 // Initialize the default preference values the first time the program is run. `this` is the context. `false` keeps this command from resetting any current preferences back to default.
777 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
779 // Get the intent that started the app.
780 final Intent launchingIntent = getIntent();
782 // Extract the launching intent data as `launchingIntentUriData`.
783 final Uri launchingIntentUriData = launchingIntent.getData();
785 // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
786 if (launchingIntentUriData != null) {
787 formattedUrlString = launchingIntentUriData.toString();
790 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
791 inFullScreenBrowsingMode = false;
793 // Initialize AdView for the free flavor.
794 adView = findViewById(R.id.adView);
796 // Initialize the privacy settings variables.
797 javaScriptEnabled = false;
798 firstPartyCookiesEnabled = false;
799 thirdPartyCookiesEnabled = false;
800 domStorageEnabled = false;
801 saveFormDataEnabled = false;
803 // Apply the settings from the shared preferences.
806 // Load `formattedUrlString` if we are not proxying through Orbot and waiting for Orbot to connect.
807 if (!(proxyThroughOrbot && !orbotStatus.equals("ON"))) {
808 loadUrl(formattedUrlString);
811 // If the favorite icon is null, load the default.
812 if (favoriteIcon == null) {
813 // We have to use `ContextCompat` until API >= 21.
814 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
815 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
816 favoriteIcon = favoriteIconBitmapDrawable.getBitmap();
822 protected void onNewIntent(Intent intent) {
823 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
826 if (intent.getData() != null) {
827 // Get the intent data and convert it to a string.
828 final Uri intentUriData = intent.getData();
829 formattedUrlString = intentUriData.toString();
832 // Close the navigation drawer if it is open.
833 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
834 drawerLayout.closeDrawer(GravityCompat.START);
838 loadUrl(formattedUrlString);
840 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
841 mainWebView.requestFocus();
845 public boolean onCreateOptionsMenu(Menu menu) {
846 // Inflate the menu; this adds items to the action bar if it is present.
847 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
849 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
852 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
853 updatePrivacyIcons(false);
855 // Get handles for the menu items.
856 MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
857 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
858 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
859 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
861 // Only display third-party cookies if SDK >= 21
862 toggleThirdPartyCookies.setVisible(Build.VERSION.SDK_INT >= 21);
864 // Get the shared preference values. `this` references the current context.
865 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
867 // Set the status of the additional app bar icons. The default is `false`.
868 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
869 toggleFirstPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
870 toggleDomStorage.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
871 toggleSaveFormData.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
872 } else { //Do not display the additional icons.
873 toggleFirstPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
874 toggleDomStorage.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
875 toggleSaveFormData.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
882 public boolean onPrepareOptionsMenu(Menu menu) {
883 // Get handles for the menu items.
884 MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
885 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
886 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
887 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
888 MenuItem clearCookies = menu.findItem(R.id.clearCookies);
889 MenuItem clearFormData = menu.findItem(R.id.clearFormData);
890 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
892 // Set the status of the menu item checkboxes.
893 toggleFirstPartyCookies.setChecked(firstPartyCookiesEnabled);
894 toggleThirdPartyCookies.setChecked(thirdPartyCookiesEnabled);
895 toggleDomStorage.setChecked(domStorageEnabled);
896 toggleSaveFormData.setChecked(saveFormDataEnabled);
898 // Enable third-party cookies if first-party cookies are enabled.
899 toggleThirdPartyCookies.setEnabled(firstPartyCookiesEnabled);
901 // Enable DOM Storage if JavaScript is enabled.
902 toggleDomStorage.setEnabled(javaScriptEnabled);
904 // Enable Clear Cookies if there are any.
905 clearCookies.setEnabled(cookieManager.hasCookies());
907 // Enable Clear Form Data is there is any.
908 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
909 clearFormData.setEnabled(mainWebViewDatabase.hasFormData());
911 // Only show `Refresh` if `swipeToRefresh` is disabled.
912 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
914 // Initialize font size variables.
915 int fontSize = mainWebView.getSettings().getTextZoom();
916 String fontSizeTitle;
917 MenuItem selectedFontSizeMenuItem;
919 // Prepare the font size title and current size menu item.
922 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.fifty_percent);
923 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeFiftyPercent);
927 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.seventy_five_percent);
928 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeSeventyFivePercent);
932 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
933 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
937 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_twenty_five_percent);
938 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredTwentyFivePercent);
942 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_fifty_percent);
943 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredFiftyPercent);
947 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_seventy_five_percent);
948 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredSeventyFivePercent);
952 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.two_hundred_percent);
953 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeTwoHundredPercent);
957 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
958 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
962 // Set the font size title and select the current size menu item.
963 MenuItem fontSizeMenuItem = menu.findItem(R.id.fontSize);
964 fontSizeMenuItem.setTitle(fontSizeTitle);
965 selectedFontSizeMenuItem.setChecked(true);
967 // Run all the other default commands.
968 super.onPrepareOptionsMenu(menu);
970 // `return true` displays the menu.
975 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
976 @SuppressLint("SetJavaScriptEnabled")
977 // removeAllCookies is deprecated, but it is required for API < 21.
978 @SuppressWarnings("deprecation")
979 public boolean onOptionsItemSelected(MenuItem menuItem) {
980 int menuItemId = menuItem.getItemId();
982 // Set the commands that relate to the menu entries.
983 switch (menuItemId) {
984 case R.id.toggleJavaScript:
985 // Switch the status of javaScriptEnabled.
986 javaScriptEnabled = !javaScriptEnabled;
988 // Apply the new JavaScript status.
989 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
991 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
992 updatePrivacyIcons(true);
994 // Display a `Snackbar`.
995 if (javaScriptEnabled) { // JavaScrip is enabled.
996 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
997 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
998 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
999 } else { // Privacy mode.
1000 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1003 // Reload the WebView.
1004 mainWebView.reload();
1007 case R.id.toggleFirstPartyCookies:
1008 // Switch the status of firstPartyCookiesEnabled.
1009 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1011 // Update the menu checkbox.
1012 menuItem.setChecked(firstPartyCookiesEnabled);
1014 // Apply the new cookie status.
1015 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1017 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1018 updatePrivacyIcons(true);
1020 // Display a `Snackbar`.
1021 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1022 Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1023 } else if (javaScriptEnabled){ // JavaScript is still enabled.
1024 Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1025 } else { // Privacy mode.
1026 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1029 // Reload the WebView.
1030 mainWebView.reload();
1033 case R.id.toggleThirdPartyCookies:
1034 if (Build.VERSION.SDK_INT >= 21) {
1035 // Switch the status of thirdPartyCookiesEnabled.
1036 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1038 // Update the menu checkbox.
1039 menuItem.setChecked(thirdPartyCookiesEnabled);
1041 // Apply the new cookie status.
1042 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1044 // Display a `Snackbar`.
1045 if (thirdPartyCookiesEnabled) {
1046 Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1048 Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1051 // Reload the WebView.
1052 mainWebView.reload();
1053 } // Else do nothing because SDK < 21.
1056 case R.id.toggleDomStorage:
1057 // Switch the status of domStorageEnabled.
1058 domStorageEnabled = !domStorageEnabled;
1060 // Update the menu checkbox.
1061 menuItem.setChecked(domStorageEnabled);
1063 // Apply the new DOM Storage status.
1064 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1066 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1067 updatePrivacyIcons(true);
1069 // Display a `Snackbar`.
1070 if (domStorageEnabled) {
1071 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1073 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1076 // Reload the WebView.
1077 mainWebView.reload();
1080 case R.id.toggleSaveFormData:
1081 // Switch the status of saveFormDataEnabled.
1082 saveFormDataEnabled = !saveFormDataEnabled;
1084 // Update the menu checkbox.
1085 menuItem.setChecked(saveFormDataEnabled);
1087 // Apply the new form data status.
1088 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1090 // Display a `Snackbar`.
1091 if (saveFormDataEnabled) {
1092 Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1094 Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1097 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1098 updatePrivacyIcons(true);
1100 // Reload the WebView.
1101 mainWebView.reload();
1104 case R.id.clearCookies:
1105 if (Build.VERSION.SDK_INT < 21) {
1106 cookieManager.removeAllCookie();
1108 cookieManager.removeAllCookies(null);
1110 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_deleted, Snackbar.LENGTH_SHORT).show();
1113 case R.id.clearDomStorage:
1114 WebStorage webStorage = WebStorage.getInstance();
1115 webStorage.deleteAllData();
1116 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_deleted, Snackbar.LENGTH_SHORT).show();
1119 case R.id.clearFormData:
1120 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1121 mainWebViewDatabase.clearFormData();
1122 Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_deleted, Snackbar.LENGTH_SHORT).show();
1125 case R.id.fontSizeFiftyPercent:
1126 mainWebView.getSettings().setTextZoom(50);
1129 case R.id.fontSizeSeventyFivePercent:
1130 mainWebView.getSettings().setTextZoom(75);
1133 case R.id.fontSizeOneHundredPercent:
1134 mainWebView.getSettings().setTextZoom(100);
1137 case R.id.fontSizeOneHundredTwentyFivePercent:
1138 mainWebView.getSettings().setTextZoom(125);
1141 case R.id.fontSizeOneHundredFiftyPercent:
1142 mainWebView.getSettings().setTextZoom(150);
1145 case R.id.fontSizeOneHundredSeventyFivePercent:
1146 mainWebView.getSettings().setTextZoom(175);
1149 case R.id.fontSizeTwoHundredPercent:
1150 mainWebView.getSettings().setTextZoom(200);
1153 case R.id.find_on_page:
1154 // Hide the URL app bar.
1155 supportAppBar.setVisibility(View.GONE);
1157 // Show the Find on Page `RelativeLayout`.
1158 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1160 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android.
1161 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1162 findOnPageEditText.postDelayed(new Runnable()
1167 // Set the focus on `findOnPageEditText`.
1168 findOnPageEditText.requestFocus();
1170 // Display the keyboard.
1171 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1177 Intent shareIntent = new Intent();
1178 shareIntent.setAction(Intent.ACTION_SEND);
1179 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
1180 shareIntent.setType("text/plain");
1181 startActivity(Intent.createChooser(shareIntent, "Share URL"));
1184 case R.id.addToHomescreen:
1185 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
1186 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
1187 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.create_shortcut));
1189 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
1193 // Get a `PrintManager` instance.
1194 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1196 // Convert `mainWebView` to `printDocumentAdapter`.
1197 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
1199 // Print the document. The print attributes are `null`.
1200 printManager.print(getResources().getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1204 mainWebView.reload();
1208 // Don't consume the event.
1209 return super.onOptionsItemSelected(menuItem);
1213 // removeAllCookies is deprecated, but it is required for API < 21.
1214 @SuppressWarnings("deprecation")
1216 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1217 int menuItemId = menuItem.getItemId();
1219 switch (menuItemId) {
1225 if (mainWebView.canGoBack()) {
1226 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1227 navigatingHistory = true;
1229 // Load the previous website in the history.
1230 mainWebView.goBack();
1235 if (mainWebView.canGoForward()) {
1236 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1237 navigatingHistory = true;
1239 // Load the next website in the history.
1240 mainWebView.goForward();
1245 // Gte the `WebBackForwardList`.
1246 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
1248 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
1249 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
1250 urlHistoryDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.history));
1253 case R.id.bookmarks:
1254 // Launch BookmarksActivity.
1255 Intent bookmarksIntent = new Intent(this, BookmarksActivity.class);
1256 startActivity(bookmarksIntent);
1259 case R.id.downloads:
1260 // Launch the system Download Manager.
1261 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1263 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1264 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1266 startActivity(downloadManagerIntent);
1270 // Launch `SettingsActivity`.
1271 Intent settingsIntent = new Intent(this, SettingsActivity.class);
1272 startActivity(settingsIntent);
1276 // Launch `DomainsActivity`.
1277 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1278 startActivity(domainsIntent);
1282 // Launch `GuideActivity`.
1283 Intent guideIntent = new Intent(this, GuideActivity.class);
1284 startActivity(guideIntent);
1288 // Launch `AboutActivity`.
1289 Intent aboutIntent = new Intent(this, AboutActivity.class);
1290 startActivity(aboutIntent);
1293 case R.id.clearAndExit:
1294 // Clear cookies. The commands changed slightly in API 21.
1295 if (Build.VERSION.SDK_INT >= 21) {
1296 cookieManager.removeAllCookies(null);
1298 cookieManager.removeAllCookie();
1301 // Clear DOM storage.
1302 WebStorage domStorage = WebStorage.getInstance();
1303 domStorage.deleteAllData();
1306 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1307 webViewDatabase.clearFormData();
1309 // Clear cache. The argument of "true" includes disk files.
1310 mainWebView.clearCache(true);
1312 // Clear the back/forward history.
1313 mainWebView.clearHistory();
1315 // Clear any SSL certificate preferences.
1316 mainWebView.clearSslPreferences();
1318 // Clear `formattedUrlString`.
1319 formattedUrlString = null;
1321 // Clear `customHeaders`.
1322 customHeaders.clear();
1324 // Detach all views from `mainWebViewRelativeLayout`.
1325 mainWebViewRelativeLayout.removeAllViews();
1327 // Destroy the internal state of `mainWebView`.
1328 mainWebView.destroy();
1330 // Manually delete the `app_webview` folder, which contains an additional `WebView` cache. See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
1331 Runtime runtime = Runtime.getRuntime();
1332 String dataDirString = getApplicationInfo().dataDir; // `dataDir` will vary, but will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
1334 runtime.exec("rm -rf " + dataDirString + "/app_webview");
1335 } catch (IOException e) {
1336 // Do nothing if the files do not exist.
1339 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
1340 if (Build.VERSION.SDK_INT >= 21) {
1341 finishAndRemoveTask();
1346 // Remove the terminated program from RAM. The status code is `0`.
1354 // Close the navigation drawer.
1355 drawerLayout.closeDrawer(GravityCompat.START);
1360 public void onPostCreate(Bundle savedInstanceState) {
1361 super.onPostCreate(savedInstanceState);
1363 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
1364 drawerToggle.syncState();
1368 public void onConfigurationChanged(Configuration newConfig) {
1369 super.onConfigurationChanged(newConfig);
1371 // Reload the ad for the free flavor if we are not in full screen mode.
1372 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
1374 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1376 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1377 adView = findViewById(R.id.adView);
1380 // `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: https://code.google.com/p/android/issues/detail?id=20493#c8
1381 // ActivityCompat.invalidateOptionsMenu(this);
1385 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
1386 // Store the `HitTestResult`.
1387 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
1390 final String imageUrl;
1391 final String linkUrl;
1393 // Get a handle for the `ClipboardManager`.
1394 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
1396 switch (hitTestResult.getType()) {
1397 // `SRC_ANCHOR_TYPE` is a link.
1398 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1399 // Get the target URL.
1400 linkUrl = hitTestResult.getExtra();
1402 // Set the target URL as the title of the `ContextMenu`.
1403 menu.setHeaderTitle(linkUrl);
1405 // Add a `Load URL` entry.
1406 menu.add(R.string.load_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1408 public boolean onMenuItemClick(MenuItem item) {
1414 // Add a `Copy URL` entry.
1415 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1417 public boolean onMenuItemClick(MenuItem item) {
1418 // Save the link URL in a `ClipData`.
1419 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), linkUrl);
1421 // Set the `ClipData` as the clipboard's primary clip.
1422 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
1427 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1428 menu.add(R.string.cancel);
1431 case WebView.HitTestResult.EMAIL_TYPE:
1432 // Get the target URL.
1433 linkUrl = hitTestResult.getExtra();
1435 // Set the target URL as the title of the `ContextMenu`.
1436 menu.setHeaderTitle(linkUrl);
1438 // Add a `Write Email` entry.
1439 menu.add(R.string.write_email).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1441 public boolean onMenuItemClick(MenuItem item) {
1442 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1443 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1445 // Parse the url and set it as the data for the `Intent`.
1446 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
1448 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
1449 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1452 startActivity(emailIntent);
1457 // Add a `Copy Email Address` entry.
1458 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1460 public boolean onMenuItemClick(MenuItem item) {
1461 // Save the email address in a `ClipData`.
1462 ClipData srcEmailTypeClipData = ClipData.newPlainText(getResources().getString(R.string.email_address), linkUrl);
1464 // Set the `ClipData` as the clipboard's primary clip.
1465 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
1470 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1471 menu.add(R.string.cancel);
1474 // `IMAGE_TYPE` is an image.
1475 case WebView.HitTestResult.IMAGE_TYPE:
1476 // Get the image URL.
1477 imageUrl = hitTestResult.getExtra();
1479 // Set the image URL as the title of the `ContextMenu`.
1480 menu.setHeaderTitle(imageUrl);
1482 // Add a `View Image` entry.
1483 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1485 public boolean onMenuItemClick(MenuItem item) {
1491 // Add a `Download Image` entry.
1492 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1494 public boolean onMenuItemClick(MenuItem item) {
1495 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
1496 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
1497 downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1502 // Add a `Copy URL` entry.
1503 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1505 public boolean onMenuItemClick(MenuItem item) {
1506 // Save the image URL in a `ClipData`.
1507 ClipData srcImageTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1509 // Set the `ClipData` as the clipboard's primary clip.
1510 clipboardManager.setPrimaryClip(srcImageTypeClipData);
1515 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1516 menu.add(R.string.cancel);
1520 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
1521 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1522 // Get the image URL.
1523 imageUrl = hitTestResult.getExtra();
1525 // Set the image URL as the title of the `ContextMenu`.
1526 menu.setHeaderTitle(imageUrl);
1528 // Add a `View Image` entry.
1529 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1531 public boolean onMenuItemClick(MenuItem item) {
1537 // Add a `Download Image` entry.
1538 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1540 public boolean onMenuItemClick(MenuItem item) {
1541 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
1542 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
1543 downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1548 // Add a `Copy URL` entry.
1549 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1551 public boolean onMenuItemClick(MenuItem item) {
1552 // Save the image URL in a `ClipData`.
1553 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1555 // Set the `ClipData` as the clipboard's primary clip.
1556 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
1561 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1562 menu.add(R.string.cancel);
1568 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
1569 // Get shortcutNameEditText from the alert dialog.
1570 EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
1572 // Create the bookmark shortcut based on formattedUrlString.
1573 Intent bookmarkShortcut = new Intent();
1574 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
1575 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
1577 // Place the bookmark shortcut on the home screen.
1578 Intent placeBookmarkShortcut = new Intent();
1579 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
1580 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
1581 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
1582 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
1583 sendBroadcast(placeBookmarkShortcut);
1587 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
1588 // Download the image if it has an HTTP or HTTPS URI.
1589 if (imageUrl.startsWith("http")) {
1590 // Get a handle for the system `DOWNLOAD_SERVICE`.
1591 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
1593 // Parse `imageUrl`.
1594 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
1596 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
1597 if (firstPartyCookiesEnabled) {
1598 // Get the cookies for `imageUrl`.
1599 String cookies = cookieManager.getCookie(imageUrl);
1601 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
1602 downloadRequest.addRequestHeader("Cookie", cookies);
1605 // Get the file name from `dialogFragment`.
1606 EditText downloadImageNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_image_name);
1607 String imageName = downloadImageNameEditText.getText().toString();
1609 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
1610 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `imageName`.
1611 downloadRequest.setDestinationInExternalFilesDir(this, "/", imageName);
1612 } else { // Only set the title using `imageName`.
1613 downloadRequest.setTitle(imageName);
1616 // Allow `MediaScanner` to index the download if it is a media file.
1617 downloadRequest.allowScanningByMediaScanner();
1619 // Add the URL as the description for the download.
1620 downloadRequest.setDescription(imageUrl);
1622 // Show the download notification after the download is completed.
1623 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
1625 // Initiate the download.
1626 downloadManager.enqueue(downloadRequest);
1627 } else { // The image is not an HTTP or HTTPS URI.
1628 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
1633 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
1634 // Download the file if it has an HTTP or HTTPS URI.
1635 if (downloadUrl.startsWith("http")) {
1637 // Get a handle for the system `DOWNLOAD_SERVICE`.
1638 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
1640 // Parse `downloadUrl`.
1641 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
1643 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
1644 if (firstPartyCookiesEnabled) {
1645 // Get the cookies for `downloadUrl`.
1646 String cookies = cookieManager.getCookie(downloadUrl);
1648 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
1649 downloadRequest.addRequestHeader("Cookie", cookies);
1652 // Get the file name from `dialogFragment`.
1653 EditText downloadFileNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_file_name);
1654 String fileName = downloadFileNameEditText.getText().toString();
1656 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
1657 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download location to `/sdcard/Android/data/com.stoutner.privacybrowser.standard/files` named `fileName`.
1658 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
1659 } else { // Only set the title using `fileName`.
1660 downloadRequest.setTitle(fileName);
1663 // Allow `MediaScanner` to index the download if it is a media file.
1664 downloadRequest.allowScanningByMediaScanner();
1666 // Add the URL as the description for the download.
1667 downloadRequest.setDescription(downloadUrl);
1669 // Show the download notification after the download is completed.
1670 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
1672 // Initiate the download.
1673 downloadManager.enqueue(downloadRequest);
1674 } else { // The download is not an HTTP or HTTPS URI.
1675 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
1679 public void viewSslCertificate(View view) {
1680 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
1681 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
1682 viewSslCertificateDialogFragment.show(getFragmentManager(), getResources().getString(R.string.view_ssl_certificate));
1686 public void onSslErrorCancel() {
1687 sslErrorHandler.cancel();
1691 public void onSslErrorProceed() {
1692 sslErrorHandler.proceed();
1696 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
1697 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1698 navigatingHistory = true;
1700 // Load the history entry.
1701 mainWebView.goBackOrForward(moveBackOrForwardSteps);
1705 public void onClearHistory() {
1706 // Clear the history.
1707 mainWebView.clearHistory();
1710 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
1712 public void onBackPressed() {
1713 // Close the navigation drawer if it is available. GravityCompat.START is the drawer on the left on Left-to-Right layout text.
1714 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1715 drawerLayout.closeDrawer(GravityCompat.START);
1717 // Load the previous URL if available.
1718 if (mainWebView.canGoBack()) {
1719 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1720 navigatingHistory = true;
1723 mainWebView.goBack();
1725 // Pass `onBackPressed()` to the system.
1726 super.onBackPressed();
1732 public void onPause() {
1733 // Pause `mainWebView`.
1734 mainWebView.onPause();
1736 // Stop all JavaScript.
1737 mainWebView.pauseTimers();
1739 // Pause the adView or it will continue to consume resources in the background on the free flavor.
1740 if (BuildConfig.FLAVOR.contentEquals("free")) {
1741 BannerAd.pauseAd(adView);
1748 public void onResume() {
1751 // Resume JavaScript (if enabled).
1752 mainWebView.resumeTimers();
1754 // Resume `mainWebView`.
1755 mainWebView.onResume();
1757 // Resume the adView for the free flavor.
1758 if (BuildConfig.FLAVOR.contentEquals("free")) {
1759 BannerAd.resumeAd(adView);
1764 public void onRestart() {
1767 // Apply the settings from shared preferences, which might have been changed in `SettingsActivity`.
1770 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1771 updatePrivacyIcons(true);
1775 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
1776 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
1777 String unformattedUrlString = urlTextBox.getText().toString().trim();
1779 URL unformattedUrl = null;
1780 Uri.Builder formattedUri = new Uri.Builder();
1782 // Check to see if unformattedUrlString is a valid URL. Otherwise, convert it into a Duck Duck Go search.
1783 if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
1784 // Add http:// at the beginning if it is missing. Otherwise the app will segfault.
1785 if (!unformattedUrlString.startsWith("http")) {
1786 unformattedUrlString = "http://" + unformattedUrlString;
1789 // 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.
1791 unformattedUrl = new URL(unformattedUrlString);
1792 } catch (MalformedURLException e) {
1793 e.printStackTrace();
1796 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
1797 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
1798 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
1799 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
1800 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
1801 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
1803 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
1804 formattedUrlString = formattedUri.build().toString();
1806 // Sanitize the search input and convert it to a DuckDuckGo search.
1807 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
1809 // Use the correct search URL.
1810 if (javaScriptEnabled) { // JavaScript is enabled.
1811 formattedUrlString = javaScriptEnabledSearchURL + encodedUrlString;
1812 } else { // JavaScript is disabled.
1813 formattedUrlString = javaScriptDisabledSearchURL + encodedUrlString;
1817 loadUrl(formattedUrlString);
1819 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
1820 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1824 private void loadUrl(String url) {
1825 // Apply any custom domain settings.
1826 applyDomainSettings(url);
1829 mainWebView.loadUrl(url, customHeaders);
1832 // We have to use the deprecated `.getColor()` until the minimum API >= 23.
1833 @SuppressWarnings("deprecation")
1834 private void applyDomainSettings(String url) {
1835 // Parse the URL into a URI.
1836 Uri uri = Uri.parse(url);
1838 // Extract the domain from `uri`.
1839 String hostname = uri.getHost();
1841 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
1842 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1843 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1845 // Get a full cursor from `domainsDatabaseHelper`.
1846 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
1848 // Initialize `domainSettingsSet`.
1849 Set<String> domainSettingsSet = new HashSet<>();
1851 // Get the domain name column index.
1852 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
1854 // Populate `domainSettingsSet`.
1855 for (int i=0; i<domainNameCursor.getCount(); i++) {
1856 // Move `domainsCursor` to the current row.
1857 domainNameCursor.moveToPosition(i);
1859 // Store the domain name in `domainSettingsSet`.
1860 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
1863 // Close `domainNameCursor.
1864 domainNameCursor.close();
1866 // Initialize variables to track if this domain has stored domain settings, and if so, under which name.
1867 boolean hostHasDomainSettings = false;
1868 String domainNameInDatabase = null;
1870 // Check all the subdomains of `domain` if it is not `null` against the list of domains in `domainCursor`.
1871 if (hostname != null) {
1872 while (hostname.contains(".") && !hostHasDomainSettings) { // Stop checking if we run out of `.` or if we already know that `hostHasDomainSettings` is `true`.
1873 if (domainSettingsSet.contains(hostname)) { // Check the host name.
1874 hostHasDomainSettings = true;
1875 domainNameInDatabase = hostname;
1876 } else if (domainSettingsSet.contains("*." + hostname)){ // Check the host name prepended by `*.`.
1877 hostHasDomainSettings = true;
1878 domainNameInDatabase = "*." + hostname;
1881 // Strip out the lowest subdomain of `host`.
1882 hostname = hostname.substring(hostname.indexOf(".") + 1);
1886 FrameLayout urlAppBarFrameLayout = (FrameLayout) findViewById(R.id.url_app_bar_framelayout);
1888 if (hostHasDomainSettings) { // The url we are loading has custom domain settings.
1889 // Get a cursor for the current host and move it to the first position.
1890 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
1891 currentHostDomainSettingsCursor.moveToFirst();
1893 // Get the settings from the cursor.
1894 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
1895 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
1896 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
1897 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
1898 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
1899 String userAgentString = (currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT)));
1900 int fontSize = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE)));
1902 // Close `currentHostDomainSettingsCursor`.
1903 currentHostDomainSettingsCursor.close();
1905 // Apply the domain settings.
1906 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1907 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1908 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1909 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1910 mainWebView.getSettings().setTextZoom(fontSize);
1912 // Set third-party cookies status if API >= 21.
1913 if (Build.VERSION.SDK_INT >= 21) {
1914 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1917 // Set the user agent.
1918 if (userAgentString.equals("WebView default user agent")) {
1919 // Set the user agent to `""`, which uses the default value.
1920 mainWebView.getSettings().setUserAgentString("");
1922 // Use the selected user agent.
1923 mainWebView.getSettings().setUserAgentString(userAgentString);
1926 // Set a green background on `urlTextBox` to indicate that custom domain settings are being used. We have to use the deprecated `.getColor()` until the minimum API >= 23.
1927 urlAppBarFrameLayout.setBackgroundColor(getResources().getColor(R.color.green_100));
1928 } else { // The URL we are loading does not have custom domain settings. Load the defaults.
1929 // Get the shared preference values. `this` references the current context.
1930 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1932 // Store the values from `sharedPreferences` in variables.
1933 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
1934 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
1935 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
1936 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
1937 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
1938 String userAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
1939 String customUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
1940 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
1942 // Apply the default settings.
1943 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1944 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1945 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1946 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1947 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
1949 // Set third-party cookies status if API >= 21.
1950 if (Build.VERSION.SDK_INT >= 21) {
1951 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1954 // Set the default user agent.
1955 switch (userAgentString) {
1956 case "WebView default user agent":
1957 // Set the user agent to `""`, which uses the default value.
1958 mainWebView.getSettings().setUserAgentString("");
1961 case "Custom user agent":
1962 // Set the custom user agent.
1963 mainWebView.getSettings().setUserAgentString(customUserAgentString);
1967 // Use the selected user agent.
1968 mainWebView.getSettings().setUserAgentString(userAgentString);
1972 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getColor()` until the minimum API >= 23.
1973 urlAppBarFrameLayout.setBackgroundColor(getResources().getColor(R.color.transparent));
1976 // Close `domainsDatabaseHelper`.
1977 domainsDatabaseHelper.close();
1979 // Update the privacy icons, but only if `mainMenu` has already been populated.
1980 if (mainMenu != null) {
1981 updatePrivacyIcons(true);
1985 public void findPreviousOnPage(View view) {
1986 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
1987 mainWebView.findNext(false);
1990 public void findNextOnPage(View view) {
1991 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
1992 mainWebView.findNext(true);
1995 public void closeFindOnPage(View view) {
1996 // Delete the contents of `find_on_page_edittext`.
1997 findOnPageEditText.setText(null);
1999 // Clear the highlighted phrases.
2000 mainWebView.clearMatches();
2002 // Hide the Find on Page `RelativeLayout`.
2003 findOnPageLinearLayout.setVisibility(View.GONE);
2005 // Show the URL app bar.
2006 supportAppBar.setVisibility(View.VISIBLE);
2008 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
2009 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2012 private void applySettings() {
2013 // Get the shared preference values. `this` references the current context.
2014 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2016 // Store the values from `sharedPreferences` in variables.
2017 String javaScriptDisabledSearchString = sharedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=");
2018 String javaScriptDisabledSearchCustomURLString = sharedPreferences.getString("javascript_disabled_search_custom_url", "");
2019 String javaScriptEnabledSearchString = sharedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=");
2020 String javaScriptEnabledSearchCustomURLString = sharedPreferences.getString("javascript_enabled_search_custom_url", "");
2021 String homepageString = sharedPreferences.getString("homepage", "https://www.duckduckgo.com");
2022 String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
2023 String torJavaScriptDisabledSearchString = sharedPreferences.getString("tor_javascript_disabled_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
2024 String torJavaScriptDisabledSearchCustomURLString = sharedPreferences.getString("tor_javascript_disabled_search_custom_url", "");
2025 String torJavaScriptEnabledSearchString = sharedPreferences.getString("tor_javascript_enabled_search", "https://3g2upl4pq6kufc4m.onion/?q=");
2026 String torJavaScriptEnabledSearchCustomURLString = sharedPreferences.getString("tor_javascript_enabled_search_custom_url", "");
2027 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh_enabled", false);
2028 adBlockerEnabled = sharedPreferences.getBoolean("block_ads", true);
2029 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
2030 proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
2031 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("enable_full_screen_browsing_mode", false);
2032 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
2033 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
2035 // Set the homepage, search, and proxy options.
2036 if (proxyThroughOrbot) { // Set the Tor options.
2037 // Set `torHomepageString` as `homepage`.
2038 homepage = torHomepageString;
2040 // If formattedUrlString is null assign the homepage to it.
2041 if (formattedUrlString == null) {
2042 formattedUrlString = homepage;
2045 // Set JavaScript disabled search.
2046 if (torJavaScriptDisabledSearchString.equals("Custom URL")) { // Get the custom URL string.
2047 javaScriptDisabledSearchURL = torJavaScriptDisabledSearchCustomURLString;
2048 } else { // Use the string from the pre-built list.
2049 javaScriptDisabledSearchURL = torJavaScriptDisabledSearchString;
2052 // Set JavaScript enabled search.
2053 if (torJavaScriptEnabledSearchString.equals("Custom URL")) { // Get the custom URL string.
2054 javaScriptEnabledSearchURL = torJavaScriptEnabledSearchCustomURLString;
2055 } else { // Use the string from the pre-built list.
2056 javaScriptEnabledSearchURL = torJavaScriptEnabledSearchString;
2059 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
2060 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
2062 // Display a message to the user if we are waiting on Orbot.
2063 if (!orbotStatus.equals("ON")) {
2064 // Save `formattedUrlString` in `pendingUrl`.
2065 pendingUrl = formattedUrlString;
2067 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
2068 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
2070 } else { // Set the non-Tor options.
2071 // Set `homepageString` as `homepage`.
2072 homepage = homepageString;
2074 // If formattedUrlString is null assign the homepage to it.
2075 if (formattedUrlString == null) {
2076 formattedUrlString = homepage;
2079 // Set JavaScript disabled search.
2080 if (javaScriptDisabledSearchString.equals("Custom URL")) { // Get the custom URL string.
2081 javaScriptDisabledSearchURL = javaScriptDisabledSearchCustomURLString;
2082 } else { // Use the string from the pre-built list.
2083 javaScriptDisabledSearchURL = javaScriptDisabledSearchString;
2086 // Set JavaScript enabled search.
2087 if (javaScriptEnabledSearchString.equals("Custom URL")) { // Get the custom URL string.
2088 javaScriptEnabledSearchURL = javaScriptEnabledSearchCustomURLString;
2089 } else { // Use the string from the pre-built list.
2090 javaScriptEnabledSearchURL = javaScriptEnabledSearchString;
2093 // Reset the proxy to default. The host is `""` and the port is `"0"`.
2094 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
2096 // Reset `pendingUrl` if we are currently waiting for Orbot to connect.
2097 if (!pendingUrl.isEmpty()) {
2098 formattedUrlString = pendingUrl;
2103 // Set swipe to refresh.
2104 swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
2106 // Set Do Not Track status.
2107 if (doNotTrackEnabled) {
2108 customHeaders.put("DNT", "1");
2110 customHeaders.remove("DNT");
2113 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
2114 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
2115 if (hideSystemBarsOnFullscreen) { // Hide everything.
2116 // Remove the translucent navigation setting if it is currently flagged.
2117 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2119 // Remove the translucent status bar overlay.
2120 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2122 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
2123 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
2125 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
2126 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
2127 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
2129 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
2130 } else { // Hide everything except the status and navigation bars.
2131 // Add the translucent status flag if it is unset.
2132 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2134 if (translucentNavigationBarOnFullscreen) {
2135 // Set the navigation bar to be translucent.
2136 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2138 // Set the navigation bar to be black.
2139 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2142 } else { // Switch to normal viewing mode.
2143 // Reset `inFullScreenBrowsingMode` to `false`.
2144 inFullScreenBrowsingMode = false;
2146 // Show the `appBar`.
2149 // Show the `BannerAd` in the free flavor.
2150 if (BuildConfig.FLAVOR.contentEquals("free")) {
2151 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
2152 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2154 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2155 adView = findViewById(R.id.adView);
2158 // Remove the translucent navigation bar flag if it is set.
2159 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2161 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
2162 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2164 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
2165 rootCoordinatorLayout.setSystemUiVisibility(0);
2167 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
2168 rootCoordinatorLayout.setFitsSystemWindows(true);
2172 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
2173 // Get handles for the icons.
2174 MenuItem privacyIcon = mainMenu.findItem(R.id.toggleJavaScript);
2175 MenuItem firstPartyCookiesIcon = mainMenu.findItem(R.id.toggleFirstPartyCookies);
2176 MenuItem domStorageIcon = mainMenu.findItem(R.id.toggleDomStorage);
2177 MenuItem formDataIcon = mainMenu.findItem(R.id.toggleSaveFormData);
2179 // Update `privacyIcon`.
2180 if (javaScriptEnabled) { // JavaScript is enabled.
2181 privacyIcon.setIcon(R.drawable.javascript_enabled);
2182 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
2183 privacyIcon.setIcon(R.drawable.warning);
2184 } else { // All the dangerous features are disabled.
2185 privacyIcon.setIcon(R.drawable.privacy_mode);
2188 // Update `firstPartyCookiesIcon`.
2189 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
2190 firstPartyCookiesIcon.setIcon(R.drawable.cookies_enabled);
2191 } else { // First-party cookies are disabled.
2192 firstPartyCookiesIcon.setIcon(R.drawable.cookies_disabled);
2195 // Update `domStorageIcon`.
2196 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
2197 domStorageIcon.setIcon(R.drawable.dom_storage_enabled);
2198 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
2199 domStorageIcon.setIcon(R.drawable.dom_storage_disabled);
2200 } else { // JavaScript is disabled, so DOM storage is ghosted.
2201 domStorageIcon.setIcon(R.drawable.dom_storage_ghosted);
2204 // Update `formDataIcon`.
2205 if (saveFormDataEnabled) { // Form data is enabled.
2206 formDataIcon.setIcon(R.drawable.form_data_enabled);
2207 } else { // Form data is disabled.
2208 formDataIcon.setIcon(R.drawable.form_data_disabled);
2211 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`. `this` references the current activity.
2212 if (runInvalidateOptionsMenu) {
2213 ActivityCompat.invalidateOptionsMenu(this);