2 * Copyright 2015-2017 Soren Stoutner <soren@stoutner.com>.
4 * Download cookie code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
6 * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
8 * Privacy Browser is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
13 * Privacy Browser is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with Privacy Browser. If not, see <http://www.gnu.org/licenses/>.
22 package com.stoutner.privacybrowser.activities;
24 import android.annotation.SuppressLint;
25 import android.app.DialogFragment;
26 import android.app.DownloadManager;
27 import android.content.BroadcastReceiver;
28 import android.content.ClipData;
29 import android.content.ClipboardManager;
30 import android.content.Context;
31 import android.content.Intent;
32 import android.content.IntentFilter;
33 import android.content.SharedPreferences;
34 import android.content.res.Configuration;
35 import android.database.Cursor;
36 import android.graphics.Bitmap;
37 import android.graphics.drawable.BitmapDrawable;
38 import android.graphics.drawable.Drawable;
39 import android.net.Uri;
40 import android.net.http.SslCertificate;
41 import android.net.http.SslError;
42 import android.os.Build;
43 import android.os.Bundle;
44 import android.preference.PreferenceManager;
45 import android.print.PrintDocumentAdapter;
46 import android.print.PrintManager;
47 import android.support.annotation.NonNull;
48 import android.support.design.widget.CoordinatorLayout;
49 import android.support.design.widget.NavigationView;
50 import android.support.design.widget.Snackbar;
51 import android.support.v4.app.ActivityCompat;
52 import android.support.v4.content.ContextCompat;
53 import android.support.v4.view.GravityCompat;
54 import android.support.v4.widget.DrawerLayout;
55 import android.support.v4.widget.SwipeRefreshLayout;
56 import android.support.v7.app.ActionBar;
57 import android.support.v7.app.ActionBarDrawerToggle;
58 import android.support.v7.app.AppCompatActivity;
59 import android.support.v7.app.AppCompatDialogFragment;
60 import android.support.v7.widget.Toolbar;
61 import android.text.Editable;
62 import android.text.TextWatcher;
63 import android.util.Patterns;
64 import android.view.ContextMenu;
65 import android.view.GestureDetector;
66 import android.view.KeyEvent;
67 import android.view.Menu;
68 import android.view.MenuItem;
69 import android.view.MotionEvent;
70 import android.view.View;
71 import android.view.WindowManager;
72 import android.view.inputmethod.InputMethodManager;
73 import android.webkit.CookieManager;
74 import android.webkit.DownloadListener;
75 import android.webkit.SslErrorHandler;
76 import android.webkit.WebBackForwardList;
77 import android.webkit.WebChromeClient;
78 import android.webkit.WebResourceResponse;
79 import android.webkit.WebStorage;
80 import android.webkit.WebView;
81 import android.webkit.WebViewClient;
82 import android.webkit.WebViewDatabase;
83 import android.widget.EditText;
84 import android.widget.FrameLayout;
85 import android.widget.ImageView;
86 import android.widget.LinearLayout;
87 import android.widget.ProgressBar;
88 import android.widget.RelativeLayout;
89 import android.widget.TextView;
91 import com.stoutner.privacybrowser.BannerAd;
92 import com.stoutner.privacybrowser.BuildConfig;
93 import com.stoutner.privacybrowser.R;
94 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
95 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
96 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
97 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
98 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
99 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
100 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
101 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
103 import java.io.BufferedReader;
104 import java.io.ByteArrayInputStream;
105 import java.io.IOException;
106 import java.io.InputStreamReader;
107 import java.io.UnsupportedEncodingException;
108 import java.net.MalformedURLException;
110 import java.net.URLDecoder;
111 import java.net.URLEncoder;
112 import java.util.HashMap;
113 import java.util.HashSet;
114 import java.util.Map;
115 import java.util.Set;
117 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
118 public class MainWebViewActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, CreateHomeScreenShortcutDialog.CreateHomeScreenSchortcutListener,
119 SslCertificateErrorDialog.SslCertificateErrorListener, DownloadFileDialog.DownloadFileListener, DownloadImageDialog.DownloadImageListener, UrlHistoryDialog.UrlHistoryListener {
121 // `appBar` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applyAppSettings()`.
122 public static ActionBar appBar;
124 // `favoriteIconBitmap` is public static so it can be accessed from `CreateHomeScreenShortcutDialog`, `BookmarksActivity`, `CreateBookmarkDialog`, `CreateBookmarkFolderDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`, `ViewSslCertificateDialog`.
125 // It is also used in `onCreate()`, `onCreateHomeScreenShortcutCreate()`, and `applyDomainSettings`.
126 public static Bitmap favoriteIconBitmap;
128 // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`, `CreateBookmarkDialog`, and `AddDomainDialog`.
129 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
130 public static String formattedUrlString;
132 // `sslCertificate` is public static so it can be accessed from `ViewSslCertificateDialog`. It is also used in `onCreate()`.
133 public static SslCertificate sslCertificate;
135 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`.
136 public static String orbotStatus;
138 // `webViewTitle` is public static so it can be accessed from `CreateBookmarkDialog` and `CreateHomeScreenShortcutDialog`. It is also used in `onCreate()`.
139 public static String webViewTitle;
142 // `navigatingHistory` is used in `onCreate()`, `onNavigationItemSelected()`, and `applyDomainSettings()`.
143 private boolean navigatingHistory;
145 // `favoriteIconDefaultBitmap` is used in `onCreate()` and `applyDomainSettings`.
146 private Bitmap favoriteIconDefaultBitmap;
148 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, and `onBackPressed()`.
149 private DrawerLayout drawerLayout;
151 // `rootCoordinatorLayout` is used in `onCreate()` and `applyAppSettings()`.
152 private CoordinatorLayout rootCoordinatorLayout;
154 // 'mainWebView' is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`, `findNextOnPage()`, `closeFindOnPage()`, and `loadUrlFromTextBox()`.
155 private WebView mainWebView;
157 // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
158 private FrameLayout fullScreenVideoFrameLayout;
160 // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu`, and `onRestart()`.
161 private SwipeRefreshLayout swipeRefreshLayout;
163 // `urlAppBarRelativeLayout` is used in `onCreate()` and `applyDomainSettings()`.
164 private RelativeLayout urlAppBarRelativeLayout;
166 // `favoriteIconImageView` is used in `onCreate()` and `applyDomainSettings()`
167 private ImageView favoriteIconImageView;
169 // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `loadUrlFromTextBox()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
170 private CookieManager cookieManager;
172 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
173 private final Map<String, String> customHeaders = new HashMap<>();
175 // `javaScriptEnabled` is also used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `applyAppSettings()`.
176 // It is `Boolean` instead of `boolean` because `applyAppSettings()` needs to know if it is `null`.
177 private Boolean javaScriptEnabled;
179 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applyAppSettings()`.
180 private boolean firstPartyCookiesEnabled;
182 // `thirdPartyCookiesEnabled` used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
183 private boolean thirdPartyCookiesEnabled;
185 // `domStorageEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
186 private boolean domStorageEnabled;
188 // `saveFormDataEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
189 private boolean saveFormDataEnabled;
191 // `swipeToRefreshEnabled` is used in `onPrepareOptionsMenu()` and `applyAppSettings()`.
192 private boolean swipeToRefreshEnabled;
194 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applyAppSettings()`.
195 private String homepage;
197 // `javaScriptDisabledSearchURL` is used in `loadURLFromTextBox()` and `applyAppSettings()`.
198 private String javaScriptDisabledSearchURL;
200 // `javaScriptEnabledSearchURL` is used in `loadURLFromTextBox()` and `applyAppSettings()`.
201 private String javaScriptEnabledSearchURL;
203 // `adBlockerEnabled` is used in `onCreate()` and `applyAppSettings()`.
204 private boolean adBlockerEnabled;
206 // `privacyBrowserRuntime` is used in `onCreate()` and `applyAppSettings()`.
207 Runtime privacyBrowserRuntime;
209 // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
210 private boolean incognitoModeEnabled;
212 // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
213 private boolean fullScreenBrowsingModeEnabled;
215 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
216 private boolean inFullScreenBrowsingMode;
218 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
219 private boolean hideSystemBarsOnFullscreen;
221 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
222 private boolean translucentNavigationBarOnFullscreen;
224 // `currentDomainName` is used in `onCreate(), `onNavigationItemSelected()`, and `applyDomainSettings()`.
225 private String currentDomainName;
227 // `waitingForOrbot` is used in `onCreate()` and `applyAppSettings()`.
228 private boolean waitingForOrbot;
230 // `waitingForOrbotData` is used in `onCreate()` and `applyAppSettings()`.
231 private String waitingForOrbotHTMLString;
233 // `privateDataDirectoryString` is used in `onCreate()` and `onNavigationItemSelected()`.
234 private String privateDataDirectoryString;
236 // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
237 private LinearLayout findOnPageLinearLayout;
239 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
240 private EditText findOnPageEditText;
242 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
243 private Menu mainMenu;
245 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
246 private ActionBarDrawerToggle drawerToggle;
248 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
249 private Toolbar supportAppBar;
251 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `loadUrl()`.
252 private EditText urlTextBox;
254 // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
257 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
258 private SslErrorHandler sslErrorHandler;
260 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
261 private InputMethodManager inputMethodManager;
263 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
264 private RelativeLayout mainWebViewRelativeLayout;
267 // 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.
268 @SuppressLint("SetJavaScriptEnabled")
269 protected void onCreate(Bundle savedInstanceState) {
270 super.onCreate(savedInstanceState);
271 setContentView(R.layout.main_drawerlayout);
273 // Get a handle for `inputMethodManager`.
274 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
276 // We need to use the `SupportActionBar` from `android.support.v7.app.ActionBar` until the minimum API is >= 21.
277 supportAppBar = (Toolbar) findViewById(R.id.app_bar);
278 setSupportActionBar(supportAppBar);
279 appBar = getSupportActionBar();
281 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
282 assert appBar != null;
284 // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
285 appBar.setCustomView(R.layout.url_app_bar);
286 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
288 // Set the "go" button on the keyboard to load the URL in urlTextBox.
289 urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.url_edittext);
290 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
292 public boolean onKey(View v, int keyCode, KeyEvent event) {
293 // If the event is a key-down event on the `enter` button, load the URL.
294 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
295 // Load the URL into the mainWebView and consume the event.
297 loadUrlFromTextBox();
298 } catch (UnsupportedEncodingException e) {
301 // If the enter key was pressed, consume the event.
304 // If any other key was pressed, do not consume the event.
310 // Set `waitingForOrbotHTMLString`.
311 waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
313 // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
314 currentDomainName = "";
315 orbotStatus = "unknown";
316 waitingForOrbot = false;
318 // Create an Orbot status `BroadcastReceiver`.
319 BroadcastReceiver orbotStatusBroadcastReceiver = new BroadcastReceiver() {
321 public void onReceive(Context context, Intent intent) {
322 // Store the content of the status message in `orbotStatus`.
323 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
325 // If we are waiting on Orbot, load the website now that Orbot is connected.
326 if (orbotStatus.equals("ON") && waitingForOrbot) {
327 // Reset `waitingForOrbot`.
328 waitingForOrbot = false;
330 // Load `formattedUrlString
331 loadUrl(formattedUrlString);
336 // Register `orbotStatusBroadcastReceiver` on `this` context.
337 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
339 // Get handles for views that need to be accessed.
340 drawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout);
341 rootCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.root_coordinatorlayout);
342 mainWebViewRelativeLayout = (RelativeLayout) findViewById(R.id.main_webview_relativelayout);
343 mainWebView = (WebView) findViewById(R.id.main_webview);
344 findOnPageLinearLayout = (LinearLayout) findViewById(R.id.find_on_page_linearlayout);
345 findOnPageEditText = (EditText) findViewById(R.id.find_on_page_edittext);
346 fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.full_screen_video_framelayout);
347 urlAppBarRelativeLayout = (RelativeLayout) findViewById(R.id.url_app_bar_relativelayout);
348 favoriteIconImageView = (ImageView) findViewById(R.id.favorite_icon);
350 // Create a double-tap listener to toggle full-screen mode.
351 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
352 // Override `onDoubleTap()`. All other events are handled using the default settings.
354 public boolean onDoubleTap(MotionEvent event) {
355 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
356 // Toggle `inFullScreenBrowsingMode`.
357 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
359 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
360 // Hide the `appBar`.
363 // Hide the `BannerAd` in the free flavor.
364 if (BuildConfig.FLAVOR.contentEquals("free")) {
365 BannerAd.hideAd(adView);
368 // Modify the system bars.
369 if (hideSystemBarsOnFullscreen) { // Hide everything.
370 // Remove the translucent overlays.
371 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
373 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
374 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
376 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
377 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
378 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
380 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
382 // Set `rootCoordinatorLayout` to fill the whole screen.
383 rootCoordinatorLayout.setFitsSystemWindows(false);
384 } else { // Hide everything except the status and navigation bars.
385 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
386 rootCoordinatorLayout.setFitsSystemWindows(false);
388 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.
389 // Set the navigation bar to be translucent.
390 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
393 } else { // Switch to normal viewing mode.
394 // Show the `appBar`.
397 // Show the `BannerAd` in the free flavor.
398 if (BuildConfig.FLAVOR.contentEquals("free")) {
399 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
400 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
402 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
403 adView = findViewById(R.id.adview);
406 // Remove the translucent navigation bar flag if it is set.
407 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
409 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
410 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
412 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
413 rootCoordinatorLayout.setSystemUiVisibility(0);
415 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
416 rootCoordinatorLayout.setFitsSystemWindows(true);
419 // Consume the double-tap.
421 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
427 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
428 mainWebView.setOnTouchListener(new View.OnTouchListener() {
430 public boolean onTouch(View v, MotionEvent event) {
431 // Send the `event` to `gestureDetector`.
432 return gestureDetector.onTouchEvent(event);
436 // Update `findOnPageCountTextView`.
437 mainWebView.setFindListener(new WebView.FindListener() {
438 // Get a handle for `findOnPageCountTextView`.
439 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
442 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
443 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
444 // Set `findOnPageCountTextView` to `0/0`.
445 findOnPageCountTextView.setText(R.string.zero_of_zero);
446 } else if (isDoneCounting) { // There are matches.
447 // `activeMatchOrdinal` is zero-based.
448 int activeMatch = activeMatchOrdinal + 1;
450 // Set `findOnPageCountTextView`.
451 findOnPageCountTextView.setText(activeMatch + "/" + numberOfMatches);
456 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
457 findOnPageEditText.addTextChangedListener(new TextWatcher() {
459 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
464 public void onTextChanged(CharSequence s, int start, int before, int count) {
469 public void afterTextChanged(Editable s) {
470 // Search for the text in `mainWebView`.
471 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
475 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
476 findOnPageEditText.setOnKeyListener(new View.OnKeyListener() {
478 public boolean onKey(View v, int keyCode, KeyEvent event) {
479 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
480 // Hide the soft keyboard. `0` indicates no additional flags.
481 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
483 // Consume the event.
485 } else { // A different key was pressed.
486 // Do not consume the event.
492 // Implement swipe to refresh
493 swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refreshlayout);
494 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
495 swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
497 public void onRefresh() {
498 mainWebView.reload();
502 // `DrawerTitle` identifies the `DrawerLayout` in accessibility mode.
503 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
505 // Listen for touches on the navigation menu.
506 final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationview);
507 navigationView.setNavigationItemSelectedListener(this);
509 // 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.
510 final Menu navigationMenu = navigationView.getMenu();
511 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
512 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
513 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
515 // The `DrawerListener` allows us to update the Navigation Menu.
516 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
518 public void onDrawerSlide(View drawerView, float slideOffset) {
522 public void onDrawerOpened(View drawerView) {
526 public void onDrawerClosed(View drawerView) {
530 public void onDrawerStateChanged(int newState) {
531 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // The drawer is opening or closing.
532 // Update the `Back`, `Forward`, and `History` menu items.
533 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
534 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
535 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
537 // Hide the keyboard so we can see the navigation menu. `0` indicates no additional flags.
538 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
543 // drawerToggle creates the hamburger icon at the start of the AppBar.
544 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
546 // Initialize `adServerSet`.
547 final Set<String> adServersSet = new HashSet<>();
549 // Load the list of ad servers into memory.
551 // Load `pgl.yoyo.org_adservers.txt` into a `BufferedReader`.
552 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(getAssets().open("pgl.yoyo.org_adservers.txt")));
554 // Create a string for storing each ad server.
557 // Populate `adServersSet`.
558 while ((adServer = bufferedReader.readLine()) != null) {
559 adServersSet.add(adServer);
562 // Close `bufferedReader`.
563 bufferedReader.close();
564 } catch (IOException ioException) {
565 // We're pretty sure the asset exists, so we don't need to worry about the `IOException` ever being thrown.
568 mainWebView.setWebViewClient(new WebViewClient() {
569 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
570 // We have to use the deprecated `shouldOverrideUrlLoading` until API >= 24.
571 @SuppressWarnings("deprecation")
573 public boolean shouldOverrideUrlLoading(WebView view, String url) {
574 // Use an external email program if the link begins with `mailto:`.
575 if (url.startsWith("mailto:")) {
576 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
577 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
579 // Parse the url and set it as the data for the `Intent`.
580 emailIntent.setData(Uri.parse(url));
582 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
583 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
586 startActivity(emailIntent);
588 } else { // Load the URL in Privacy Browser.
594 // Block ads. We have to use the deprecated `shouldInterceptRequest` until minimum API >= 21.
595 @SuppressWarnings("deprecation")
597 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
598 if (adBlockerEnabled) { // Block ads.
599 // Extract the host from `url`.
600 Uri requestUri = Uri.parse(url);
601 String requestHost = requestUri.getHost();
603 // Initialize a variable to track if this is an ad server.
604 boolean requestHostIsAdServer = false;
606 // Check all the subdomains of `requestHost` if it is not `null` against the ad server database.
607 if (requestHost != null) {
608 while (requestHost.contains(".") && !requestHostIsAdServer) { // Stop checking if we run out of `.` or if we already know that `requestHostIsAdServer` is `true`.
609 if (adServersSet.contains(requestHost)) {
610 requestHostIsAdServer = true;
613 // Strip out the lowest subdomain of `requestHost`.
614 requestHost = requestHost.substring(requestHost.indexOf(".") + 1);
618 if (requestHostIsAdServer) { // It is an ad server.
619 // Return an empty `WebResourceResponse`.
620 return new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
621 } else { // It is not an ad server.
622 // `return null` loads the requested resource.
625 } else { // Ad blocking is disabled.
626 // `return null` loads the requested resource.
631 // Update the URL in urlTextBox when the page starts to load.
633 public void onPageStarted(WebView view, String url, Bitmap favicon) {
634 // Reset `webViewTitle`
635 webViewTitle = getString(R.string.no_title);
637 // Check to see if we are waiting on Orbot.
638 if (!waitingForOrbot) { // We are not waiting on Orbot, so we need to process the URL.
639 // 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.
640 formattedUrlString = url;
642 // Display the loading URL is the URL text box.
643 urlTextBox.setText(url);
645 // Apply any custom domain settings if the URL was loaded by navigating history.
646 if (navigatingHistory) {
647 applyDomainSettings(url);
652 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
654 public void onPageFinished(WebView view, String url) {
655 // Clear the cache and history if Incognito Mode is enabled.
656 if (incognitoModeEnabled) {
657 // Clear the cache. `true` includes disk files.
658 mainWebView.clearCache(true);
660 // Clear the back/forward history.
661 mainWebView.clearHistory();
663 // Manually delete cache folders.
665 // Delete the main `cache` folder.
666 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
668 // Delete the `app_webview` folder, which contains an additional `WebView` cache. See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
669 privacyBrowserRuntime.exec("rm -rf " + privacyBrowserRuntime + "/app_webview");
670 } catch (IOException e) {
671 // Do nothing if an error is thrown.
675 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
676 if (!waitingForOrbot) {
677 // Check to see if `WebView` has set `url` to be `about:blank`.
678 if (url.equals("about:blank")) { // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
679 // Set `formattedUrlString` to `""`.
680 formattedUrlString = "";
682 // Update `urlTextBox`.
683 urlTextBox.setText(formattedUrlString);
685 // Request focus for `urlTextBox`.
686 urlTextBox.requestFocus();
688 // Display the keyboard.
689 inputMethodManager.showSoftInput(urlTextBox, 0);
691 // Apply the domain settings.
692 applyDomainSettings(formattedUrlString);
693 } else { // `WebView` has loaded a webpage.
694 // Set `formattedUrlString`.
695 formattedUrlString = url;
697 // Only update `urlTextBox` if the user is not typing in it.
698 if (!urlTextBox.hasFocus()) {
699 urlTextBox.setText(formattedUrlString);
703 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog`.
704 sslCertificate = mainWebView.getCertificate();
708 // Handle SSL Certificate errors.
710 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
711 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
712 sslErrorHandler = handler;
714 // Display the SSL error `AlertDialog`.
715 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
716 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.ssl_certificate_error));
720 // Get a handle for the progress bar.
721 final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress_bar);
723 mainWebView.setWebChromeClient(new WebChromeClient() {
724 // Update the progress bar when a page is loading.
726 public void onProgressChanged(WebView view, int progress) {
727 progressBar.setProgress(progress);
728 if (progress < 100) {
729 progressBar.setVisibility(View.VISIBLE);
731 progressBar.setVisibility(View.GONE);
733 //Stop the `SwipeToRefresh` indicator if it is running
734 swipeRefreshLayout.setRefreshing(false);
738 // Set the favorite icon when it changes.
740 public void onReceivedIcon(WebView view, Bitmap icon) {
741 // Only update the favorite icon if the website has finished loading.
742 if (progressBar.getVisibility() == View.GONE) {
743 // Save a copy of the favorite icon.
744 favoriteIconBitmap = icon;
746 // Place the favorite icon in the appBar.
747 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
751 // Save a copy of the title when it changes.
753 public void onReceivedTitle(WebView view, String title) {
754 // Save a copy of the title.
755 webViewTitle = title;
758 // Enter full screen video
760 public void onShowCustomView(View view, CustomViewCallback callback) {
761 // Pause the ad if this is the free flavor.
762 if (BuildConfig.FLAVOR.contentEquals("free")) {
763 BannerAd.pauseAd(adView);
766 // Remove the translucent overlays.
767 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
769 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
770 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
772 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
773 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
774 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
776 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
778 // Set `rootCoordinatorLayout` to fill the entire screen.
779 rootCoordinatorLayout.setFitsSystemWindows(false);
781 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
782 fullScreenVideoFrameLayout.addView(view);
783 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
786 // Exit full screen video
787 public void onHideCustomView() {
788 // Hide `fullScreenVideoFrameLayout`.
789 fullScreenVideoFrameLayout.removeAllViews();
790 fullScreenVideoFrameLayout.setVisibility(View.GONE);
792 // Add the translucent status flag. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
793 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
795 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars. This also clears the `SYSTEM_UI` flags.
796 rootCoordinatorLayout.setFitsSystemWindows(true);
798 // Show the ad if this is the free flavor.
799 if (BuildConfig.FLAVOR.contentEquals("free")) {
800 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
801 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
803 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
804 adView = findViewById(R.id.adview);
809 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
810 registerForContextMenu(mainWebView);
812 // Allow the downloading of files.
813 mainWebView.setDownloadListener(new DownloadListener() {
815 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
816 // Show the `DownloadFileDialog` `AlertDialog` and name this instance `@string/download`.
817 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
818 downloadFileDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
822 // Allow pinch to zoom.
823 mainWebView.getSettings().setBuiltInZoomControls(true);
825 // Hide zoom controls.
826 mainWebView.getSettings().setDisplayZoomControls(false);
828 // Initialize cookieManager.
829 cookieManager = CookieManager.getInstance();
831 // 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).
832 customHeaders.put("X-Requested-With", "");
834 // 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.
835 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
837 // Get the intent that started the app.
838 final Intent launchingIntent = getIntent();
840 // Extract the launching intent data as `launchingIntentUriData`.
841 final Uri launchingIntentUriData = launchingIntent.getData();
843 // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
844 if (launchingIntentUriData != null) {
845 formattedUrlString = launchingIntentUriData.toString();
848 // Get a handle for the `Runtime`.
849 privacyBrowserRuntime = Runtime.getRuntime();
851 // Store the application's private data directory.
852 privateDataDirectoryString = getApplicationInfo().dataDir; // `dataDir` will vary, but will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
854 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
855 inFullScreenBrowsingMode = false;
857 // Initialize AdView for the free flavor.
858 adView = findViewById(R.id.adview);
860 // Initialize the privacy settings variables.
861 javaScriptEnabled = false;
862 firstPartyCookiesEnabled = false;
863 thirdPartyCookiesEnabled = false;
864 domStorageEnabled = false;
865 saveFormDataEnabled = false;
867 // Initialize `webViewTitle`.
868 webViewTitle = getString(R.string.no_title);
870 // Initialize `favoriteIconBitmap`. We have to use `ContextCompat` until API >= 21.
871 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
872 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
873 favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
875 // If the favorite icon is null, load the default.
876 if (favoriteIconBitmap == null) {
877 favoriteIconBitmap = favoriteIconDefaultBitmap;
880 // Apply the app settings from the shared preferences.
883 // Load `formattedUrlString` if we are not waiting for Orbot to connect.
884 if (!waitingForOrbot) {
885 loadUrl(formattedUrlString);
891 protected void onNewIntent(Intent intent) {
892 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
895 if (intent.getData() != null) {
896 // Get the intent data and convert it to a string.
897 final Uri intentUriData = intent.getData();
898 formattedUrlString = intentUriData.toString();
901 // Close the navigation drawer if it is open.
902 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
903 drawerLayout.closeDrawer(GravityCompat.START);
907 loadUrl(formattedUrlString);
909 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
910 mainWebView.requestFocus();
914 public boolean onCreateOptionsMenu(Menu menu) {
915 // Inflate the menu; this adds items to the action bar if it is present.
916 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
918 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
921 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
922 updatePrivacyIcons(false);
924 // Get handles for the menu items.
925 MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
926 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
927 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
928 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
930 // Only display third-party cookies if SDK >= 21
931 toggleThirdPartyCookies.setVisible(Build.VERSION.SDK_INT >= 21);
933 // Get the shared preference values. `this` references the current context.
934 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
936 // Set the status of the additional app bar icons. The default is `false`.
937 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
938 toggleFirstPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
939 toggleDomStorage.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
940 toggleSaveFormData.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
941 } else { //Do not display the additional icons.
942 toggleFirstPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
943 toggleDomStorage.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
944 toggleSaveFormData.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
951 public boolean onPrepareOptionsMenu(Menu menu) {
952 // Get handles for the menu items.
953 MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
954 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
955 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
956 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
957 MenuItem clearCookies = menu.findItem(R.id.clearCookies);
958 MenuItem clearFormData = menu.findItem(R.id.clearFormData);
959 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
961 // Set the status of the menu item checkboxes.
962 toggleFirstPartyCookies.setChecked(firstPartyCookiesEnabled);
963 toggleThirdPartyCookies.setChecked(thirdPartyCookiesEnabled);
964 toggleDomStorage.setChecked(domStorageEnabled);
965 toggleSaveFormData.setChecked(saveFormDataEnabled);
967 // Enable third-party cookies if first-party cookies are enabled.
968 toggleThirdPartyCookies.setEnabled(firstPartyCookiesEnabled);
970 // Enable DOM Storage if JavaScript is enabled.
971 toggleDomStorage.setEnabled(javaScriptEnabled);
973 // Enable Clear Cookies if there are any.
974 clearCookies.setEnabled(cookieManager.hasCookies());
976 // Enable Clear Form Data is there is any.
977 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
978 clearFormData.setEnabled(mainWebViewDatabase.hasFormData());
980 // Only show `Refresh` if `swipeToRefresh` is disabled.
981 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
983 // Initialize font size variables.
984 int fontSize = mainWebView.getSettings().getTextZoom();
985 String fontSizeTitle;
986 MenuItem selectedFontSizeMenuItem;
988 // Prepare the font size title and current size menu item.
991 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.fifty_percent);
992 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeFiftyPercent);
996 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.seventy_five_percent);
997 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeSeventyFivePercent);
1001 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
1002 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
1006 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_twenty_five_percent);
1007 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredTwentyFivePercent);
1011 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_fifty_percent);
1012 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredFiftyPercent);
1016 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_seventy_five_percent);
1017 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredSeventyFivePercent);
1021 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.two_hundred_percent);
1022 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeTwoHundredPercent);
1026 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
1027 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
1031 // Set the font size title and select the current size menu item.
1032 MenuItem fontSizeMenuItem = menu.findItem(R.id.fontSize);
1033 fontSizeMenuItem.setTitle(fontSizeTitle);
1034 selectedFontSizeMenuItem.setChecked(true);
1036 // Run all the other default commands.
1037 super.onPrepareOptionsMenu(menu);
1039 // `return true` displays the menu.
1044 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1045 @SuppressLint("SetJavaScriptEnabled")
1046 // removeAllCookies is deprecated, but it is required for API < 21.
1047 @SuppressWarnings("deprecation")
1048 public boolean onOptionsItemSelected(MenuItem menuItem) {
1049 int menuItemId = menuItem.getItemId();
1051 // Set the commands that relate to the menu entries.
1052 switch (menuItemId) {
1053 case R.id.toggleJavaScript:
1054 // Switch the status of javaScriptEnabled.
1055 javaScriptEnabled = !javaScriptEnabled;
1057 // Apply the new JavaScript status.
1058 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1060 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1061 updatePrivacyIcons(true);
1063 // Display a `Snackbar`.
1064 if (javaScriptEnabled) { // JavaScrip is enabled.
1065 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1066 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
1067 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1068 } else { // Privacy mode.
1069 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1072 // Reload the WebView.
1073 mainWebView.reload();
1076 case R.id.toggleFirstPartyCookies:
1077 // Switch the status of firstPartyCookiesEnabled.
1078 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1080 // Update the menu checkbox.
1081 menuItem.setChecked(firstPartyCookiesEnabled);
1083 // Apply the new cookie status.
1084 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1086 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1087 updatePrivacyIcons(true);
1089 // Display a `Snackbar`.
1090 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1091 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1092 } else if (javaScriptEnabled){ // JavaScript is still enabled.
1093 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1094 } else { // Privacy mode.
1095 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1098 // Reload the WebView.
1099 mainWebView.reload();
1102 case R.id.toggleThirdPartyCookies:
1103 if (Build.VERSION.SDK_INT >= 21) {
1104 // Switch the status of thirdPartyCookiesEnabled.
1105 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1107 // Update the menu checkbox.
1108 menuItem.setChecked(thirdPartyCookiesEnabled);
1110 // Apply the new cookie status.
1111 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1113 // Display a `Snackbar`.
1114 if (thirdPartyCookiesEnabled) {
1115 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1117 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1120 // Reload the WebView.
1121 mainWebView.reload();
1122 } // Else do nothing because SDK < 21.
1125 case R.id.toggleDomStorage:
1126 // Switch the status of domStorageEnabled.
1127 domStorageEnabled = !domStorageEnabled;
1129 // Update the menu checkbox.
1130 menuItem.setChecked(domStorageEnabled);
1132 // Apply the new DOM Storage status.
1133 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1135 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1136 updatePrivacyIcons(true);
1138 // Display a `Snackbar`.
1139 if (domStorageEnabled) {
1140 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1142 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1145 // Reload the WebView.
1146 mainWebView.reload();
1149 case R.id.toggleSaveFormData:
1150 // Switch the status of saveFormDataEnabled.
1151 saveFormDataEnabled = !saveFormDataEnabled;
1153 // Update the menu checkbox.
1154 menuItem.setChecked(saveFormDataEnabled);
1156 // Apply the new form data status.
1157 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1159 // Display a `Snackbar`.
1160 if (saveFormDataEnabled) {
1161 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1163 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1166 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1167 updatePrivacyIcons(true);
1169 // Reload the WebView.
1170 mainWebView.reload();
1173 case R.id.clearCookies:
1174 if (Build.VERSION.SDK_INT < 21) {
1175 cookieManager.removeAllCookie();
1177 cookieManager.removeAllCookies(null);
1179 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_SHORT).show();
1182 case R.id.clearDomStorage:
1183 WebStorage webStorage = WebStorage.getInstance();
1184 webStorage.deleteAllData();
1185 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_SHORT).show();
1188 case R.id.clearFormData:
1189 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1190 mainWebViewDatabase.clearFormData();
1191 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_SHORT).show();
1194 case R.id.fontSizeFiftyPercent:
1195 mainWebView.getSettings().setTextZoom(50);
1198 case R.id.fontSizeSeventyFivePercent:
1199 mainWebView.getSettings().setTextZoom(75);
1202 case R.id.fontSizeOneHundredPercent:
1203 mainWebView.getSettings().setTextZoom(100);
1206 case R.id.fontSizeOneHundredTwentyFivePercent:
1207 mainWebView.getSettings().setTextZoom(125);
1210 case R.id.fontSizeOneHundredFiftyPercent:
1211 mainWebView.getSettings().setTextZoom(150);
1214 case R.id.fontSizeOneHundredSeventyFivePercent:
1215 mainWebView.getSettings().setTextZoom(175);
1218 case R.id.fontSizeTwoHundredPercent:
1219 mainWebView.getSettings().setTextZoom(200);
1223 Intent shareIntent = new Intent();
1224 shareIntent.setAction(Intent.ACTION_SEND);
1225 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
1226 shareIntent.setType("text/plain");
1227 startActivity(Intent.createChooser(shareIntent, "Share URL"));
1230 case R.id.find_on_page:
1231 // Hide the URL app bar.
1232 supportAppBar.setVisibility(View.GONE);
1234 // Show the Find on Page `RelativeLayout`.
1235 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1237 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android.
1238 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1239 findOnPageEditText.postDelayed(new Runnable()
1244 // Set the focus on `findOnPageEditText`.
1245 findOnPageEditText.requestFocus();
1247 // Display the keyboard.
1248 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1254 mainWebView.reload();
1258 // Get a `PrintManager` instance.
1259 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1261 // Convert `mainWebView` to `printDocumentAdapter`.
1262 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
1264 // Print the document. The print attributes are `null`.
1265 printManager.print(getResources().getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1268 case R.id.addToHomescreen:
1269 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
1270 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
1271 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.create_shortcut));
1273 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
1277 // Don't consume the event.
1278 return super.onOptionsItemSelected(menuItem);
1282 // removeAllCookies is deprecated, but it is required for API < 21.
1283 @SuppressWarnings("deprecation")
1285 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1286 int menuItemId = menuItem.getItemId();
1288 switch (menuItemId) {
1294 if (mainWebView.canGoBack()) {
1295 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1296 navigatingHistory = true;
1298 // Load the previous website in the history.
1299 mainWebView.goBack();
1304 if (mainWebView.canGoForward()) {
1305 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1306 navigatingHistory = true;
1308 // Load the next website in the history.
1309 mainWebView.goForward();
1314 // Get the `WebBackForwardList`.
1315 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
1317 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
1318 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
1319 urlHistoryDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.history));
1322 case R.id.bookmarks:
1323 // Launch BookmarksActivity.
1324 Intent bookmarksIntent = new Intent(this, BookmarksActivity.class);
1325 startActivity(bookmarksIntent);
1328 case R.id.downloads:
1329 // Launch the system Download Manager.
1330 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1332 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1333 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1335 startActivity(downloadManagerIntent);
1339 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1340 currentDomainName = "";
1342 // Launch `SettingsActivity`.
1343 Intent settingsIntent = new Intent(this, SettingsActivity.class);
1344 startActivity(settingsIntent);
1348 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1349 currentDomainName = "";
1351 // Launch `DomainsActivity`.
1352 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1353 startActivity(domainsIntent);
1357 // Launch `GuideActivity`.
1358 Intent guideIntent = new Intent(this, GuideActivity.class);
1359 startActivity(guideIntent);
1363 // Launch `AboutActivity`.
1364 Intent aboutIntent = new Intent(this, AboutActivity.class);
1365 startActivity(aboutIntent);
1368 case R.id.clearAndExit:
1369 // Clear cookies. The commands changed slightly in API 21.
1370 if (Build.VERSION.SDK_INT >= 21) {
1371 cookieManager.removeAllCookies(null);
1373 cookieManager.removeAllCookie();
1376 // Clear DOM storage.
1377 WebStorage domStorage = WebStorage.getInstance();
1378 domStorage.deleteAllData();
1381 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1382 webViewDatabase.clearFormData();
1384 // Clear the cache. `true` includes disk files.
1385 mainWebView.clearCache(true);
1387 // Clear the back/forward history.
1388 mainWebView.clearHistory();
1390 // Clear any SSL certificate preferences.
1391 mainWebView.clearSslPreferences();
1393 // Clear `formattedUrlString`.
1394 formattedUrlString = null;
1396 // Clear `customHeaders`.
1397 customHeaders.clear();
1399 // Detach all views from `mainWebViewRelativeLayout`.
1400 mainWebViewRelativeLayout.removeAllViews();
1402 // Destroy the internal state of `mainWebView`.
1403 mainWebView.destroy();
1405 // Manually delete cache folders.
1407 // Delete the main `cache` folder.
1408 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1410 // Delete the `app_webview` folder, which contains an additional `WebView` cache. See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
1411 privacyBrowserRuntime.exec("rm -rf " + privacyBrowserRuntime + "/app_webview");
1412 } catch (IOException e) {
1413 // Do nothing if an error is thrown.
1416 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
1417 if (Build.VERSION.SDK_INT >= 21) {
1418 finishAndRemoveTask();
1423 // Remove the terminated program from RAM. The status code is `0`.
1431 // Close the navigation drawer.
1432 drawerLayout.closeDrawer(GravityCompat.START);
1437 public void onPostCreate(Bundle savedInstanceState) {
1438 super.onPostCreate(savedInstanceState);
1440 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
1441 drawerToggle.syncState();
1445 public void onConfigurationChanged(Configuration newConfig) {
1446 super.onConfigurationChanged(newConfig);
1448 // Reload the ad for the free flavor if we are not in full screen mode.
1449 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
1451 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1453 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1454 adView = findViewById(R.id.adview);
1457 // `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
1458 // ActivityCompat.invalidateOptionsMenu(this);
1462 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
1463 // Store the `HitTestResult`.
1464 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
1467 final String imageUrl;
1468 final String linkUrl;
1470 // Get a handle for the `ClipboardManager`.
1471 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
1473 switch (hitTestResult.getType()) {
1474 // `SRC_ANCHOR_TYPE` is a link.
1475 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1476 // Get the target URL.
1477 linkUrl = hitTestResult.getExtra();
1479 // Set the target URL as the title of the `ContextMenu`.
1480 menu.setHeaderTitle(linkUrl);
1482 // Add a `Load URL` entry.
1483 menu.add(R.string.load_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1485 public boolean onMenuItemClick(MenuItem item) {
1491 // Add a `Copy URL` entry.
1492 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1494 public boolean onMenuItemClick(MenuItem item) {
1495 // Save the link URL in a `ClipData`.
1496 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), linkUrl);
1498 // Set the `ClipData` as the clipboard's primary clip.
1499 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
1504 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1505 menu.add(R.string.cancel);
1508 case WebView.HitTestResult.EMAIL_TYPE:
1509 // Get the target URL.
1510 linkUrl = hitTestResult.getExtra();
1512 // Set the target URL as the title of the `ContextMenu`.
1513 menu.setHeaderTitle(linkUrl);
1515 // Add a `Write Email` entry.
1516 menu.add(R.string.write_email).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1518 public boolean onMenuItemClick(MenuItem item) {
1519 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1520 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1522 // Parse the url and set it as the data for the `Intent`.
1523 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
1525 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
1526 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1529 startActivity(emailIntent);
1534 // Add a `Copy Email Address` entry.
1535 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1537 public boolean onMenuItemClick(MenuItem item) {
1538 // Save the email address in a `ClipData`.
1539 ClipData srcEmailTypeClipData = ClipData.newPlainText(getResources().getString(R.string.email_address), linkUrl);
1541 // Set the `ClipData` as the clipboard's primary clip.
1542 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
1547 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1548 menu.add(R.string.cancel);
1551 // `IMAGE_TYPE` is an image.
1552 case WebView.HitTestResult.IMAGE_TYPE:
1553 // Get the image URL.
1554 imageUrl = hitTestResult.getExtra();
1556 // Set the image URL as the title of the `ContextMenu`.
1557 menu.setHeaderTitle(imageUrl);
1559 // Add a `View Image` entry.
1560 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1562 public boolean onMenuItemClick(MenuItem item) {
1568 // Add a `Download Image` entry.
1569 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1571 public boolean onMenuItemClick(MenuItem item) {
1572 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
1573 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
1574 downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1579 // Add a `Copy URL` entry.
1580 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1582 public boolean onMenuItemClick(MenuItem item) {
1583 // Save the image URL in a `ClipData`.
1584 ClipData srcImageTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1586 // Set the `ClipData` as the clipboard's primary clip.
1587 clipboardManager.setPrimaryClip(srcImageTypeClipData);
1592 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1593 menu.add(R.string.cancel);
1597 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
1598 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1599 // Get the image URL.
1600 imageUrl = hitTestResult.getExtra();
1602 // Set the image URL as the title of the `ContextMenu`.
1603 menu.setHeaderTitle(imageUrl);
1605 // Add a `View Image` entry.
1606 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1608 public boolean onMenuItemClick(MenuItem item) {
1614 // Add a `Download Image` entry.
1615 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1617 public boolean onMenuItemClick(MenuItem item) {
1618 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
1619 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
1620 downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1625 // Add a `Copy URL` entry.
1626 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1628 public boolean onMenuItemClick(MenuItem item) {
1629 // Save the image URL in a `ClipData`.
1630 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1632 // Set the `ClipData` as the clipboard's primary clip.
1633 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
1638 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1639 menu.add(R.string.cancel);
1645 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
1646 // Get shortcutNameEditText from the alert dialog.
1647 EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
1649 // Create the bookmark shortcut based on formattedUrlString.
1650 Intent bookmarkShortcut = new Intent();
1651 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
1652 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
1654 // Place the bookmark shortcut on the home screen.
1655 Intent placeBookmarkShortcut = new Intent();
1656 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
1657 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
1658 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIconBitmap);
1659 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
1660 sendBroadcast(placeBookmarkShortcut);
1664 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
1665 // Download the image if it has an HTTP or HTTPS URI.
1666 if (imageUrl.startsWith("http")) {
1667 // Get a handle for the system `DOWNLOAD_SERVICE`.
1668 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
1670 // Parse `imageUrl`.
1671 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
1673 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
1674 if (firstPartyCookiesEnabled) {
1675 // Get the cookies for `imageUrl`.
1676 String cookies = cookieManager.getCookie(imageUrl);
1678 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
1679 downloadRequest.addRequestHeader("Cookie", cookies);
1682 // Get the file name from `dialogFragment`.
1683 EditText downloadImageNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_image_name);
1684 String imageName = downloadImageNameEditText.getText().toString();
1686 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
1687 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `imageName`.
1688 downloadRequest.setDestinationInExternalFilesDir(this, "/", imageName);
1689 } else { // Only set the title using `imageName`.
1690 downloadRequest.setTitle(imageName);
1693 // Allow `MediaScanner` to index the download if it is a media file.
1694 downloadRequest.allowScanningByMediaScanner();
1696 // Add the URL as the description for the download.
1697 downloadRequest.setDescription(imageUrl);
1699 // Show the download notification after the download is completed.
1700 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
1702 // Initiate the download.
1703 downloadManager.enqueue(downloadRequest);
1704 } else { // The image is not an HTTP or HTTPS URI.
1705 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
1710 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
1711 // Download the file if it has an HTTP or HTTPS URI.
1712 if (downloadUrl.startsWith("http")) {
1714 // Get a handle for the system `DOWNLOAD_SERVICE`.
1715 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
1717 // Parse `downloadUrl`.
1718 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
1720 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
1721 if (firstPartyCookiesEnabled) {
1722 // Get the cookies for `downloadUrl`.
1723 String cookies = cookieManager.getCookie(downloadUrl);
1725 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
1726 downloadRequest.addRequestHeader("Cookie", cookies);
1729 // Get the file name from `dialogFragment`.
1730 EditText downloadFileNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_file_name);
1731 String fileName = downloadFileNameEditText.getText().toString();
1733 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
1734 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download location to `/sdcard/Android/data/com.stoutner.privacybrowser.standard/files` named `fileName`.
1735 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
1736 } else { // Only set the title using `fileName`.
1737 downloadRequest.setTitle(fileName);
1740 // Allow `MediaScanner` to index the download if it is a media file.
1741 downloadRequest.allowScanningByMediaScanner();
1743 // Add the URL as the description for the download.
1744 downloadRequest.setDescription(downloadUrl);
1746 // Show the download notification after the download is completed.
1747 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
1749 // Initiate the download.
1750 downloadManager.enqueue(downloadRequest);
1751 } else { // The download is not an HTTP or HTTPS URI.
1752 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
1756 public void viewSslCertificate(View view) {
1757 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
1758 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
1759 viewSslCertificateDialogFragment.show(getFragmentManager(), getResources().getString(R.string.view_ssl_certificate));
1763 public void onSslErrorCancel() {
1764 sslErrorHandler.cancel();
1768 public void onSslErrorProceed() {
1769 sslErrorHandler.proceed();
1773 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
1774 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1775 navigatingHistory = true;
1777 // Load the history entry.
1778 mainWebView.goBackOrForward(moveBackOrForwardSteps);
1782 public void onClearHistory() {
1783 // Clear the history.
1784 mainWebView.clearHistory();
1787 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
1789 public void onBackPressed() {
1790 // Close the navigation drawer if it is available. GravityCompat.START is the drawer on the left on Left-to-Right layout text.
1791 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1792 drawerLayout.closeDrawer(GravityCompat.START);
1794 // Load the previous URL if available.
1795 if (mainWebView.canGoBack()) {
1796 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1797 navigatingHistory = true;
1800 mainWebView.goBack();
1802 // Pass `onBackPressed()` to the system.
1803 super.onBackPressed();
1809 public void onPause() {
1810 // Pause `mainWebView`.
1811 mainWebView.onPause();
1813 // Stop all JavaScript.
1814 mainWebView.pauseTimers();
1816 // Pause the adView or it will continue to consume resources in the background on the free flavor.
1817 if (BuildConfig.FLAVOR.contentEquals("free")) {
1818 BannerAd.pauseAd(adView);
1825 public void onResume() { // `onResume()` also runs every time the app starts after `onCreate()` and `onStart()`.
1828 // Resume JavaScript (if enabled).
1829 mainWebView.resumeTimers();
1831 // Resume `mainWebView`.
1832 mainWebView.onResume();
1834 // Resume the adView for the free flavor.
1835 if (BuildConfig.FLAVOR.contentEquals("free")) {
1836 BannerAd.resumeAd(adView);
1841 public void onRestart() {
1844 // Apply the settings from shared preferences, which might have been changed in `SettingsActivity`.
1847 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1848 updatePrivacyIcons(true);
1852 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
1853 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
1854 String unformattedUrlString = urlTextBox.getText().toString().trim();
1856 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
1857 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.contains("localhost"))) {
1858 // Add `http://` at the beginning if it is missing. Otherwise the app will segfault.
1859 if (!unformattedUrlString.startsWith("http")) {
1860 unformattedUrlString = "http://" + unformattedUrlString;
1863 // Initialize `unformattedUrl`.
1864 URL unformattedUrl = null;
1866 // 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.
1868 unformattedUrl = new URL(unformattedUrlString);
1869 } catch (MalformedURLException e) {
1870 e.printStackTrace();
1873 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
1874 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
1875 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
1876 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
1877 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
1878 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
1881 Uri.Builder formattedUri = new Uri.Builder();
1882 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
1884 // Decode `formattedUri` as a `String` in `UTF-8`.
1885 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
1887 // Sanitize the search input and convert it to a search.
1888 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
1890 // Use the correct search URL.
1891 if (javaScriptEnabled) { // JavaScript is enabled.
1892 formattedUrlString = javaScriptEnabledSearchURL + encodedUrlString;
1893 } else { // JavaScript is disabled.
1894 formattedUrlString = javaScriptDisabledSearchURL + encodedUrlString;
1898 loadUrl(formattedUrlString);
1900 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
1901 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1905 private void loadUrl(String url) {
1906 // Apply any custom domain settings.
1907 applyDomainSettings(url);
1910 mainWebView.loadUrl(url, customHeaders);
1913 // We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
1914 @SuppressWarnings("deprecation")
1915 private void applyDomainSettings(String url) {
1916 // Reset `navigatingHistory`.
1917 navigatingHistory = false;
1919 // Parse the URL into a URI.
1920 Uri uri = Uri.parse(url);
1922 // Extract the domain from `uri`.
1923 String hostName = uri.getHost();
1925 // Initialize `loadingNewDomainName`.
1926 boolean loadingNewDomainName;
1928 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
1929 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
1930 //noinspection SimplifiableIfStatement
1931 if ((hostName == null) || (currentDomainName == null)) {
1932 loadingNewDomainName = true;
1933 } else { // Determine if `hostName` equals `currentDomainName`.
1934 loadingNewDomainName = !hostName.equals(currentDomainName);
1937 // Only apply the domain settings if we are loading a new domain. This allows the user to set temporary settings for JavaScript, cookies, DOM storage, etc.
1938 if (loadingNewDomainName) {
1939 // Set the new `hostname` as the `currentDomainName`.
1940 currentDomainName = hostName;
1942 // Reset `favoriteIconBitmap` and display it in the `appbar`.
1943 favoriteIconBitmap = favoriteIconDefaultBitmap;
1944 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
1946 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
1947 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1948 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1950 // Get a full cursor from `domainsDatabaseHelper`.
1951 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
1953 // Initialize `domainSettingsSet`.
1954 Set<String> domainSettingsSet = new HashSet<>();
1956 // Get the domain name column index.
1957 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
1959 // Populate `domainSettingsSet`.
1960 for (int i = 0; i < domainNameCursor.getCount(); i++) {
1961 // Move `domainsCursor` to the current row.
1962 domainNameCursor.moveToPosition(i);
1964 // Store the domain name in `domainSettingsSet`.
1965 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
1968 // Close `domainNameCursor.
1969 domainNameCursor.close();
1971 // Initialize variables to track if this domain has stored domain settings, and if so, under which name.
1972 boolean hostHasDomainSettings = false;
1973 String domainNameInDatabase = null;
1975 // Check the hostname.
1976 if (domainSettingsSet.contains(hostName)) {
1977 hostHasDomainSettings = true;
1978 domainNameInDatabase = hostName;
1981 // If `hostName` is not `null`, check all the subdomains of `hostName` against wildcard domains in `domainCursor`.
1982 if (hostName != null) {
1983 while (hostName.contains(".") && !hostHasDomainSettings) { // Stop checking if we run out of `.` or if we already know that `hostHasDomainSettings` is `true`.
1984 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
1985 hostHasDomainSettings = true;
1986 domainNameInDatabase = "*." + hostName;
1989 // Strip out the lowest subdomain of `host`.
1990 hostName = hostName.substring(hostName.indexOf(".") + 1);
1994 if (hostHasDomainSettings) { // The url we are loading has custom domain settings.
1995 // Get a cursor for the current host and move it to the first position.
1996 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
1997 currentHostDomainSettingsCursor.moveToFirst();
1999 // Get the settings from the cursor.
2000 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
2001 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
2002 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
2003 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
2004 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
2005 String userAgentString = (currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT)));
2006 int fontSize = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE)));
2008 // Close `currentHostDomainSettingsCursor`.
2009 currentHostDomainSettingsCursor.close();
2011 // Apply the domain settings.
2012 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2013 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2014 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2015 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2016 mainWebView.getSettings().setTextZoom(fontSize);
2018 // Set third-party cookies status if API >= 21.
2019 if (Build.VERSION.SDK_INT >= 21) {
2020 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2023 // Set the user agent.
2024 if (userAgentString.equals("WebView default user agent")) {
2025 // Set the user agent to `""`, which uses the default value.
2026 mainWebView.getSettings().setUserAgentString("");
2028 // Use the selected user agent.
2029 mainWebView.getSettings().setUserAgentString(userAgentString);
2032 // Set a green background on `urlTextBox` to indicate that custom domain settings are being used. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2033 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_green));
2034 } else { // The URL we are loading does not have custom domain settings. Load the defaults.
2035 // Get the shared preference values. `this` references the current context.
2036 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2038 // Store the values from `sharedPreferences` in variables.
2039 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
2040 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
2041 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
2042 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
2043 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
2044 String userAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
2045 String customUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
2046 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
2048 // Apply the default settings.
2049 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2050 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2051 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2052 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2053 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
2055 // Set third-party cookies status if API >= 21.
2056 if (Build.VERSION.SDK_INT >= 21) {
2057 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2060 // Set the default user agent.
2061 switch (userAgentString) {
2062 case "WebView default user agent":
2063 // Set the user agent to `""`, which uses the default value.
2064 mainWebView.getSettings().setUserAgentString("");
2067 case "Custom user agent":
2068 // Set the custom user agent.
2069 mainWebView.getSettings().setUserAgentString(customUserAgentString);
2073 // Use the selected user agent.
2074 mainWebView.getSettings().setUserAgentString(userAgentString);
2078 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2079 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.url_bar_background_transparent));
2082 // Close `domainsDatabaseHelper`.
2083 domainsDatabaseHelper.close();
2085 // Update the privacy icons, but only if `mainMenu` has already been populated.
2086 if (mainMenu != null) {
2087 updatePrivacyIcons(true);
2092 public void findPreviousOnPage(View view) {
2093 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
2094 mainWebView.findNext(false);
2097 public void findNextOnPage(View view) {
2098 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2099 mainWebView.findNext(true);
2102 public void closeFindOnPage(View view) {
2103 // Delete the contents of `find_on_page_edittext`.
2104 findOnPageEditText.setText(null);
2106 // Clear the highlighted phrases.
2107 mainWebView.clearMatches();
2109 // Hide the Find on Page `RelativeLayout`.
2110 findOnPageLinearLayout.setVisibility(View.GONE);
2112 // Show the URL app bar.
2113 supportAppBar.setVisibility(View.VISIBLE);
2115 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
2116 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2119 private void applyAppSettings() {
2120 // Get the shared preference values. `this` references the current context.
2121 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2123 // Store the values from `sharedPreferences` in variables.
2124 String javaScriptDisabledSearchString = sharedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=");
2125 String javaScriptDisabledSearchCustomURLString = sharedPreferences.getString("javascript_disabled_search_custom_url", "");
2126 String javaScriptEnabledSearchString = sharedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=");
2127 String javaScriptEnabledSearchCustomURLString = sharedPreferences.getString("javascript_enabled_search_custom_url", "");
2128 String homepageString = sharedPreferences.getString("homepage", "https://duckduckgo.com");
2129 String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
2130 String torJavaScriptDisabledSearchString = sharedPreferences.getString("tor_javascript_disabled_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
2131 String torJavaScriptDisabledSearchCustomURLString = sharedPreferences.getString("tor_javascript_disabled_search_custom_url", "");
2132 String torJavaScriptEnabledSearchString = sharedPreferences.getString("tor_javascript_enabled_search", "https://3g2upl4pq6kufc4m.onion/?q=");
2133 String torJavaScriptEnabledSearchCustomURLString = sharedPreferences.getString("tor_javascript_enabled_search_custom_url", "");
2134 adBlockerEnabled = sharedPreferences.getBoolean("block_ads", true);
2135 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
2136 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
2137 boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
2138 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("enable_full_screen_browsing_mode", false);
2139 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
2140 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
2141 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh", false);
2143 // Set the homepage, search, and proxy options.
2144 if (proxyThroughOrbot) { // Set the Tor options.
2145 // Set `torHomepageString` as `homepage`.
2146 homepage = torHomepageString;
2148 // If formattedUrlString is null assign the homepage to it.
2149 if (formattedUrlString == null) {
2150 formattedUrlString = homepage;
2153 // Set JavaScript disabled search.
2154 if (torJavaScriptDisabledSearchString.equals("Custom URL")) { // Get the custom URL string.
2155 javaScriptDisabledSearchURL = torJavaScriptDisabledSearchCustomURLString;
2156 } else { // Use the string from the pre-built list.
2157 javaScriptDisabledSearchURL = torJavaScriptDisabledSearchString;
2160 // Set JavaScript enabled search.
2161 if (torJavaScriptEnabledSearchString.equals("Custom URL")) { // Get the custom URL string.
2162 javaScriptEnabledSearchURL = torJavaScriptEnabledSearchCustomURLString;
2163 } else { // Use the string from the pre-built list.
2164 javaScriptEnabledSearchURL = torJavaScriptEnabledSearchString;
2167 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
2168 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
2170 // Display a message to the user if we are waiting on Orbot.
2171 if (!orbotStatus.equals("ON")) {
2172 // Set `waitingForOrbot`.
2173 waitingForOrbot = true;
2175 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
2176 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
2178 } else { // Set the non-Tor options.
2179 // Set `homepageString` as `homepage`.
2180 homepage = homepageString;
2182 // If formattedUrlString is null assign the homepage to it.
2183 if (formattedUrlString == null) {
2184 formattedUrlString = homepage;
2187 // Set JavaScript disabled search.
2188 if (javaScriptDisabledSearchString.equals("Custom URL")) { // Get the custom URL string.
2189 javaScriptDisabledSearchURL = javaScriptDisabledSearchCustomURLString;
2190 } else { // Use the string from the pre-built list.
2191 javaScriptDisabledSearchURL = javaScriptDisabledSearchString;
2194 // Set JavaScript enabled search.
2195 if (javaScriptEnabledSearchString.equals("Custom URL")) { // Get the custom URL string.
2196 javaScriptEnabledSearchURL = javaScriptEnabledSearchCustomURLString;
2197 } else { // Use the string from the pre-built list.
2198 javaScriptEnabledSearchURL = javaScriptEnabledSearchString;
2201 // Reset the proxy to default. The host is `""` and the port is `"0"`.
2202 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
2204 // Reset `waitingForOrbot.
2205 waitingForOrbot = false;
2208 // Set swipe to refresh.
2209 swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
2211 // Set Do Not Track status.
2212 if (doNotTrackEnabled) {
2213 customHeaders.put("DNT", "1");
2215 customHeaders.remove("DNT");
2218 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
2219 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
2220 if (hideSystemBarsOnFullscreen) { // Hide everything.
2221 // Remove the translucent navigation setting if it is currently flagged.
2222 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2224 // Remove the translucent status bar overlay.
2225 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2227 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
2228 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
2230 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
2231 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
2232 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
2234 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
2235 } else { // Hide everything except the status and navigation bars.
2236 // Add the translucent status flag if it is unset.
2237 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2239 if (translucentNavigationBarOnFullscreen) {
2240 // Set the navigation bar to be translucent.
2241 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2243 // Set the navigation bar to be black.
2244 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2247 } else { // Switch to normal viewing mode.
2248 // Reset `inFullScreenBrowsingMode` to `false`.
2249 inFullScreenBrowsingMode = false;
2251 // Show the `appBar`.
2254 // Show the `BannerAd` in the free flavor.
2255 if (BuildConfig.FLAVOR.contentEquals("free")) {
2256 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
2257 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2259 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2260 adView = findViewById(R.id.adview);
2263 // Remove the translucent navigation bar flag if it is set.
2264 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2266 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
2267 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2269 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
2270 rootCoordinatorLayout.setSystemUiVisibility(0);
2272 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
2273 rootCoordinatorLayout.setFitsSystemWindows(true);
2277 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
2278 // Get handles for the icons.
2279 MenuItem privacyIcon = mainMenu.findItem(R.id.toggleJavaScript);
2280 MenuItem firstPartyCookiesIcon = mainMenu.findItem(R.id.toggleFirstPartyCookies);
2281 MenuItem domStorageIcon = mainMenu.findItem(R.id.toggleDomStorage);
2282 MenuItem formDataIcon = mainMenu.findItem(R.id.toggleSaveFormData);
2284 // Update `privacyIcon`.
2285 if (javaScriptEnabled) { // JavaScript is enabled.
2286 privacyIcon.setIcon(R.drawable.javascript_enabled);
2287 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
2288 privacyIcon.setIcon(R.drawable.warning);
2289 } else { // All the dangerous features are disabled.
2290 privacyIcon.setIcon(R.drawable.privacy_mode);
2293 // Update `firstPartyCookiesIcon`.
2294 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
2295 firstPartyCookiesIcon.setIcon(R.drawable.cookies_enabled);
2296 } else { // First-party cookies are disabled.
2297 firstPartyCookiesIcon.setIcon(R.drawable.cookies_disabled);
2300 // Update `domStorageIcon`.
2301 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
2302 domStorageIcon.setIcon(R.drawable.dom_storage_enabled);
2303 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
2304 domStorageIcon.setIcon(R.drawable.dom_storage_disabled);
2305 } else { // JavaScript is disabled, so DOM storage is ghosted.
2306 domStorageIcon.setIcon(R.drawable.dom_storage_ghosted);
2309 // Update `formDataIcon`.
2310 if (saveFormDataEnabled) { // Form data is enabled.
2311 formDataIcon.setIcon(R.drawable.form_data_enabled);
2312 } else { // Form data is disabled.
2313 formDataIcon.setIcon(R.drawable.form_data_disabled);
2316 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`. `this` references the current activity.
2317 if (runInvalidateOptionsMenu) {
2318 ActivityCompat.invalidateOptionsMenu(this);