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()`, and `closeFindOnPage()`.
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 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
134 private EditText findOnPageEditText;
136 // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
137 private FrameLayout fullScreenVideoFrameLayout;
139 // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu`, and `onRestart()`.
140 private SwipeRefreshLayout swipeRefreshLayout;
142 // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, and `onRestart()`.
143 private CookieManager cookieManager;
145 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrlFromTextBox()`.
146 private final Map<String, String> customHeaders = new HashMap<>();
148 // `javaScriptEnabled` is also used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `applySettings()`.
149 // It is `Boolean` instead of `boolean` because `applySettings()` needs to know if it is `null`.
150 private Boolean javaScriptEnabled;
152 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
153 private boolean firstPartyCookiesEnabled;
155 // `thirdPartyCookiesEnabled` used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
156 private boolean thirdPartyCookiesEnabled;
158 // `domStorageEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
159 private boolean domStorageEnabled;
161 // `saveFormDataEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
162 private boolean saveFormDataEnabled;
164 // `swipeToRefreshEnabled` is used in `onPrepareOptionsMenu()` and `applySettings()`.
165 private boolean swipeToRefreshEnabled;
167 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applySettings()`.
168 private String homepage;
170 // `javaScriptDisabledSearchURL` is used in `loadURLFromTextBox()` and `applySettings()`.
171 private String javaScriptDisabledSearchURL;
173 // `javaScriptEnabledSearchURL` is used in `loadURLFromTextBox()` and `applySettings()`.
174 private String javaScriptEnabledSearchURL;
176 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applySettings()`.
177 private boolean hideSystemBarsOnFullscreen;
179 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applySettings()`.
180 private boolean translucentNavigationBarOnFullscreen;
182 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
183 private Menu mainMenu;
185 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
186 private ActionBarDrawerToggle drawerToggle;
188 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, and `loadUrlFromTextBox()`.
189 private EditText urlTextBox;
191 // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
194 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
195 private SslErrorHandler sslErrorHandler;
197 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
198 private InputMethodManager inputMethodManager;
201 // 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.
202 @SuppressLint("SetJavaScriptEnabled")
203 protected void onCreate(Bundle savedInstanceState) {
204 super.onCreate(savedInstanceState);
205 setContentView(R.layout.drawerlayout);
207 // Get a handle for `inputMethodManager`.
208 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
210 // We need to use the `SupportActionBar` from `android.support.v7.app.ActionBar` until the minimum API is >= 21.
211 Toolbar supportAppBar = (Toolbar) findViewById(R.id.app_bar);
212 setSupportActionBar(supportAppBar);
213 appBar = getSupportActionBar();
215 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
216 assert appBar != null;
218 // Add the custom url_app_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
219 appBar.setCustomView(R.layout.url_app_bar);
220 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
222 // Set the "go" button on the keyboard to load the URL in urlTextBox.
223 urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.urlTextBox);
224 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
226 public boolean onKey(View v, int keyCode, KeyEvent event) {
227 // If the event is a key-down event on the `enter` button, load the URL.
228 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
229 // Load the URL into the mainWebView and consume the event.
231 loadUrlFromTextBox();
232 } catch (UnsupportedEncodingException e) {
235 // If the enter key was pressed, consume the event.
238 // If any other key was pressed, do not consume the event.
244 // Get handles for views that need to be accessed.
245 drawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout);
246 rootCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.root_coordinatorlayout);
247 mainWebView = (WebView) findViewById(R.id.mainWebView);
248 findOnPageEditText = (EditText) findViewById(R.id.find_on_page_edittext);
249 fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.full_screen_video_framelayout);
251 // Create a double-tap listener to toggle full-screen mode.
252 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
253 // Override `onDoubleTap()`. All other events are handled using the default settings.
255 public boolean onDoubleTap(MotionEvent event) {
256 if (appBar.isShowing()) { // If `appBar` is visible, switch to full screen mode.
257 // Hide the `appBar`.
260 // Hide the `BannerAd` in the free flavor.
261 if (BuildConfig.FLAVOR.contentEquals("free")) {
262 BannerAd.hideAd(adView);
265 // Modify the system bars.
266 if (hideSystemBarsOnFullscreen) { // Hide everything.
267 // Remove the translucent overlays.
268 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
270 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
271 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
273 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
274 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
275 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
277 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
279 // Set `rootCoordinatorLayout` to fill the whole screen.
280 rootCoordinatorLayout.setFitsSystemWindows(false);
281 } else { // Hide everything except the status and navigation bars.
282 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
283 rootCoordinatorLayout.setFitsSystemWindows(false);
285 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.
286 // Set the navigation bar to be translucent.
287 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
290 } else { // Switch to normal viewing mode.
291 // Show the `appBar`.
294 // Show the `BannerAd` in the free flavor.
295 if (BuildConfig.FLAVOR.contentEquals("free")) {
296 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
297 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
299 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
300 adView = findViewById(R.id.adView);
303 // Remove the translucent navigation bar flag if it is set.
304 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
306 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
307 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
309 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
310 rootCoordinatorLayout.setSystemUiVisibility(0);
312 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
313 rootCoordinatorLayout.setFitsSystemWindows(true);
316 // Consume the double-tap.
321 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
322 mainWebView.setOnTouchListener(new View.OnTouchListener() {
324 public boolean onTouch(View v, MotionEvent event) {
325 // Send the `event` to `gestureDetector`.
326 return gestureDetector.onTouchEvent(event);
330 // Update `findOnPageCountTextView`.
331 mainWebView.setFindListener(new WebView.FindListener() {
332 // Get a handle for `findOnPageCountTextView`.
333 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
336 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
337 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
338 // Set `findOnPageCountTextView` to `0/0`.
339 findOnPageCountTextView.setText(R.string.zero_of_zero);
340 } else if (isDoneCounting) { // There are matches.
341 // `activeMatchOrdinal` is zero-based.
342 int activeMatch = activeMatchOrdinal + 1;
344 // Set `findOnPageCountTextView`.
345 findOnPageCountTextView.setText(activeMatch + "/" + numberOfMatches);
350 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
351 findOnPageEditText.addTextChangedListener(new TextWatcher() {
353 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
358 public void onTextChanged(CharSequence s, int start, int before, int count) {
363 public void afterTextChanged(Editable s) {
364 // Search for the text in `mainWebView`.
365 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
369 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
370 findOnPageEditText.setOnKeyListener(new View.OnKeyListener() {
372 public boolean onKey(View v, int keyCode, KeyEvent event) {
373 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
374 // Hide the soft keyboard. `0` indicates no additional flags.
375 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
377 // Consume the event.
379 } else { // A different key was pressed.
380 // Do not consume the event.
386 // Implement swipe to refresh
387 swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
388 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
389 swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
391 public void onRefresh() {
392 mainWebView.reload();
396 // `DrawerTitle` identifies the `DrawerLayout` in accessibility mode.
397 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
399 // Listen for touches on the navigation menu.
400 final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationview);
401 navigationView.setNavigationItemSelectedListener(this);
403 // 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.
404 final Menu navigationMenu = navigationView.getMenu();
405 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
406 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
407 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
409 // The `DrawerListener` allows us to update the Navigation Menu.
410 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
412 public void onDrawerSlide(View drawerView, float slideOffset) {
416 public void onDrawerOpened(View drawerView) {
420 public void onDrawerClosed(View drawerView) {
424 public void onDrawerStateChanged(int newState) {
425 // Update the `Back`, `Forward`, and `History` menu items every time the drawer opens.
426 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
427 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
428 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
430 // Hide the keyboard so we can see the navigation menu. `0` indicates no additional flags.
431 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
435 // drawerToggle creates the hamburger icon at the start of the AppBar.
436 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
438 mainWebView.setWebViewClient(new WebViewClient() {
439 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
440 // We have to use the deprecated `shouldOverrideUrlLoading` until API >= 24.
441 @SuppressWarnings("deprecation")
443 public boolean shouldOverrideUrlLoading(WebView view, String url) {
444 // Use an external email program if the link begins with `mailto:`.
445 if (url.startsWith("mailto:")) {
446 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
447 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
449 // Parse the url and set it as the data for the `Intent`.
450 emailIntent.setData(Uri.parse(url));
452 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
453 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
456 startActivity(emailIntent);
458 } else { // Load the URL in Privacy Browser.
459 mainWebView.loadUrl(url, customHeaders);
464 // Update the URL in urlTextBox when the page starts to load.
466 public void onPageStarted(WebView view, String url, Bitmap favicon) {
467 // 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.
468 formattedUrlString = url;
470 // Display the loading URL is the URL text box.
471 urlTextBox.setText(url);
474 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
476 public void onPageFinished(WebView view, String url) {
477 formattedUrlString = url;
479 // Only update urlTextBox if the user is not typing in it.
480 if (!urlTextBox.hasFocus()) {
481 urlTextBox.setText(formattedUrlString);
484 // Store the SSL certificate so it can be accessed from `ViewSslCertificate`.
485 sslCertificate = mainWebView.getCertificate();
488 // Handle SSL Certificate errors.
490 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
491 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
492 sslErrorHandler = handler;
494 // Display the SSL error `AlertDialog`.
495 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateError.displayDialog(error);
496 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.ssl_certificate_error));
500 mainWebView.setWebChromeClient(new WebChromeClient() {
501 // Update the progress bar when a page is loading.
503 public void onProgressChanged(WebView view, int progress) {
504 ProgressBar progressBar = (ProgressBar) appBar.getCustomView().findViewById(R.id.progressBar);
505 progressBar.setProgress(progress);
506 if (progress < 100) {
507 progressBar.setVisibility(View.VISIBLE);
509 progressBar.setVisibility(View.GONE);
511 //Stop the `SwipeToRefresh` indicator if it is running
512 swipeRefreshLayout.setRefreshing(false);
516 // Set the favorite icon when it changes.
518 public void onReceivedIcon(WebView view, Bitmap icon) {
519 // Save a copy of the favorite icon for use if a shortcut is added to the home screen.
522 // Place the favorite icon in the appBar.
523 ImageView imageViewFavoriteIcon = (ImageView) appBar.getCustomView().findViewById(R.id.favoriteIcon);
524 imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
527 // Enter full screen video
529 public void onShowCustomView(View view, CustomViewCallback callback) {
530 // Pause the ad if this is the free flavor.
531 if (BuildConfig.FLAVOR.contentEquals("free")) {
532 BannerAd.pauseAd(adView);
535 // Remove the translucent overlays.
536 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
538 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
539 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
541 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
542 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
543 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
545 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
547 // Set `rootCoordinatorLayout` to fill the entire screen.
548 rootCoordinatorLayout.setFitsSystemWindows(false);
550 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
551 fullScreenVideoFrameLayout.addView(view);
552 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
555 // Exit full screen video
556 public void onHideCustomView() {
557 // Hide `fullScreenVideoFrameLayout`.
558 fullScreenVideoFrameLayout.removeAllViews();
559 fullScreenVideoFrameLayout.setVisibility(View.GONE);
561 // Add the translucent status flag. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
562 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
564 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars. This also clears the `SYSTEM_UI` flags.
565 rootCoordinatorLayout.setFitsSystemWindows(true);
567 // Show the ad if this is the free flavor.
568 if (BuildConfig.FLAVOR.contentEquals("free")) {
569 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
570 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
572 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
573 adView = findViewById(R.id.adView);
578 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
579 registerForContextMenu(mainWebView);
581 // Allow the downloading of files.
582 mainWebView.setDownloadListener(new DownloadListener() {
584 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
585 // Show the `DownloadFile` `AlertDialog` and name this instance `@string/download`.
586 AppCompatDialogFragment downloadFileDialogFragment = DownloadFile.fromUrl(url, contentDisposition, contentLength);
587 downloadFileDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
591 // Allow pinch to zoom.
592 mainWebView.getSettings().setBuiltInZoomControls(true);
594 // Hide zoom controls.
595 mainWebView.getSettings().setDisplayZoomControls(false);
597 // Initialize cookieManager.
598 cookieManager = CookieManager.getInstance();
600 // 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).
601 customHeaders.put("X-Requested-With", "");
603 // Initialize the default preference values the first time the program is run.
604 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
606 // Apply the settings from the shared preferences.
609 // Get the intent information that started the app.
610 final Intent intent = getIntent();
612 if (intent.getData() != null) {
613 // Get the intent data and convert it to a string.
614 final Uri intentUriData = intent.getData();
615 formattedUrlString = intentUriData.toString();
618 // If formattedUrlString is null assign the homepage to it.
619 if (formattedUrlString == null) {
620 formattedUrlString = homepage;
623 // Load the initial website.
624 mainWebView.loadUrl(formattedUrlString, customHeaders);
626 // If the favorite icon is null, load the default.
627 if (favoriteIcon == null) {
628 // We have to use `ContextCompat` until API >= 21.
629 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
630 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
631 favoriteIcon = favoriteIconBitmapDrawable.getBitmap();
634 // Initialize AdView for the free flavor and request an ad. If this is not the free flavor BannerAd.requestAd() does nothing.
635 adView = findViewById(R.id.adView);
636 BannerAd.requestAd(adView);
641 protected void onNewIntent(Intent intent) {
642 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
645 if (intent.getData() != null) {
646 // Get the intent data and convert it to a string.
647 final Uri intentUriData = intent.getData();
648 formattedUrlString = intentUriData.toString();
651 // Close the navigation drawer if it is open.
652 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
653 drawerLayout.closeDrawer(GravityCompat.START);
657 mainWebView.loadUrl(formattedUrlString, customHeaders);
659 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
660 mainWebView.requestFocus();
664 public boolean onCreateOptionsMenu(Menu menu) {
665 // Inflate the menu; this adds items to the action bar if it is present.
666 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
668 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
671 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
672 updatePrivacyIcons(false);
674 // Get handles for the menu items.
675 MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
676 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
677 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
678 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
680 // Only display third-Party Cookies if SDK >= 21
681 toggleThirdPartyCookies.setVisible(Build.VERSION.SDK_INT >= 21);
683 // Get the shared preference values. `this` references the current context.
684 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
686 // Set the status of the additional app bar icons. The default is `false`.
687 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
688 toggleFirstPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
689 toggleDomStorage.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
690 toggleSaveFormData.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
691 } else { //Do not display the additional icons.
692 toggleFirstPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
693 toggleDomStorage.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
694 toggleSaveFormData.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
701 public boolean onPrepareOptionsMenu(Menu menu) {
702 // Get handles for the menu items.
703 MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
704 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
705 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
706 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
707 MenuItem clearCookies = menu.findItem(R.id.clearCookies);
708 MenuItem clearFormData = menu.findItem(R.id.clearFormData);
709 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
711 // Set the status of the menu item checkboxes.
712 toggleFirstPartyCookies.setChecked(firstPartyCookiesEnabled);
713 toggleThirdPartyCookies.setChecked(thirdPartyCookiesEnabled);
714 toggleDomStorage.setChecked(domStorageEnabled);
715 toggleSaveFormData.setChecked(saveFormDataEnabled);
717 // Enable third-party cookies if first-party cookies are enabled.
718 toggleThirdPartyCookies.setEnabled(firstPartyCookiesEnabled);
720 // Enable DOM Storage if JavaScript is enabled.
721 toggleDomStorage.setEnabled(javaScriptEnabled);
723 // Enable Clear Cookies if there are any.
724 clearCookies.setEnabled(cookieManager.hasCookies());
726 // Enable Clear Form Data is there is any.
727 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
728 clearFormData.setEnabled(mainWebViewDatabase.hasFormData());
730 // Only show `Refresh` if `swipeToRefresh` is disabled.
731 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
733 // Initialize font size variables.
734 int fontSize = mainWebView.getSettings().getTextZoom();
735 String fontSizeTitle;
736 MenuItem selectedFontSizeMenuItem;
738 // Prepare the font size title and current size menu item.
741 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.fifty_percent);
742 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeFiftyPercent);
746 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.seventy_five_percent);
747 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeSeventyFivePercent);
751 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
752 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
756 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_twenty_five_percent);
757 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredTwentyFivePercent);
761 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_fifty_percent);
762 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredFiftyPercent);
766 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_seventy_five_percent);
767 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredSeventyFivePercent);
771 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.two_hundred_percent);
772 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeTwoHundredPercent);
776 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
777 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
781 // Set the font size title and select the current size menu item.
782 MenuItem fontSizeMenuItem = menu.findItem(R.id.fontSize);
783 fontSizeMenuItem.setTitle(fontSizeTitle);
784 selectedFontSizeMenuItem.setChecked(true);
786 // Run all the other default commands.
787 super.onPrepareOptionsMenu(menu);
789 // `return true` displays the menu.
794 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
795 @SuppressLint("SetJavaScriptEnabled")
796 // removeAllCookies is deprecated, but it is required for API < 21.
797 @SuppressWarnings("deprecation")
798 public boolean onOptionsItemSelected(MenuItem menuItem) {
799 int menuItemId = menuItem.getItemId();
801 // Set the commands that relate to the menu entries.
802 switch (menuItemId) {
803 case R.id.toggleJavaScript:
804 // Switch the status of javaScriptEnabled.
805 javaScriptEnabled = !javaScriptEnabled;
807 // Apply the new JavaScript status.
808 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
810 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
811 updatePrivacyIcons(true);
813 // Display a `Snackbar`.
814 if (javaScriptEnabled) { // JavaScrip is enabled.
815 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
816 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
817 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
818 } else { // Privacy mode.
819 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
822 // Reload the WebView.
823 mainWebView.reload();
826 case R.id.toggleFirstPartyCookies:
827 // Switch the status of firstPartyCookiesEnabled.
828 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
830 // Update the menu checkbox.
831 menuItem.setChecked(firstPartyCookiesEnabled);
833 // Apply the new cookie status.
834 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
836 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
837 updatePrivacyIcons(true);
839 // Display a `Snackbar`.
840 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
841 Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
842 } else if (javaScriptEnabled){ // JavaScript is still enabled.
843 Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
844 } else { // Privacy mode.
845 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
848 // Reload the WebView.
849 mainWebView.reload();
852 case R.id.toggleThirdPartyCookies:
853 if (Build.VERSION.SDK_INT >= 21) {
854 // Switch the status of thirdPartyCookiesEnabled.
855 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
857 // Update the menu checkbox.
858 menuItem.setChecked(thirdPartyCookiesEnabled);
860 // Apply the new cookie status.
861 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
863 // Display a `Snackbar`.
864 if (thirdPartyCookiesEnabled) {
865 Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
867 Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
870 // Reload the WebView.
871 mainWebView.reload();
872 } // Else do nothing because SDK < 21.
875 case R.id.toggleDomStorage:
876 // Switch the status of domStorageEnabled.
877 domStorageEnabled = !domStorageEnabled;
879 // Update the menu checkbox.
880 menuItem.setChecked(domStorageEnabled);
882 // Apply the new DOM Storage status.
883 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
885 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
886 updatePrivacyIcons(true);
888 // Display a `Snackbar`.
889 if (domStorageEnabled) {
890 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
892 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
895 // Reload the WebView.
896 mainWebView.reload();
899 case R.id.toggleSaveFormData:
900 // Switch the status of saveFormDataEnabled.
901 saveFormDataEnabled = !saveFormDataEnabled;
903 // Update the menu checkbox.
904 menuItem.setChecked(saveFormDataEnabled);
906 // Apply the new form data status.
907 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
909 // Display a `Snackbar`.
910 if (saveFormDataEnabled) {
911 Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
913 Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
916 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
917 updatePrivacyIcons(true);
919 // Reload the WebView.
920 mainWebView.reload();
923 case R.id.clearCookies:
924 if (Build.VERSION.SDK_INT < 21) {
925 cookieManager.removeAllCookie();
927 cookieManager.removeAllCookies(null);
929 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_deleted, Snackbar.LENGTH_SHORT).show();
932 case R.id.clearDomStorage:
933 WebStorage webStorage = WebStorage.getInstance();
934 webStorage.deleteAllData();
935 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_deleted, Snackbar.LENGTH_SHORT).show();
938 case R.id.clearFormData:
939 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
940 mainWebViewDatabase.clearFormData();
941 Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_deleted, Snackbar.LENGTH_SHORT).show();
944 case R.id.fontSizeFiftyPercent:
945 mainWebView.getSettings().setTextZoom(50);
948 case R.id.fontSizeSeventyFivePercent:
949 mainWebView.getSettings().setTextZoom(75);
952 case R.id.fontSizeOneHundredPercent:
953 mainWebView.getSettings().setTextZoom(100);
956 case R.id.fontSizeOneHundredTwentyFivePercent:
957 mainWebView.getSettings().setTextZoom(125);
960 case R.id.fontSizeOneHundredFiftyPercent:
961 mainWebView.getSettings().setTextZoom(150);
964 case R.id.fontSizeOneHundredSeventyFivePercent:
965 mainWebView.getSettings().setTextZoom(175);
968 case R.id.fontSizeTwoHundredPercent:
969 mainWebView.getSettings().setTextZoom(200);
972 case R.id.find_on_page:
973 // Hide the URL app bar.
974 Toolbar appBarToolbar = (Toolbar) findViewById(R.id.app_bar);
975 appBarToolbar.setVisibility(View.GONE);
977 // Show the Find on Page `RelativeLayout`.
978 LinearLayout findOnPageLinearLayout = (LinearLayout) findViewById(R.id.find_on_page_linearlayout);
979 findOnPageLinearLayout.setVisibility(View.VISIBLE);
981 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android.
982 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
983 findOnPageEditText.postDelayed(new Runnable()
988 // Set the focus on `findOnPageEditText`.
989 findOnPageEditText.requestFocus();
991 // Display the keyboard.
992 inputMethodManager.showSoftInput(findOnPageEditText, 0);
998 Intent shareIntent = new Intent();
999 shareIntent.setAction(Intent.ACTION_SEND);
1000 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
1001 shareIntent.setType("text/plain");
1002 startActivity(Intent.createChooser(shareIntent, "Share URL"));
1005 case R.id.addToHomescreen:
1006 // Show the `CreateHomeScreenShortcut` `AlertDialog` and name this instance `R.string.create_shortcut`.
1007 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcut();
1008 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.create_shortcut));
1010 //Everything else will be handled by `CreateHomeScreenShortcut` and the associated listener below.
1014 // Get a `PrintManager` instance.
1015 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1017 // Convert `mainWebView` to `printDocumentAdapter`.
1018 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
1020 // Print the document. The print attributes are `null`.
1021 printManager.print(getResources().getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1025 mainWebView.reload();
1029 // Don't consume the event.
1030 return super.onOptionsItemSelected(menuItem);
1034 // removeAllCookies is deprecated, but it is required for API < 21.
1035 @SuppressWarnings("deprecation")
1037 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1038 int menuItemId = menuItem.getItemId();
1040 switch (menuItemId) {
1042 mainWebView.loadUrl(homepage, customHeaders);
1046 if (mainWebView.canGoBack()) {
1047 mainWebView.goBack();
1052 if (mainWebView.canGoForward()) {
1053 mainWebView.goForward();
1058 // Gte the `WebBackForwardList`.
1059 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
1061 // Show the `UrlHistory` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
1062 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistory.loadBackForwardList(this, webBackForwardList);
1063 urlHistoryDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.history));
1066 case R.id.bookmarks:
1067 // Launch Bookmarks.
1068 Intent bookmarksIntent = new Intent(this, Bookmarks.class);
1069 startActivity(bookmarksIntent);
1072 case R.id.downloads:
1073 // Launch the system Download Manager.
1074 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1076 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1077 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1079 startActivity(downloadManagerIntent);
1083 // Launch `Settings`.
1084 Intent settingsIntent = new Intent(this, Settings.class);
1085 startActivity(settingsIntent);
1090 Intent guideIntent = new Intent(this, Guide.class);
1091 startActivity(guideIntent);
1096 Intent aboutIntent = new Intent(this, About.class);
1097 startActivity(aboutIntent);
1100 case R.id.clearAndExit:
1101 // Clear cookies. The commands changed slightly in API 21.
1102 if (Build.VERSION.SDK_INT >= 21) {
1103 cookieManager.removeAllCookies(null);
1105 cookieManager.removeAllCookie();
1108 // Clear DOM storage.
1109 WebStorage domStorage = WebStorage.getInstance();
1110 domStorage.deleteAllData();
1113 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1114 webViewDatabase.clearFormData();
1116 // Clear cache. The argument of "true" includes disk files.
1117 mainWebView.clearCache(true);
1119 // Clear the back/forward history.
1120 mainWebView.clearHistory();
1122 // Clear any SSL certificate preferences.
1123 mainWebView.clearSslPreferences();
1125 // Clear `formattedUrlString`.
1126 formattedUrlString = null;
1128 // Clear `customHeaders`.
1129 customHeaders.clear();
1131 // Detach all views from `mainWebViewRelativeLayout`.
1132 RelativeLayout mainWebViewRelativeLayout = (RelativeLayout) findViewById(R.id.mainWebViewRelativeLayout);
1133 mainWebViewRelativeLayout.removeAllViews();
1135 // Destroy the internal state of `mainWebView`.
1136 mainWebView.destroy();
1138 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
1139 if (Build.VERSION.SDK_INT >= 21) {
1140 finishAndRemoveTask();
1145 // Remove the terminated program from RAM. The status code is `0`.
1153 // Close the navigation drawer.
1154 drawerLayout.closeDrawer(GravityCompat.START);
1159 public void onPostCreate(Bundle savedInstanceState) {
1160 super.onPostCreate(savedInstanceState);
1162 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
1163 drawerToggle.syncState();
1167 public void onConfigurationChanged(Configuration newConfig) {
1168 super.onConfigurationChanged(newConfig);
1170 // Reload the ad for the free flavor if we are not in full screen mode.
1171 if (BuildConfig.FLAVOR.contentEquals("free") && adView.isShown() && !fullScreenVideoFrameLayout.isShown()) {
1173 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1175 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1176 adView = findViewById(R.id.adView);
1179 // `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
1180 // ActivityCompat.invalidateOptionsMenu(this);
1184 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
1185 // Store the `HitTestResult`.
1186 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
1189 final String imageUrl;
1190 final String linkUrl;
1192 // Get a handle for the `ClipboardManager`.
1193 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
1195 switch (hitTestResult.getType()) {
1196 // `SRC_ANCHOR_TYPE` is a link.
1197 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1198 // Get the target URL.
1199 linkUrl = hitTestResult.getExtra();
1201 // Set the target URL as the title of the `ContextMenu`.
1202 menu.setHeaderTitle(linkUrl);
1204 // Add a `Load URL` entry.
1205 menu.add(R.string.load_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1207 public boolean onMenuItemClick(MenuItem item) {
1208 mainWebView.loadUrl(linkUrl, customHeaders);
1213 // Add a `Copy URL` entry.
1214 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1216 public boolean onMenuItemClick(MenuItem item) {
1217 // Save the link URL in a `ClipData`.
1218 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), linkUrl);
1220 // Set the `ClipData` as the clipboard's primary clip.
1221 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
1226 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1227 menu.add(R.string.cancel);
1230 case WebView.HitTestResult.EMAIL_TYPE:
1231 // Get the target URL.
1232 linkUrl = hitTestResult.getExtra();
1234 // Set the target URL as the title of the `ContextMenu`.
1235 menu.setHeaderTitle(linkUrl);
1237 // Add a `Write Email` entry.
1238 menu.add(R.string.write_email).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1240 public boolean onMenuItemClick(MenuItem item) {
1241 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1242 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1244 // Parse the url and set it as the data for the `Intent`.
1245 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
1247 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
1248 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1251 startActivity(emailIntent);
1256 // Add a `Copy Email Address` entry.
1257 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1259 public boolean onMenuItemClick(MenuItem item) {
1260 // Save the email address in a `ClipData`.
1261 ClipData srcEmailTypeClipData = ClipData.newPlainText(getResources().getString(R.string.email_address), linkUrl);
1263 // Set the `ClipData` as the clipboard's primary clip.
1264 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
1269 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1270 menu.add(R.string.cancel);
1273 // `IMAGE_TYPE` is an image.
1274 case WebView.HitTestResult.IMAGE_TYPE:
1275 // Get the image URL.
1276 imageUrl = hitTestResult.getExtra();
1278 // Set the image URL as the title of the `ContextMenu`.
1279 menu.setHeaderTitle(imageUrl);
1281 // Add a `View Image` entry.
1282 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1284 public boolean onMenuItemClick(MenuItem item) {
1285 mainWebView.loadUrl(imageUrl, customHeaders);
1290 // Add a `Download Image` entry.
1291 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1293 public boolean onMenuItemClick(MenuItem item) {
1294 // Show the `DownloadImage` `AlertDialog` and name this instance `@string/download`.
1295 AppCompatDialogFragment downloadImageDialogFragment = DownloadImage.imageUrl(imageUrl);
1296 downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1301 // Add a `Copy URL` entry.
1302 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1304 public boolean onMenuItemClick(MenuItem item) {
1305 // Save the image URL in a `ClipData`.
1306 ClipData srcImageTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1308 // Set the `ClipData` as the clipboard's primary clip.
1309 clipboardManager.setPrimaryClip(srcImageTypeClipData);
1314 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1315 menu.add(R.string.cancel);
1319 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
1320 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1321 // Get the image URL.
1322 imageUrl = hitTestResult.getExtra();
1324 // Set the image URL as the title of the `ContextMenu`.
1325 menu.setHeaderTitle(imageUrl);
1327 // Add a `View Image` entry.
1328 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1330 public boolean onMenuItemClick(MenuItem item) {
1331 mainWebView.loadUrl(imageUrl, customHeaders);
1336 // Add a `Download Image` entry.
1337 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1339 public boolean onMenuItemClick(MenuItem item) {
1340 // Show the `DownloadImage` `AlertDialog` and name this instance `@string/download`.
1341 AppCompatDialogFragment downloadImageDialogFragment = DownloadImage.imageUrl(imageUrl);
1342 downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1347 // Add a `Copy URL` entry.
1348 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1350 public boolean onMenuItemClick(MenuItem item) {
1351 // Save the image URL in a `ClipData`.
1352 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1354 // Set the `ClipData` as the clipboard's primary clip.
1355 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
1360 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1361 menu.add(R.string.cancel);
1367 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
1368 // Get shortcutNameEditText from the alert dialog.
1369 EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
1371 // Create the bookmark shortcut based on formattedUrlString.
1372 Intent bookmarkShortcut = new Intent();
1373 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
1374 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
1376 // Place the bookmark shortcut on the home screen.
1377 Intent placeBookmarkShortcut = new Intent();
1378 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
1379 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
1380 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
1381 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
1382 sendBroadcast(placeBookmarkShortcut);
1386 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
1387 // Get a handle for the system `DOWNLOAD_SERVICE`.
1388 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
1390 // Parse `imageUrl`.
1391 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
1393 // Get the file name from `dialogFragment`.
1394 EditText downloadImageNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_image_name);
1395 String imageName = downloadImageNameEditText.getText().toString();
1397 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
1398 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `imageName`.
1399 downloadRequest.setDestinationInExternalFilesDir(this, "/", imageName);
1400 } else { // Only set the title using `imageName`.
1401 downloadRequest.setTitle(imageName);
1404 // Allow `MediaScanner` to index the download if it is a media file.
1405 downloadRequest.allowScanningByMediaScanner();
1407 // Add the URL as the description for the download.
1408 downloadRequest.setDescription(imageUrl);
1410 // Show the download notification after the download is completed.
1411 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
1413 // Initiate the download.
1414 downloadManager.enqueue(downloadRequest);
1418 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
1419 // Get a handle for the system `DOWNLOAD_SERVICE`.
1420 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
1422 // Parse `downloadUrl`.
1423 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
1425 // Get the file name from `dialogFragment`.
1426 EditText downloadFileNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_file_name);
1427 String fileName = downloadFileNameEditText.getText().toString();
1429 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
1430 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `fileName`.
1431 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
1432 } else { // Only set the title using `fileName`.
1433 downloadRequest.setTitle(fileName);
1436 // Allow `MediaScanner` to index the download if it is a media file.
1437 downloadRequest.allowScanningByMediaScanner();
1439 // Add the URL as the description for the download.
1440 downloadRequest.setDescription(downloadUrl);
1442 // Show the download notification after the download is completed.
1443 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
1445 // Initiate the download.
1446 downloadManager.enqueue(downloadRequest);
1449 public void viewSslCertificate(View view) {
1450 // Show the `ViewSslCertificate` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
1451 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificate();
1452 viewSslCertificateDialogFragment.show(getFragmentManager(), getResources().getString(R.string.view_ssl_certificate));
1456 public void onSslErrorCancel() {
1457 sslErrorHandler.cancel();
1461 public void onSslErrorProceed() {
1462 sslErrorHandler.proceed();
1466 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
1467 // Load the history entry.
1468 mainWebView.goBackOrForward(moveBackOrForwardSteps);
1472 public void onClearHistory() {
1473 // Clear the history.
1474 mainWebView.clearHistory();
1477 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
1479 public void onBackPressed() {
1480 // Close the navigation drawer if it is available. GravityCompat.START is the drawer on the left on Left-to-Right layout text.
1481 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1482 drawerLayout.closeDrawer(GravityCompat.START);
1484 // Load the previous URL if available.
1485 if (mainWebView.canGoBack()) {
1486 mainWebView.goBack();
1488 // Pass `onBackPressed()` to the system.
1489 super.onBackPressed();
1495 public void onPause() {
1496 // Pause `mainWebView`.
1497 mainWebView.onPause();
1499 // Stop all JavaScript.
1500 mainWebView.pauseTimers();
1502 // Pause the adView or it will continue to consume resources in the background on the free flavor.
1503 if (BuildConfig.FLAVOR.contentEquals("free")) {
1504 BannerAd.pauseAd(adView);
1511 public void onResume() {
1514 // Resume JavaScript (if enabled).
1515 mainWebView.resumeTimers();
1517 // Resume `mainWebView`.
1518 mainWebView.onResume();
1520 // Resume the adView for the free flavor.
1521 if (BuildConfig.FLAVOR.contentEquals("free")) {
1522 BannerAd.resumeAd(adView);
1527 public void onRestart() {
1530 // Apply the settings from shared preferences, which might have been changed in `Settings`.
1533 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1534 updatePrivacyIcons(true);
1538 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
1539 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
1540 String unformattedUrlString = urlTextBox.getText().toString().trim();
1542 URL unformattedUrl = null;
1543 Uri.Builder formattedUri = new Uri.Builder();
1545 // Check to see if unformattedUrlString is a valid URL. Otherwise, convert it into a Duck Duck Go search.
1546 if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
1547 // Add http:// at the beginning if it is missing. Otherwise the app will segfault.
1548 if (!unformattedUrlString.startsWith("http")) {
1549 unformattedUrlString = "http://" + unformattedUrlString;
1552 // 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.
1554 unformattedUrl = new URL(unformattedUrlString);
1555 } catch (MalformedURLException e) {
1556 e.printStackTrace();
1559 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
1560 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
1561 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
1562 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
1563 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
1564 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
1566 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
1567 formattedUrlString = formattedUri.build().toString();
1569 // Sanitize the search input and convert it to a DuckDuckGo search.
1570 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
1572 // Use the correct search URL.
1573 if (javaScriptEnabled) { // JavaScript is enabled.
1574 formattedUrlString = javaScriptEnabledSearchURL + encodedUrlString;
1575 } else { // JavaScript is disabled.
1576 formattedUrlString = javaScriptDisabledSearchURL + encodedUrlString;
1580 mainWebView.loadUrl(formattedUrlString, customHeaders);
1582 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
1583 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1586 public void findPreviousOnPage(View view) {
1587 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
1588 mainWebView.findNext(false);
1591 public void findNextOnPage(View view) {
1592 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
1593 mainWebView.findNext(true);
1596 public void closeFindOnPage(View view) {
1597 // Delete the contents of `find_on_page_edittext`.
1598 findOnPageEditText.setText(null);
1600 // Clear the highlighted phrases.
1601 mainWebView.clearMatches();
1603 // Hide the Find on Page `RelativeLayout`.
1604 LinearLayout findOnPageLinearLayout = (LinearLayout) findViewById(R.id.find_on_page_linearlayout);
1605 findOnPageLinearLayout.setVisibility(View.GONE);
1607 // Show the URL app bar.
1608 Toolbar appBarToolbar = (Toolbar) findViewById(R.id.app_bar);
1609 appBarToolbar.setVisibility(View.VISIBLE);
1611 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
1612 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1615 private void applySettings() {
1616 // Get the shared preference values. `this` references the current context.
1617 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1619 // Store the values from `sharedPreferences` in variables.
1620 String userAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
1621 String customUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
1622 String javaScriptDisabledSearchString = sharedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=");
1623 String javaScriptDisabledCustomSearchString = sharedPreferences.getString("javascript_disabled_search_custom_url", "");
1624 String javaScriptEnabledSearchString = sharedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=");
1625 String javaScriptEnabledCustomSearchString = sharedPreferences.getString("javascript_enabled_search_custom_url", "");
1626 String homepageString = sharedPreferences.getString("homepage", "https://www.duckduckgo.com");
1627 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
1628 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh_enabled", false);
1629 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", true);
1630 boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
1631 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
1632 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
1634 // Because they can be modified on-the-fly by the user, these default settings are only applied when the program first runs.
1635 if (javaScriptEnabled == null) { // If `javaScriptEnabled` is null the program is just starting.
1636 // Get the values from `sharedPreferences`.
1637 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
1638 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
1639 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
1640 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
1641 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
1643 // Apply the default settings.
1644 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1645 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1646 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1647 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1648 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
1650 // Set third-party cookies status if API >= 21.
1651 if (Build.VERSION.SDK_INT >= 21) {
1652 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1656 // Apply the other settings from `sharedPreferences`.
1657 homepage = homepageString;
1658 swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
1660 // Set the user agent initial status.
1661 switch (userAgentString) {
1662 case "Default user agent":
1663 // Set the user agent to `""`, which uses the default value.
1664 mainWebView.getSettings().setUserAgentString("");
1667 case "Custom user agent":
1668 // Set the custom user agent.
1669 mainWebView.getSettings().setUserAgentString(customUserAgentString);
1673 // Use the selected user agent.
1674 mainWebView.getSettings().setUserAgentString(userAgentString);
1678 // Set JavaScript disabled search.
1679 if (javaScriptDisabledSearchString.equals("Custom URL")) { // Get the custom URL string.
1680 javaScriptDisabledSearchURL = javaScriptDisabledCustomSearchString;
1681 } else { // Use the string from the pre-built list.
1682 javaScriptDisabledSearchURL = javaScriptDisabledSearchString;
1685 // Set JavaScript enabled search.
1686 if (javaScriptEnabledSearchString.equals("Custom URL")) { // Get the custom URL string.
1687 javaScriptEnabledSearchURL = javaScriptEnabledCustomSearchString;
1688 } else { // Use the string from the pre-built list.
1689 javaScriptEnabledSearchURL = javaScriptEnabledSearchString;
1692 // Set Do Not Track status.
1693 if (doNotTrackEnabled) {
1694 customHeaders.put("DNT", "1");
1696 customHeaders.remove("DNT");
1699 // Set Orbot proxy status.
1700 if (proxyThroughOrbot) {
1701 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
1702 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
1703 } else { // Reset the proxy to default. The host is `""` and the port is `"0"`.
1704 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
1707 // If we are in full screen mode update the `SYSTEM_UI` flags.
1708 if (!appBar.isShowing()) {
1709 if (hideSystemBarsOnFullscreen) { // Hide everything.
1710 // Remove the translucent navigation setting if it is currently flagged.
1711 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1713 // Remove the translucent status bar overlay.
1714 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1716 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1717 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1719 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1720 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1721 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
1723 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1724 } else { // Hide everything except the status and navigation bars.
1725 // Add the translucent status flag if it is unset.
1726 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1728 if (translucentNavigationBarOnFullscreen) {
1729 // Set the navigation bar to be translucent.
1730 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1732 // Set the navigation bar to be black.
1733 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1739 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
1740 // Get handles for the icons.
1741 MenuItem privacyIcon = mainMenu.findItem(R.id.toggleJavaScript);
1742 MenuItem firstPartyCookiesIcon = mainMenu.findItem(R.id.toggleFirstPartyCookies);
1743 MenuItem domStorageIcon = mainMenu.findItem(R.id.toggleDomStorage);
1744 MenuItem formDataIcon = mainMenu.findItem(R.id.toggleSaveFormData);
1746 // Update `privacyIcon`.
1747 if (javaScriptEnabled) { // JavaScript is enabled.
1748 privacyIcon.setIcon(R.drawable.javascript_enabled);
1749 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
1750 privacyIcon.setIcon(R.drawable.warning);
1751 } else { // All the dangerous features are disabled.
1752 privacyIcon.setIcon(R.drawable.privacy_mode);
1755 // Update `firstPartyCookiesIcon`.
1756 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1757 firstPartyCookiesIcon.setIcon(R.drawable.cookies_enabled);
1758 } else { // First-party cookies are disabled.
1759 firstPartyCookiesIcon.setIcon(R.drawable.cookies_disabled);
1762 // Update `domStorageIcon`.
1763 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
1764 domStorageIcon.setIcon(R.drawable.dom_storage_enabled);
1765 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
1766 domStorageIcon.setIcon(R.drawable.dom_storage_disabled);
1767 } else { // JavaScript is disabled, so DOM storage is ghosted.
1768 domStorageIcon.setIcon(R.drawable.dom_storage_ghosted);
1771 // Update `formDataIcon`.
1772 if (saveFormDataEnabled) { // Form data is enabled.
1773 formDataIcon.setIcon(R.drawable.form_data_enabled);
1774 } else { // Form data is disabled.
1775 formDataIcon.setIcon(R.drawable.form_data_disabled);
1778 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`. `this` references the current activity.
1779 if (runInvalidateOptionsMenu) {
1780 ActivityCompat.invalidateOptionsMenu(this);