2 * Copyright 2015-2016 Soren Stoutner <soren@stoutner.com>.
4 * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
6 * Privacy Browser is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * Privacy Browser is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with Privacy Browser. If not, see <http://www.gnu.org/licenses/>.
20 package com.stoutner.privacybrowser.activities;
22 import android.annotation.SuppressLint;
23 import android.app.DialogFragment;
24 import android.app.DownloadManager;
25 import android.content.ClipData;
26 import android.content.ClipboardManager;
27 import android.content.Context;
28 import android.content.Intent;
29 import android.content.SharedPreferences;
30 import android.content.res.Configuration;
31 import android.graphics.Bitmap;
32 import android.graphics.drawable.BitmapDrawable;
33 import android.graphics.drawable.Drawable;
34 import android.net.Uri;
35 import android.net.http.SslCertificate;
36 import android.net.http.SslError;
37 import android.os.Build;
38 import android.os.Bundle;
39 import android.preference.PreferenceManager;
40 import android.print.PrintDocumentAdapter;
41 import android.print.PrintManager;
42 import android.support.annotation.NonNull;
43 import android.support.design.widget.CoordinatorLayout;
44 import android.support.design.widget.NavigationView;
45 import android.support.design.widget.Snackbar;
46 import android.support.v4.app.ActivityCompat;
47 import android.support.v4.content.ContextCompat;
48 import android.support.v4.view.GravityCompat;
49 import android.support.v4.widget.DrawerLayout;
50 import android.support.v4.widget.SwipeRefreshLayout;
51 import android.support.v7.app.ActionBar;
52 import android.support.v7.app.ActionBarDrawerToggle;
53 import android.support.v7.app.AppCompatActivity;
54 import android.support.v7.app.AppCompatDialogFragment;
55 import android.support.v7.widget.Toolbar;
56 import android.text.Editable;
57 import android.text.TextWatcher;
58 import android.util.Patterns;
59 import android.view.ContextMenu;
60 import android.view.GestureDetector;
61 import android.view.KeyEvent;
62 import android.view.Menu;
63 import android.view.MenuItem;
64 import android.view.MotionEvent;
65 import android.view.View;
66 import android.view.WindowManager;
67 import android.view.inputmethod.InputMethodManager;
68 import android.webkit.CookieManager;
69 import android.webkit.DownloadListener;
70 import android.webkit.SslErrorHandler;
71 import android.webkit.WebBackForwardList;
72 import android.webkit.WebChromeClient;
73 import android.webkit.WebStorage;
74 import android.webkit.WebView;
75 import android.webkit.WebViewClient;
76 import android.webkit.WebViewDatabase;
77 import android.widget.EditText;
78 import android.widget.FrameLayout;
79 import android.widget.ImageView;
80 import android.widget.LinearLayout;
81 import android.widget.ProgressBar;
82 import android.widget.RelativeLayout;
83 import android.widget.TextView;
85 import com.stoutner.privacybrowser.BannerAd;
86 import com.stoutner.privacybrowser.BuildConfig;
87 import com.stoutner.privacybrowser.R;
88 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
89 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcut;
90 import com.stoutner.privacybrowser.dialogs.DownloadFile;
91 import com.stoutner.privacybrowser.dialogs.DownloadImage;
92 import com.stoutner.privacybrowser.dialogs.SslCertificateError;
93 import com.stoutner.privacybrowser.dialogs.UrlHistory;
94 import com.stoutner.privacybrowser.dialogs.ViewSslCertificate;
96 import java.io.UnsupportedEncodingException;
97 import java.net.MalformedURLException;
99 import java.net.URLEncoder;
100 import java.util.HashMap;
101 import java.util.Map;
103 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
104 public class MainWebView extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, CreateHomeScreenShortcut.CreateHomeScreenSchortcutListener,
105 SslCertificateError.SslCertificateErrorListener, DownloadFile.DownloadFileListener, DownloadImage.DownloadImageListener, UrlHistory.UrlHistoryListener {
107 // `appBar` is public static so it can be accessed from `OrbotProxyHelper`.
108 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applySettings()`.
109 public static ActionBar appBar;
111 // `favoriteIcon` is public static so it can be accessed from `CreateHomeScreenShortcut`, `Bookmarks`, `CreateBookmark`, `CreateBookmarkFolder`, and `EditBookmark`.
112 // It is also used in `onCreate()` and `onCreateHomeScreenShortcutCreate()`.
113 public static Bitmap favoriteIcon;
115 // `formattedUrlString` is public static so it can be accessed from `Bookmarks`.
116 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
117 public static String formattedUrlString;
119 // `sslCertificate` is public static so it can be accessed from `ViewSslCertificate`. It is also used in `onCreate()`.
120 public static SslCertificate sslCertificate;
124 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, and `onBackPressed()`.
125 private DrawerLayout drawerLayout;
127 // `rootCoordinatorLayout` is used in `onCreate()` and `applySettings()`.
128 private CoordinatorLayout rootCoordinatorLayout;
130 // 'mainWebView' is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`, `findNextOnPage()`, `closeFindOnPage()`, and `loadUrlFromTextBox()`.
131 private WebView mainWebView;
133 // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
134 private FrameLayout fullScreenVideoFrameLayout;
136 // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu`, and `onRestart()`.
137 private SwipeRefreshLayout swipeRefreshLayout;
139 // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, and `onRestart()`.
140 private CookieManager cookieManager;
142 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrlFromTextBox()`.
143 private final Map<String, String> customHeaders = new HashMap<>();
145 // `javaScriptEnabled` is also used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `applySettings()`.
146 // It is `Boolean` instead of `boolean` because `applySettings()` needs to know if it is `null`.
147 private Boolean javaScriptEnabled;
149 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
150 private boolean firstPartyCookiesEnabled;
152 // `thirdPartyCookiesEnabled` used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
153 private boolean thirdPartyCookiesEnabled;
155 // `domStorageEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
156 private boolean domStorageEnabled;
158 // `saveFormDataEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
159 private boolean saveFormDataEnabled;
161 // `swipeToRefreshEnabled` is used in `onPrepareOptionsMenu()` and `applySettings()`.
162 private boolean swipeToRefreshEnabled;
164 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applySettings()`.
165 private String homepage;
167 // `javaScriptDisabledSearchURL` is used in `loadURLFromTextBox()` and `applySettings()`.
168 private String javaScriptDisabledSearchURL;
170 // `javaScriptEnabledSearchURL` is used in `loadURLFromTextBox()` and `applySettings()`.
171 private String javaScriptEnabledSearchURL;
173 // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applySettings()`.
174 private boolean fullScreenBrowsingModeEnabled;
176 // `inFullScreenBrowsingMode` is used in `onCreate()` and `applySettings()`.
177 private boolean inFullScreenBrowsingMode;
179 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applySettings()`.
180 private boolean hideSystemBarsOnFullscreen;
182 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applySettings()`.
183 private boolean translucentNavigationBarOnFullscreen;
185 // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
186 private LinearLayout findOnPageLinearLayout;
188 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
189 private EditText findOnPageEditText;
191 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
192 private Menu mainMenu;
194 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
195 private ActionBarDrawerToggle drawerToggle;
197 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
198 private Toolbar supportAppBar;
200 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, and `loadUrlFromTextBox()`.
201 private EditText urlTextBox;
203 // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
206 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
207 private SslErrorHandler sslErrorHandler;
209 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
210 private InputMethodManager inputMethodManager;
212 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
213 private RelativeLayout mainWebViewRelativeLayout;
216 // 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.
217 @SuppressLint("SetJavaScriptEnabled")
218 protected void onCreate(Bundle savedInstanceState) {
219 super.onCreate(savedInstanceState);
220 setContentView(R.layout.drawerlayout);
222 // Get a handle for `inputMethodManager`.
223 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
225 // We need to use the `SupportActionBar` from `android.support.v7.app.ActionBar` until the minimum API is >= 21.
226 supportAppBar = (Toolbar) findViewById(R.id.app_bar);
227 setSupportActionBar(supportAppBar);
228 appBar = getSupportActionBar();
230 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
231 assert appBar != null;
233 // Add the custom url_app_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
234 appBar.setCustomView(R.layout.url_app_bar);
235 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
237 // Set the "go" button on the keyboard to load the URL in urlTextBox.
238 urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.urlTextBox);
239 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
241 public boolean onKey(View v, int keyCode, KeyEvent event) {
242 // If the event is a key-down event on the `enter` button, load the URL.
243 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
244 // Load the URL into the mainWebView and consume the event.
246 loadUrlFromTextBox();
247 } catch (UnsupportedEncodingException e) {
250 // If the enter key was pressed, consume the event.
253 // If any other key was pressed, do not consume the event.
259 // Get handles for views that need to be accessed.
260 drawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout);
261 rootCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.root_coordinatorlayout);
262 mainWebViewRelativeLayout = (RelativeLayout) findViewById(R.id.main_webview_relativelayout);
263 mainWebView = (WebView) findViewById(R.id.mainWebView);
264 findOnPageLinearLayout = (LinearLayout) findViewById(R.id.find_on_page_linearlayout);
265 findOnPageEditText = (EditText) findViewById(R.id.find_on_page_edittext);
266 fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.full_screen_video_framelayout);
268 // Create a double-tap listener to toggle full-screen mode.
269 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
270 // Override `onDoubleTap()`. All other events are handled using the default settings.
272 public boolean onDoubleTap(MotionEvent event) {
273 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
274 // Toggle `inFullScreenBrowsingMode`.
275 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
277 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
278 // Hide the `appBar`.
281 // Hide the `BannerAd` in the free flavor.
282 if (BuildConfig.FLAVOR.contentEquals("free")) {
283 BannerAd.hideAd(adView);
286 // Modify the system bars.
287 if (hideSystemBarsOnFullscreen) { // Hide everything.
288 // Remove the translucent overlays.
289 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
291 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
292 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
294 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
295 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
296 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
298 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
300 // Set `rootCoordinatorLayout` to fill the whole screen.
301 rootCoordinatorLayout.setFitsSystemWindows(false);
302 } else { // Hide everything except the status and navigation bars.
303 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
304 rootCoordinatorLayout.setFitsSystemWindows(false);
306 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.
307 // Set the navigation bar to be translucent.
308 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
311 } else { // Switch to normal viewing mode.
312 // Show the `appBar`.
315 // Show the `BannerAd` in the free flavor.
316 if (BuildConfig.FLAVOR.contentEquals("free")) {
317 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
318 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
320 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
321 adView = findViewById(R.id.adView);
324 // Remove the translucent navigation bar flag if it is set.
325 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
327 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
328 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
330 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
331 rootCoordinatorLayout.setSystemUiVisibility(0);
333 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
334 rootCoordinatorLayout.setFitsSystemWindows(true);
337 // Consume the double-tap.
339 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
345 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
346 mainWebView.setOnTouchListener(new View.OnTouchListener() {
348 public boolean onTouch(View v, MotionEvent event) {
349 // Send the `event` to `gestureDetector`.
350 return gestureDetector.onTouchEvent(event);
354 // Update `findOnPageCountTextView`.
355 mainWebView.setFindListener(new WebView.FindListener() {
356 // Get a handle for `findOnPageCountTextView`.
357 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
360 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
361 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
362 // Set `findOnPageCountTextView` to `0/0`.
363 findOnPageCountTextView.setText(R.string.zero_of_zero);
364 } else if (isDoneCounting) { // There are matches.
365 // `activeMatchOrdinal` is zero-based.
366 int activeMatch = activeMatchOrdinal + 1;
368 // Set `findOnPageCountTextView`.
369 findOnPageCountTextView.setText(activeMatch + "/" + numberOfMatches);
374 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
375 findOnPageEditText.addTextChangedListener(new TextWatcher() {
377 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
382 public void onTextChanged(CharSequence s, int start, int before, int count) {
387 public void afterTextChanged(Editable s) {
388 // Search for the text in `mainWebView`.
389 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
393 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
394 findOnPageEditText.setOnKeyListener(new View.OnKeyListener() {
396 public boolean onKey(View v, int keyCode, KeyEvent event) {
397 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
398 // Hide the soft keyboard. `0` indicates no additional flags.
399 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
401 // Consume the event.
403 } else { // A different key was pressed.
404 // Do not consume the event.
410 // Implement swipe to refresh
411 swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
412 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
413 swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
415 public void onRefresh() {
416 mainWebView.reload();
420 // `DrawerTitle` identifies the `DrawerLayout` in accessibility mode.
421 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
423 // Listen for touches on the navigation menu.
424 final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationview);
425 navigationView.setNavigationItemSelectedListener(this);
427 // 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.
428 final Menu navigationMenu = navigationView.getMenu();
429 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
430 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
431 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
433 // The `DrawerListener` allows us to update the Navigation Menu.
434 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
436 public void onDrawerSlide(View drawerView, float slideOffset) {
440 public void onDrawerOpened(View drawerView) {
444 public void onDrawerClosed(View drawerView) {
448 public void onDrawerStateChanged(int newState) {
449 // Update the `Back`, `Forward`, and `History` menu items every time the drawer opens.
450 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
451 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
452 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
454 // Hide the keyboard so we can see the navigation menu. `0` indicates no additional flags.
455 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
459 // drawerToggle creates the hamburger icon at the start of the AppBar.
460 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
462 mainWebView.setWebViewClient(new WebViewClient() {
463 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
464 // We have to use the deprecated `shouldOverrideUrlLoading` until API >= 24.
465 @SuppressWarnings("deprecation")
467 public boolean shouldOverrideUrlLoading(WebView view, String url) {
468 // Use an external email program if the link begins with `mailto:`.
469 if (url.startsWith("mailto:")) {
470 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
471 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
473 // Parse the url and set it as the data for the `Intent`.
474 emailIntent.setData(Uri.parse(url));
476 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
477 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
480 startActivity(emailIntent);
482 } else { // Load the URL in Privacy Browser.
483 mainWebView.loadUrl(url, customHeaders);
488 // Update the URL in urlTextBox when the page starts to load.
490 public void onPageStarted(WebView view, String url, Bitmap favicon) {
491 // 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.
492 formattedUrlString = url;
494 // Display the loading URL is the URL text box.
495 urlTextBox.setText(url);
498 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
500 public void onPageFinished(WebView view, String url) {
501 formattedUrlString = url;
503 // Only update urlTextBox if the user is not typing in it.
504 if (!urlTextBox.hasFocus()) {
505 urlTextBox.setText(formattedUrlString);
508 // Store the SSL certificate so it can be accessed from `ViewSslCertificate`.
509 sslCertificate = mainWebView.getCertificate();
512 // Handle SSL Certificate errors.
514 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
515 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
516 sslErrorHandler = handler;
518 // Display the SSL error `AlertDialog`.
519 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateError.displayDialog(error);
520 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.ssl_certificate_error));
524 mainWebView.setWebChromeClient(new WebChromeClient() {
525 // Update the progress bar when a page is loading.
527 public void onProgressChanged(WebView view, int progress) {
528 ProgressBar progressBar = (ProgressBar) appBar.getCustomView().findViewById(R.id.progressBar);
529 progressBar.setProgress(progress);
530 if (progress < 100) {
531 progressBar.setVisibility(View.VISIBLE);
533 progressBar.setVisibility(View.GONE);
535 //Stop the `SwipeToRefresh` indicator if it is running
536 swipeRefreshLayout.setRefreshing(false);
540 // Set the favorite icon when it changes.
542 public void onReceivedIcon(WebView view, Bitmap icon) {
543 // Save a copy of the favorite icon for use if a shortcut is added to the home screen.
546 // Place the favorite icon in the appBar.
547 ImageView imageViewFavoriteIcon = (ImageView) appBar.getCustomView().findViewById(R.id.favoriteIcon);
548 imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
551 // Enter full screen video
553 public void onShowCustomView(View view, CustomViewCallback callback) {
554 // Pause the ad if this is the free flavor.
555 if (BuildConfig.FLAVOR.contentEquals("free")) {
556 BannerAd.pauseAd(adView);
559 // Remove the translucent overlays.
560 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
562 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
563 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
565 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
566 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
567 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
569 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
571 // Set `rootCoordinatorLayout` to fill the entire screen.
572 rootCoordinatorLayout.setFitsSystemWindows(false);
574 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
575 fullScreenVideoFrameLayout.addView(view);
576 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
579 // Exit full screen video
580 public void onHideCustomView() {
581 // Hide `fullScreenVideoFrameLayout`.
582 fullScreenVideoFrameLayout.removeAllViews();
583 fullScreenVideoFrameLayout.setVisibility(View.GONE);
585 // Add the translucent status flag. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
586 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
588 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars. This also clears the `SYSTEM_UI` flags.
589 rootCoordinatorLayout.setFitsSystemWindows(true);
591 // Show the ad if this is the free flavor.
592 if (BuildConfig.FLAVOR.contentEquals("free")) {
593 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
594 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
596 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
597 adView = findViewById(R.id.adView);
602 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
603 registerForContextMenu(mainWebView);
605 // Allow the downloading of files.
606 mainWebView.setDownloadListener(new DownloadListener() {
608 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
609 // Show the `DownloadFile` `AlertDialog` and name this instance `@string/download`.
610 AppCompatDialogFragment downloadFileDialogFragment = DownloadFile.fromUrl(url, contentDisposition, contentLength);
611 downloadFileDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
615 // Allow pinch to zoom.
616 mainWebView.getSettings().setBuiltInZoomControls(true);
618 // Hide zoom controls.
619 mainWebView.getSettings().setDisplayZoomControls(false);
621 // Initialize cookieManager.
622 cookieManager = CookieManager.getInstance();
624 // 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).
625 customHeaders.put("X-Requested-With", "");
627 // 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.
628 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
630 // Apply the settings from the shared preferences.
633 // Get the intent information that started the app.
634 final Intent intent = getIntent();
636 if (intent.getData() != null) {
637 // Get the intent data and convert it to a string.
638 final Uri intentUriData = intent.getData();
639 formattedUrlString = intentUriData.toString();
642 // If formattedUrlString is null assign the homepage to it.
643 if (formattedUrlString == null) {
644 formattedUrlString = homepage;
647 // Load the initial website.
648 mainWebView.loadUrl(formattedUrlString, customHeaders);
650 // If the favorite icon is null, load the default.
651 if (favoriteIcon == null) {
652 // We have to use `ContextCompat` until API >= 21.
653 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
654 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
655 favoriteIcon = favoriteIconBitmapDrawable.getBitmap();
658 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
659 inFullScreenBrowsingMode = false;
661 // Initialize AdView for the free flavor and request an ad. If this is not the free flavor BannerAd.requestAd() does nothing.
662 adView = findViewById(R.id.adView);
663 BannerAd.requestAd(adView);
668 protected void onNewIntent(Intent intent) {
669 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
672 if (intent.getData() != null) {
673 // Get the intent data and convert it to a string.
674 final Uri intentUriData = intent.getData();
675 formattedUrlString = intentUriData.toString();
678 // Close the navigation drawer if it is open.
679 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
680 drawerLayout.closeDrawer(GravityCompat.START);
684 mainWebView.loadUrl(formattedUrlString, customHeaders);
686 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
687 mainWebView.requestFocus();
691 public boolean onCreateOptionsMenu(Menu menu) {
692 // Inflate the menu; this adds items to the action bar if it is present.
693 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
695 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
698 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
699 updatePrivacyIcons(false);
701 // Get handles for the menu items.
702 MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
703 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
704 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
705 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
707 // Only display third-Party Cookies if SDK >= 21
708 toggleThirdPartyCookies.setVisible(Build.VERSION.SDK_INT >= 21);
710 // Get the shared preference values. `this` references the current context.
711 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
713 // Set the status of the additional app bar icons. The default is `false`.
714 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
715 toggleFirstPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
716 toggleDomStorage.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
717 toggleSaveFormData.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
718 } else { //Do not display the additional icons.
719 toggleFirstPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
720 toggleDomStorage.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
721 toggleSaveFormData.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
728 public boolean onPrepareOptionsMenu(Menu menu) {
729 // Get handles for the menu items.
730 MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
731 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
732 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
733 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
734 MenuItem clearCookies = menu.findItem(R.id.clearCookies);
735 MenuItem clearFormData = menu.findItem(R.id.clearFormData);
736 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
738 // Set the status of the menu item checkboxes.
739 toggleFirstPartyCookies.setChecked(firstPartyCookiesEnabled);
740 toggleThirdPartyCookies.setChecked(thirdPartyCookiesEnabled);
741 toggleDomStorage.setChecked(domStorageEnabled);
742 toggleSaveFormData.setChecked(saveFormDataEnabled);
744 // Enable third-party cookies if first-party cookies are enabled.
745 toggleThirdPartyCookies.setEnabled(firstPartyCookiesEnabled);
747 // Enable DOM Storage if JavaScript is enabled.
748 toggleDomStorage.setEnabled(javaScriptEnabled);
750 // Enable Clear Cookies if there are any.
751 clearCookies.setEnabled(cookieManager.hasCookies());
753 // Enable Clear Form Data is there is any.
754 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
755 clearFormData.setEnabled(mainWebViewDatabase.hasFormData());
757 // Only show `Refresh` if `swipeToRefresh` is disabled.
758 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
760 // Initialize font size variables.
761 int fontSize = mainWebView.getSettings().getTextZoom();
762 String fontSizeTitle;
763 MenuItem selectedFontSizeMenuItem;
765 // Prepare the font size title and current size menu item.
768 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.fifty_percent);
769 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeFiftyPercent);
773 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.seventy_five_percent);
774 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeSeventyFivePercent);
778 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
779 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
783 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_twenty_five_percent);
784 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredTwentyFivePercent);
788 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_fifty_percent);
789 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredFiftyPercent);
793 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_seventy_five_percent);
794 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredSeventyFivePercent);
798 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.two_hundred_percent);
799 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeTwoHundredPercent);
803 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
804 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
808 // Set the font size title and select the current size menu item.
809 MenuItem fontSizeMenuItem = menu.findItem(R.id.fontSize);
810 fontSizeMenuItem.setTitle(fontSizeTitle);
811 selectedFontSizeMenuItem.setChecked(true);
813 // Run all the other default commands.
814 super.onPrepareOptionsMenu(menu);
816 // `return true` displays the menu.
821 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
822 @SuppressLint("SetJavaScriptEnabled")
823 // removeAllCookies is deprecated, but it is required for API < 21.
824 @SuppressWarnings("deprecation")
825 public boolean onOptionsItemSelected(MenuItem menuItem) {
826 int menuItemId = menuItem.getItemId();
828 // Set the commands that relate to the menu entries.
829 switch (menuItemId) {
830 case R.id.toggleJavaScript:
831 // Switch the status of javaScriptEnabled.
832 javaScriptEnabled = !javaScriptEnabled;
834 // Apply the new JavaScript status.
835 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
837 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
838 updatePrivacyIcons(true);
840 // Display a `Snackbar`.
841 if (javaScriptEnabled) { // JavaScrip is enabled.
842 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
843 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
844 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
845 } else { // Privacy mode.
846 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
849 // Reload the WebView.
850 mainWebView.reload();
853 case R.id.toggleFirstPartyCookies:
854 // Switch the status of firstPartyCookiesEnabled.
855 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
857 // Update the menu checkbox.
858 menuItem.setChecked(firstPartyCookiesEnabled);
860 // Apply the new cookie status.
861 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
863 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
864 updatePrivacyIcons(true);
866 // Display a `Snackbar`.
867 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
868 Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
869 } else if (javaScriptEnabled){ // JavaScript is still enabled.
870 Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
871 } else { // Privacy mode.
872 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
875 // Reload the WebView.
876 mainWebView.reload();
879 case R.id.toggleThirdPartyCookies:
880 if (Build.VERSION.SDK_INT >= 21) {
881 // Switch the status of thirdPartyCookiesEnabled.
882 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
884 // Update the menu checkbox.
885 menuItem.setChecked(thirdPartyCookiesEnabled);
887 // Apply the new cookie status.
888 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
890 // Display a `Snackbar`.
891 if (thirdPartyCookiesEnabled) {
892 Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
894 Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
897 // Reload the WebView.
898 mainWebView.reload();
899 } // Else do nothing because SDK < 21.
902 case R.id.toggleDomStorage:
903 // Switch the status of domStorageEnabled.
904 domStorageEnabled = !domStorageEnabled;
906 // Update the menu checkbox.
907 menuItem.setChecked(domStorageEnabled);
909 // Apply the new DOM Storage status.
910 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
912 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
913 updatePrivacyIcons(true);
915 // Display a `Snackbar`.
916 if (domStorageEnabled) {
917 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
919 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
922 // Reload the WebView.
923 mainWebView.reload();
926 case R.id.toggleSaveFormData:
927 // Switch the status of saveFormDataEnabled.
928 saveFormDataEnabled = !saveFormDataEnabled;
930 // Update the menu checkbox.
931 menuItem.setChecked(saveFormDataEnabled);
933 // Apply the new form data status.
934 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
936 // Display a `Snackbar`.
937 if (saveFormDataEnabled) {
938 Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
940 Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
943 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
944 updatePrivacyIcons(true);
946 // Reload the WebView.
947 mainWebView.reload();
950 case R.id.clearCookies:
951 if (Build.VERSION.SDK_INT < 21) {
952 cookieManager.removeAllCookie();
954 cookieManager.removeAllCookies(null);
956 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_deleted, Snackbar.LENGTH_SHORT).show();
959 case R.id.clearDomStorage:
960 WebStorage webStorage = WebStorage.getInstance();
961 webStorage.deleteAllData();
962 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_deleted, Snackbar.LENGTH_SHORT).show();
965 case R.id.clearFormData:
966 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
967 mainWebViewDatabase.clearFormData();
968 Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_deleted, Snackbar.LENGTH_SHORT).show();
971 case R.id.fontSizeFiftyPercent:
972 mainWebView.getSettings().setTextZoom(50);
975 case R.id.fontSizeSeventyFivePercent:
976 mainWebView.getSettings().setTextZoom(75);
979 case R.id.fontSizeOneHundredPercent:
980 mainWebView.getSettings().setTextZoom(100);
983 case R.id.fontSizeOneHundredTwentyFivePercent:
984 mainWebView.getSettings().setTextZoom(125);
987 case R.id.fontSizeOneHundredFiftyPercent:
988 mainWebView.getSettings().setTextZoom(150);
991 case R.id.fontSizeOneHundredSeventyFivePercent:
992 mainWebView.getSettings().setTextZoom(175);
995 case R.id.fontSizeTwoHundredPercent:
996 mainWebView.getSettings().setTextZoom(200);
999 case R.id.find_on_page:
1000 // Hide the URL app bar.
1001 supportAppBar.setVisibility(View.GONE);
1003 // Show the Find on Page `RelativeLayout`.
1004 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1006 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android.
1007 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1008 findOnPageEditText.postDelayed(new Runnable()
1013 // Set the focus on `findOnPageEditText`.
1014 findOnPageEditText.requestFocus();
1016 // Display the keyboard.
1017 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1023 Intent shareIntent = new Intent();
1024 shareIntent.setAction(Intent.ACTION_SEND);
1025 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
1026 shareIntent.setType("text/plain");
1027 startActivity(Intent.createChooser(shareIntent, "Share URL"));
1030 case R.id.addToHomescreen:
1031 // Show the `CreateHomeScreenShortcut` `AlertDialog` and name this instance `R.string.create_shortcut`.
1032 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcut();
1033 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.create_shortcut));
1035 //Everything else will be handled by `CreateHomeScreenShortcut` and the associated listener below.
1039 // Get a `PrintManager` instance.
1040 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1042 // Convert `mainWebView` to `printDocumentAdapter`.
1043 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
1045 // Print the document. The print attributes are `null`.
1046 printManager.print(getResources().getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1050 mainWebView.reload();
1054 // Don't consume the event.
1055 return super.onOptionsItemSelected(menuItem);
1059 // removeAllCookies is deprecated, but it is required for API < 21.
1060 @SuppressWarnings("deprecation")
1062 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1063 int menuItemId = menuItem.getItemId();
1065 switch (menuItemId) {
1067 mainWebView.loadUrl(homepage, customHeaders);
1071 if (mainWebView.canGoBack()) {
1072 mainWebView.goBack();
1077 if (mainWebView.canGoForward()) {
1078 mainWebView.goForward();
1083 // Gte the `WebBackForwardList`.
1084 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
1086 // Show the `UrlHistory` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
1087 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistory.loadBackForwardList(this, webBackForwardList);
1088 urlHistoryDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.history));
1091 case R.id.bookmarks:
1092 // Launch Bookmarks.
1093 Intent bookmarksIntent = new Intent(this, Bookmarks.class);
1094 startActivity(bookmarksIntent);
1097 case R.id.downloads:
1098 // Launch the system Download Manager.
1099 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1101 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1102 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1104 startActivity(downloadManagerIntent);
1108 // Launch `Settings`.
1109 Intent settingsIntent = new Intent(this, Settings.class);
1110 startActivity(settingsIntent);
1115 Intent guideIntent = new Intent(this, Guide.class);
1116 startActivity(guideIntent);
1121 Intent aboutIntent = new Intent(this, About.class);
1122 startActivity(aboutIntent);
1125 case R.id.clearAndExit:
1126 // Clear cookies. The commands changed slightly in API 21.
1127 if (Build.VERSION.SDK_INT >= 21) {
1128 cookieManager.removeAllCookies(null);
1130 cookieManager.removeAllCookie();
1133 // Clear DOM storage.
1134 WebStorage domStorage = WebStorage.getInstance();
1135 domStorage.deleteAllData();
1138 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1139 webViewDatabase.clearFormData();
1141 // Clear cache. The argument of "true" includes disk files.
1142 mainWebView.clearCache(true);
1144 // Clear the back/forward history.
1145 mainWebView.clearHistory();
1147 // Clear any SSL certificate preferences.
1148 mainWebView.clearSslPreferences();
1150 // Clear `formattedUrlString`.
1151 formattedUrlString = null;
1153 // Clear `customHeaders`.
1154 customHeaders.clear();
1156 // Detach all views from `mainWebViewRelativeLayout`.
1157 mainWebViewRelativeLayout.removeAllViews();
1159 // Destroy the internal state of `mainWebView`.
1160 mainWebView.destroy();
1162 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
1163 if (Build.VERSION.SDK_INT >= 21) {
1164 finishAndRemoveTask();
1169 // Remove the terminated program from RAM. The status code is `0`.
1177 // Close the navigation drawer.
1178 drawerLayout.closeDrawer(GravityCompat.START);
1183 public void onPostCreate(Bundle savedInstanceState) {
1184 super.onPostCreate(savedInstanceState);
1186 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
1187 drawerToggle.syncState();
1191 public void onConfigurationChanged(Configuration newConfig) {
1192 super.onConfigurationChanged(newConfig);
1194 // Reload the ad for the free flavor if we are not in full screen mode.
1195 if (BuildConfig.FLAVOR.contentEquals("free") && adView.isShown() && !fullScreenVideoFrameLayout.isShown()) {
1197 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1199 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1200 adView = findViewById(R.id.adView);
1203 // `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
1204 // ActivityCompat.invalidateOptionsMenu(this);
1208 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
1209 // Store the `HitTestResult`.
1210 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
1213 final String imageUrl;
1214 final String linkUrl;
1216 // Get a handle for the `ClipboardManager`.
1217 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
1219 switch (hitTestResult.getType()) {
1220 // `SRC_ANCHOR_TYPE` is a link.
1221 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1222 // Get the target URL.
1223 linkUrl = hitTestResult.getExtra();
1225 // Set the target URL as the title of the `ContextMenu`.
1226 menu.setHeaderTitle(linkUrl);
1228 // Add a `Load URL` entry.
1229 menu.add(R.string.load_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1231 public boolean onMenuItemClick(MenuItem item) {
1232 mainWebView.loadUrl(linkUrl, customHeaders);
1237 // Add a `Copy URL` entry.
1238 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1240 public boolean onMenuItemClick(MenuItem item) {
1241 // Save the link URL in a `ClipData`.
1242 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), linkUrl);
1244 // Set the `ClipData` as the clipboard's primary clip.
1245 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
1250 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1251 menu.add(R.string.cancel);
1254 case WebView.HitTestResult.EMAIL_TYPE:
1255 // Get the target URL.
1256 linkUrl = hitTestResult.getExtra();
1258 // Set the target URL as the title of the `ContextMenu`.
1259 menu.setHeaderTitle(linkUrl);
1261 // Add a `Write Email` entry.
1262 menu.add(R.string.write_email).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1264 public boolean onMenuItemClick(MenuItem item) {
1265 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1266 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1268 // Parse the url and set it as the data for the `Intent`.
1269 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
1271 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
1272 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1275 startActivity(emailIntent);
1280 // Add a `Copy Email Address` entry.
1281 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1283 public boolean onMenuItemClick(MenuItem item) {
1284 // Save the email address in a `ClipData`.
1285 ClipData srcEmailTypeClipData = ClipData.newPlainText(getResources().getString(R.string.email_address), linkUrl);
1287 // Set the `ClipData` as the clipboard's primary clip.
1288 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
1293 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1294 menu.add(R.string.cancel);
1297 // `IMAGE_TYPE` is an image.
1298 case WebView.HitTestResult.IMAGE_TYPE:
1299 // Get the image URL.
1300 imageUrl = hitTestResult.getExtra();
1302 // Set the image URL as the title of the `ContextMenu`.
1303 menu.setHeaderTitle(imageUrl);
1305 // Add a `View Image` entry.
1306 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1308 public boolean onMenuItemClick(MenuItem item) {
1309 mainWebView.loadUrl(imageUrl, customHeaders);
1314 // Add a `Download Image` entry.
1315 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1317 public boolean onMenuItemClick(MenuItem item) {
1318 // Show the `DownloadImage` `AlertDialog` and name this instance `@string/download`.
1319 AppCompatDialogFragment downloadImageDialogFragment = DownloadImage.imageUrl(imageUrl);
1320 downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1325 // Add a `Copy URL` entry.
1326 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1328 public boolean onMenuItemClick(MenuItem item) {
1329 // Save the image URL in a `ClipData`.
1330 ClipData srcImageTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1332 // Set the `ClipData` as the clipboard's primary clip.
1333 clipboardManager.setPrimaryClip(srcImageTypeClipData);
1338 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1339 menu.add(R.string.cancel);
1343 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
1344 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1345 // Get the image URL.
1346 imageUrl = hitTestResult.getExtra();
1348 // Set the image URL as the title of the `ContextMenu`.
1349 menu.setHeaderTitle(imageUrl);
1351 // Add a `View Image` entry.
1352 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1354 public boolean onMenuItemClick(MenuItem item) {
1355 mainWebView.loadUrl(imageUrl, customHeaders);
1360 // Add a `Download Image` entry.
1361 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1363 public boolean onMenuItemClick(MenuItem item) {
1364 // Show the `DownloadImage` `AlertDialog` and name this instance `@string/download`.
1365 AppCompatDialogFragment downloadImageDialogFragment = DownloadImage.imageUrl(imageUrl);
1366 downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1371 // Add a `Copy URL` entry.
1372 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1374 public boolean onMenuItemClick(MenuItem item) {
1375 // Save the image URL in a `ClipData`.
1376 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1378 // Set the `ClipData` as the clipboard's primary clip.
1379 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
1384 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1385 menu.add(R.string.cancel);
1391 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
1392 // Get shortcutNameEditText from the alert dialog.
1393 EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
1395 // Create the bookmark shortcut based on formattedUrlString.
1396 Intent bookmarkShortcut = new Intent();
1397 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
1398 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
1400 // Place the bookmark shortcut on the home screen.
1401 Intent placeBookmarkShortcut = new Intent();
1402 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
1403 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
1404 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
1405 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
1406 sendBroadcast(placeBookmarkShortcut);
1410 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
1411 // Get a handle for the system `DOWNLOAD_SERVICE`.
1412 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
1414 // Parse `imageUrl`.
1415 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
1417 // Get the file name from `dialogFragment`.
1418 EditText downloadImageNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_image_name);
1419 String imageName = downloadImageNameEditText.getText().toString();
1421 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
1422 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `imageName`.
1423 downloadRequest.setDestinationInExternalFilesDir(this, "/", imageName);
1424 } else { // Only set the title using `imageName`.
1425 downloadRequest.setTitle(imageName);
1428 // Allow `MediaScanner` to index the download if it is a media file.
1429 downloadRequest.allowScanningByMediaScanner();
1431 // Add the URL as the description for the download.
1432 downloadRequest.setDescription(imageUrl);
1434 // Show the download notification after the download is completed.
1435 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
1437 // Initiate the download.
1438 downloadManager.enqueue(downloadRequest);
1442 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
1443 // Get a handle for the system `DOWNLOAD_SERVICE`.
1444 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
1446 // Parse `downloadUrl`.
1447 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
1449 // Get the file name from `dialogFragment`.
1450 EditText downloadFileNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_file_name);
1451 String fileName = downloadFileNameEditText.getText().toString();
1453 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
1454 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `fileName`.
1455 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
1456 } else { // Only set the title using `fileName`.
1457 downloadRequest.setTitle(fileName);
1460 // Allow `MediaScanner` to index the download if it is a media file.
1461 downloadRequest.allowScanningByMediaScanner();
1463 // Add the URL as the description for the download.
1464 downloadRequest.setDescription(downloadUrl);
1466 // Show the download notification after the download is completed.
1467 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
1469 // Initiate the download.
1470 downloadManager.enqueue(downloadRequest);
1473 public void viewSslCertificate(View view) {
1474 // Show the `ViewSslCertificate` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
1475 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificate();
1476 viewSslCertificateDialogFragment.show(getFragmentManager(), getResources().getString(R.string.view_ssl_certificate));
1480 public void onSslErrorCancel() {
1481 sslErrorHandler.cancel();
1485 public void onSslErrorProceed() {
1486 sslErrorHandler.proceed();
1490 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
1491 // Load the history entry.
1492 mainWebView.goBackOrForward(moveBackOrForwardSteps);
1496 public void onClearHistory() {
1497 // Clear the history.
1498 mainWebView.clearHistory();
1501 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
1503 public void onBackPressed() {
1504 // Close the navigation drawer if it is available. GravityCompat.START is the drawer on the left on Left-to-Right layout text.
1505 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1506 drawerLayout.closeDrawer(GravityCompat.START);
1508 // Load the previous URL if available.
1509 if (mainWebView.canGoBack()) {
1510 mainWebView.goBack();
1512 // Pass `onBackPressed()` to the system.
1513 super.onBackPressed();
1519 public void onPause() {
1520 // Pause `mainWebView`.
1521 mainWebView.onPause();
1523 // Stop all JavaScript.
1524 mainWebView.pauseTimers();
1526 // Pause the adView or it will continue to consume resources in the background on the free flavor.
1527 if (BuildConfig.FLAVOR.contentEquals("free")) {
1528 BannerAd.pauseAd(adView);
1535 public void onResume() {
1538 // Resume JavaScript (if enabled).
1539 mainWebView.resumeTimers();
1541 // Resume `mainWebView`.
1542 mainWebView.onResume();
1544 // Resume the adView for the free flavor.
1545 if (BuildConfig.FLAVOR.contentEquals("free")) {
1546 BannerAd.resumeAd(adView);
1551 public void onRestart() {
1554 // Apply the settings from shared preferences, which might have been changed in `Settings`.
1557 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1558 updatePrivacyIcons(true);
1562 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
1563 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
1564 String unformattedUrlString = urlTextBox.getText().toString().trim();
1566 URL unformattedUrl = null;
1567 Uri.Builder formattedUri = new Uri.Builder();
1569 // Check to see if unformattedUrlString is a valid URL. Otherwise, convert it into a Duck Duck Go search.
1570 if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
1571 // Add http:// at the beginning if it is missing. Otherwise the app will segfault.
1572 if (!unformattedUrlString.startsWith("http")) {
1573 unformattedUrlString = "http://" + unformattedUrlString;
1576 // 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.
1578 unformattedUrl = new URL(unformattedUrlString);
1579 } catch (MalformedURLException e) {
1580 e.printStackTrace();
1583 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
1584 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
1585 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
1586 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
1587 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
1588 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
1590 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
1591 formattedUrlString = formattedUri.build().toString();
1593 // Sanitize the search input and convert it to a DuckDuckGo search.
1594 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
1596 // Use the correct search URL.
1597 if (javaScriptEnabled) { // JavaScript is enabled.
1598 formattedUrlString = javaScriptEnabledSearchURL + encodedUrlString;
1599 } else { // JavaScript is disabled.
1600 formattedUrlString = javaScriptDisabledSearchURL + encodedUrlString;
1604 mainWebView.loadUrl(formattedUrlString, customHeaders);
1606 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
1607 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1610 public void findPreviousOnPage(View view) {
1611 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
1612 mainWebView.findNext(false);
1615 public void findNextOnPage(View view) {
1616 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
1617 mainWebView.findNext(true);
1620 public void closeFindOnPage(View view) {
1621 // Delete the contents of `find_on_page_edittext`.
1622 findOnPageEditText.setText(null);
1624 // Clear the highlighted phrases.
1625 mainWebView.clearMatches();
1627 // Hide the Find on Page `RelativeLayout`.
1628 findOnPageLinearLayout.setVisibility(View.GONE);
1630 // Show the URL app bar.
1631 supportAppBar.setVisibility(View.VISIBLE);
1633 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
1634 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1637 private void applySettings() {
1638 // Get the shared preference values. `this` references the current context.
1639 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1641 // Store the values from `sharedPreferences` in variables.
1642 String userAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
1643 String customUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
1644 String javaScriptDisabledSearchString = sharedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=");
1645 String javaScriptDisabledCustomSearchString = sharedPreferences.getString("javascript_disabled_search_custom_url", "");
1646 String javaScriptEnabledSearchString = sharedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=");
1647 String javaScriptEnabledCustomSearchString = sharedPreferences.getString("javascript_enabled_search_custom_url", "");
1648 String homepageString = sharedPreferences.getString("homepage", "https://www.duckduckgo.com");
1649 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
1650 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh_enabled", false);
1651 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", true);
1652 boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
1653 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("enable_full_screen_browsing_mode", false);
1654 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
1655 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
1657 // Because they can be modified on-the-fly by the user, these default settings are only applied when the program first runs.
1658 if (javaScriptEnabled == null) { // If `javaScriptEnabled` is null the program is just starting.
1659 // Get the values from `sharedPreferences`.
1660 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
1661 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
1662 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
1663 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
1664 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
1666 // Apply the default settings.
1667 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1668 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1669 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1670 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1671 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
1673 // Set third-party cookies status if API >= 21.
1674 if (Build.VERSION.SDK_INT >= 21) {
1675 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1679 // Apply the other settings from `sharedPreferences`.
1680 homepage = homepageString;
1681 swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
1683 // Set the user agent initial status.
1684 switch (userAgentString) {
1685 case "Default user agent":
1686 // Set the user agent to `""`, which uses the default value.
1687 mainWebView.getSettings().setUserAgentString("");
1690 case "Custom user agent":
1691 // Set the custom user agent.
1692 mainWebView.getSettings().setUserAgentString(customUserAgentString);
1696 // Use the selected user agent.
1697 mainWebView.getSettings().setUserAgentString(userAgentString);
1701 // Set JavaScript disabled search.
1702 if (javaScriptDisabledSearchString.equals("Custom URL")) { // Get the custom URL string.
1703 javaScriptDisabledSearchURL = javaScriptDisabledCustomSearchString;
1704 } else { // Use the string from the pre-built list.
1705 javaScriptDisabledSearchURL = javaScriptDisabledSearchString;
1708 // Set JavaScript enabled search.
1709 if (javaScriptEnabledSearchString.equals("Custom URL")) { // Get the custom URL string.
1710 javaScriptEnabledSearchURL = javaScriptEnabledCustomSearchString;
1711 } else { // Use the string from the pre-built list.
1712 javaScriptEnabledSearchURL = javaScriptEnabledSearchString;
1715 // Set Do Not Track status.
1716 if (doNotTrackEnabled) {
1717 customHeaders.put("DNT", "1");
1719 customHeaders.remove("DNT");
1722 // Set Orbot proxy status.
1723 if (proxyThroughOrbot) {
1724 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
1725 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
1726 } else { // Reset the proxy to default. The host is `""` and the port is `"0"`.
1727 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
1730 // If we are in full screen mode update the `SYSTEM_UI` flags.
1731 if (inFullScreenBrowsingMode) {
1732 if (hideSystemBarsOnFullscreen) { // Hide everything.
1733 // Remove the translucent navigation setting if it is currently flagged.
1734 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1736 // Remove the translucent status bar overlay.
1737 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1739 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1740 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1742 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1743 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1744 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
1746 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1747 } else { // Hide everything except the status and navigation bars.
1748 // Add the translucent status flag if it is unset.
1749 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1751 if (translucentNavigationBarOnFullscreen) {
1752 // Set the navigation bar to be translucent.
1753 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1755 // Set the navigation bar to be black.
1756 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1762 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
1763 // Get handles for the icons.
1764 MenuItem privacyIcon = mainMenu.findItem(R.id.toggleJavaScript);
1765 MenuItem firstPartyCookiesIcon = mainMenu.findItem(R.id.toggleFirstPartyCookies);
1766 MenuItem domStorageIcon = mainMenu.findItem(R.id.toggleDomStorage);
1767 MenuItem formDataIcon = mainMenu.findItem(R.id.toggleSaveFormData);
1769 // Update `privacyIcon`.
1770 if (javaScriptEnabled) { // JavaScript is enabled.
1771 privacyIcon.setIcon(R.drawable.javascript_enabled);
1772 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
1773 privacyIcon.setIcon(R.drawable.warning);
1774 } else { // All the dangerous features are disabled.
1775 privacyIcon.setIcon(R.drawable.privacy_mode);
1778 // Update `firstPartyCookiesIcon`.
1779 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1780 firstPartyCookiesIcon.setIcon(R.drawable.cookies_enabled);
1781 } else { // First-party cookies are disabled.
1782 firstPartyCookiesIcon.setIcon(R.drawable.cookies_disabled);
1785 // Update `domStorageIcon`.
1786 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
1787 domStorageIcon.setIcon(R.drawable.dom_storage_enabled);
1788 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
1789 domStorageIcon.setIcon(R.drawable.dom_storage_disabled);
1790 } else { // JavaScript is disabled, so DOM storage is ghosted.
1791 domStorageIcon.setIcon(R.drawable.dom_storage_ghosted);
1794 // Update `formDataIcon`.
1795 if (saveFormDataEnabled) { // Form data is enabled.
1796 formDataIcon.setIcon(R.drawable.form_data_enabled);
1797 } else { // Form data is disabled.
1798 formDataIcon.setIcon(R.drawable.form_data_disabled);
1801 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`. `this` references the current activity.
1802 if (runInvalidateOptionsMenu) {
1803 ActivityCompat.invalidateOptionsMenu(this);