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.twenty_five_percent);
992 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeTwentyFivePercent);
996 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.fifty_percent);
997 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeFiftyPercent);
1001 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.seventy_five_percent);
1002 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeSeventyFivePercent);
1006 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
1007 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
1011 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_twenty_five_percent);
1012 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredTwentyFivePercent);
1016 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_fifty_percent);
1017 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredFiftyPercent);
1021 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_seventy_five_percent);
1022 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredSeventyFivePercent);
1026 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.two_hundred_percent);
1027 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeTwoHundredPercent);
1031 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
1032 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
1036 // Set the font size title and select the current size menu item.
1037 MenuItem fontSizeMenuItem = menu.findItem(R.id.fontSize);
1038 fontSizeMenuItem.setTitle(fontSizeTitle);
1039 selectedFontSizeMenuItem.setChecked(true);
1041 // Run all the other default commands.
1042 super.onPrepareOptionsMenu(menu);
1044 // `return true` displays the menu.
1049 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1050 @SuppressLint("SetJavaScriptEnabled")
1051 // removeAllCookies is deprecated, but it is required for API < 21.
1052 @SuppressWarnings("deprecation")
1053 public boolean onOptionsItemSelected(MenuItem menuItem) {
1054 int menuItemId = menuItem.getItemId();
1056 // Set the commands that relate to the menu entries.
1057 switch (menuItemId) {
1058 case R.id.toggleJavaScript:
1059 // Switch the status of javaScriptEnabled.
1060 javaScriptEnabled = !javaScriptEnabled;
1062 // Apply the new JavaScript status.
1063 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1065 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1066 updatePrivacyIcons(true);
1068 // Display a `Snackbar`.
1069 if (javaScriptEnabled) { // JavaScrip is enabled.
1070 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1071 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
1072 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1073 } else { // Privacy mode.
1074 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1077 // Reload the WebView.
1078 mainWebView.reload();
1081 case R.id.toggleFirstPartyCookies:
1082 // Switch the status of firstPartyCookiesEnabled.
1083 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1085 // Update the menu checkbox.
1086 menuItem.setChecked(firstPartyCookiesEnabled);
1088 // Apply the new cookie status.
1089 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1091 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1092 updatePrivacyIcons(true);
1094 // Display a `Snackbar`.
1095 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1096 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1097 } else if (javaScriptEnabled){ // JavaScript is still enabled.
1098 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1099 } else { // Privacy mode.
1100 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1103 // Reload the WebView.
1104 mainWebView.reload();
1107 case R.id.toggleThirdPartyCookies:
1108 if (Build.VERSION.SDK_INT >= 21) {
1109 // Switch the status of thirdPartyCookiesEnabled.
1110 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1112 // Update the menu checkbox.
1113 menuItem.setChecked(thirdPartyCookiesEnabled);
1115 // Apply the new cookie status.
1116 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1118 // Display a `Snackbar`.
1119 if (thirdPartyCookiesEnabled) {
1120 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1122 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1125 // Reload the WebView.
1126 mainWebView.reload();
1127 } // Else do nothing because SDK < 21.
1130 case R.id.toggleDomStorage:
1131 // Switch the status of domStorageEnabled.
1132 domStorageEnabled = !domStorageEnabled;
1134 // Update the menu checkbox.
1135 menuItem.setChecked(domStorageEnabled);
1137 // Apply the new DOM Storage status.
1138 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1140 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1141 updatePrivacyIcons(true);
1143 // Display a `Snackbar`.
1144 if (domStorageEnabled) {
1145 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1147 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1150 // Reload the WebView.
1151 mainWebView.reload();
1154 case R.id.toggleSaveFormData:
1155 // Switch the status of saveFormDataEnabled.
1156 saveFormDataEnabled = !saveFormDataEnabled;
1158 // Update the menu checkbox.
1159 menuItem.setChecked(saveFormDataEnabled);
1161 // Apply the new form data status.
1162 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1164 // Display a `Snackbar`.
1165 if (saveFormDataEnabled) {
1166 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1168 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1171 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1172 updatePrivacyIcons(true);
1174 // Reload the WebView.
1175 mainWebView.reload();
1178 case R.id.clearCookies:
1179 if (Build.VERSION.SDK_INT < 21) {
1180 cookieManager.removeAllCookie();
1182 cookieManager.removeAllCookies(null);
1184 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_SHORT).show();
1187 case R.id.clearDomStorage:
1188 WebStorage webStorage = WebStorage.getInstance();
1189 webStorage.deleteAllData();
1190 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_SHORT).show();
1193 case R.id.clearFormData:
1194 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1195 mainWebViewDatabase.clearFormData();
1196 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_SHORT).show();
1199 case R.id.fontSizeTwentyFivePercent:
1200 mainWebView.getSettings().setTextZoom(25);
1203 case R.id.fontSizeFiftyPercent:
1204 mainWebView.getSettings().setTextZoom(50);
1207 case R.id.fontSizeSeventyFivePercent:
1208 mainWebView.getSettings().setTextZoom(75);
1211 case R.id.fontSizeOneHundredPercent:
1212 mainWebView.getSettings().setTextZoom(100);
1215 case R.id.fontSizeOneHundredTwentyFivePercent:
1216 mainWebView.getSettings().setTextZoom(125);
1219 case R.id.fontSizeOneHundredFiftyPercent:
1220 mainWebView.getSettings().setTextZoom(150);
1223 case R.id.fontSizeOneHundredSeventyFivePercent:
1224 mainWebView.getSettings().setTextZoom(175);
1227 case R.id.fontSizeTwoHundredPercent:
1228 mainWebView.getSettings().setTextZoom(200);
1232 Intent shareIntent = new Intent();
1233 shareIntent.setAction(Intent.ACTION_SEND);
1234 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
1235 shareIntent.setType("text/plain");
1236 startActivity(Intent.createChooser(shareIntent, "Share URL"));
1239 case R.id.find_on_page:
1240 // Hide the URL app bar.
1241 supportAppBar.setVisibility(View.GONE);
1243 // Show the Find on Page `RelativeLayout`.
1244 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1246 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android.
1247 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1248 findOnPageEditText.postDelayed(new Runnable()
1253 // Set the focus on `findOnPageEditText`.
1254 findOnPageEditText.requestFocus();
1256 // Display the keyboard.
1257 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1263 mainWebView.reload();
1267 // Get a `PrintManager` instance.
1268 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1270 // Convert `mainWebView` to `printDocumentAdapter`.
1271 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
1273 // Print the document. The print attributes are `null`.
1274 printManager.print(getResources().getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1277 case R.id.addToHomescreen:
1278 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
1279 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
1280 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.create_shortcut));
1282 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
1286 // Don't consume the event.
1287 return super.onOptionsItemSelected(menuItem);
1291 // removeAllCookies is deprecated, but it is required for API < 21.
1292 @SuppressWarnings("deprecation")
1294 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1295 int menuItemId = menuItem.getItemId();
1297 switch (menuItemId) {
1303 if (mainWebView.canGoBack()) {
1304 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1305 navigatingHistory = true;
1307 // Load the previous website in the history.
1308 mainWebView.goBack();
1313 if (mainWebView.canGoForward()) {
1314 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1315 navigatingHistory = true;
1317 // Load the next website in the history.
1318 mainWebView.goForward();
1323 // Get the `WebBackForwardList`.
1324 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
1326 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
1327 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
1328 urlHistoryDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.history));
1331 case R.id.bookmarks:
1332 // Launch BookmarksActivity.
1333 Intent bookmarksIntent = new Intent(this, BookmarksActivity.class);
1334 startActivity(bookmarksIntent);
1337 case R.id.downloads:
1338 // Launch the system Download Manager.
1339 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1341 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1342 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1344 startActivity(downloadManagerIntent);
1348 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1349 currentDomainName = "";
1351 // Launch `SettingsActivity`.
1352 Intent settingsIntent = new Intent(this, SettingsActivity.class);
1353 startActivity(settingsIntent);
1357 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1358 currentDomainName = "";
1360 // Launch `DomainsActivity`.
1361 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1362 startActivity(domainsIntent);
1366 // Launch `GuideActivity`.
1367 Intent guideIntent = new Intent(this, GuideActivity.class);
1368 startActivity(guideIntent);
1372 // Launch `AboutActivity`.
1373 Intent aboutIntent = new Intent(this, AboutActivity.class);
1374 startActivity(aboutIntent);
1377 case R.id.clearAndExit:
1378 // Clear cookies. The commands changed slightly in API 21.
1379 if (Build.VERSION.SDK_INT >= 21) {
1380 cookieManager.removeAllCookies(null);
1382 cookieManager.removeAllCookie();
1385 // Clear DOM storage.
1386 WebStorage domStorage = WebStorage.getInstance();
1387 domStorage.deleteAllData();
1390 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1391 webViewDatabase.clearFormData();
1393 // Clear the cache. `true` includes disk files.
1394 mainWebView.clearCache(true);
1396 // Clear the back/forward history.
1397 mainWebView.clearHistory();
1399 // Clear any SSL certificate preferences.
1400 mainWebView.clearSslPreferences();
1402 // Clear `formattedUrlString`.
1403 formattedUrlString = null;
1405 // Clear `customHeaders`.
1406 customHeaders.clear();
1408 // Detach all views from `mainWebViewRelativeLayout`.
1409 mainWebViewRelativeLayout.removeAllViews();
1411 // Destroy the internal state of `mainWebView`.
1412 mainWebView.destroy();
1414 // Manually delete cache folders.
1416 // Delete the main `cache` folder.
1417 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1419 // 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`.
1420 privacyBrowserRuntime.exec("rm -rf " + privacyBrowserRuntime + "/app_webview");
1421 } catch (IOException e) {
1422 // Do nothing if an error is thrown.
1425 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
1426 if (Build.VERSION.SDK_INT >= 21) {
1427 finishAndRemoveTask();
1432 // Remove the terminated program from RAM. The status code is `0`.
1440 // Close the navigation drawer.
1441 drawerLayout.closeDrawer(GravityCompat.START);
1446 public void onPostCreate(Bundle savedInstanceState) {
1447 super.onPostCreate(savedInstanceState);
1449 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
1450 drawerToggle.syncState();
1454 public void onConfigurationChanged(Configuration newConfig) {
1455 super.onConfigurationChanged(newConfig);
1457 // Reload the ad for the free flavor if we are not in full screen mode.
1458 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
1460 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1462 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1463 adView = findViewById(R.id.adview);
1466 // `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
1467 // ActivityCompat.invalidateOptionsMenu(this);
1471 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
1472 // Store the `HitTestResult`.
1473 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
1476 final String imageUrl;
1477 final String linkUrl;
1479 // Get a handle for the `ClipboardManager`.
1480 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
1482 switch (hitTestResult.getType()) {
1483 // `SRC_ANCHOR_TYPE` is a link.
1484 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1485 // Get the target URL.
1486 linkUrl = hitTestResult.getExtra();
1488 // Set the target URL as the title of the `ContextMenu`.
1489 menu.setHeaderTitle(linkUrl);
1491 // Add a `Load URL` entry.
1492 menu.add(R.string.load_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1494 public boolean onMenuItemClick(MenuItem item) {
1500 // Add a `Copy URL` entry.
1501 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1503 public boolean onMenuItemClick(MenuItem item) {
1504 // Save the link URL in a `ClipData`.
1505 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), linkUrl);
1507 // Set the `ClipData` as the clipboard's primary clip.
1508 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
1513 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1514 menu.add(R.string.cancel);
1517 case WebView.HitTestResult.EMAIL_TYPE:
1518 // Get the target URL.
1519 linkUrl = hitTestResult.getExtra();
1521 // Set the target URL as the title of the `ContextMenu`.
1522 menu.setHeaderTitle(linkUrl);
1524 // Add a `Write Email` entry.
1525 menu.add(R.string.write_email).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1527 public boolean onMenuItemClick(MenuItem item) {
1528 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1529 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1531 // Parse the url and set it as the data for the `Intent`.
1532 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
1534 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
1535 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1538 startActivity(emailIntent);
1543 // Add a `Copy Email Address` entry.
1544 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1546 public boolean onMenuItemClick(MenuItem item) {
1547 // Save the email address in a `ClipData`.
1548 ClipData srcEmailTypeClipData = ClipData.newPlainText(getResources().getString(R.string.email_address), linkUrl);
1550 // Set the `ClipData` as the clipboard's primary clip.
1551 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
1556 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1557 menu.add(R.string.cancel);
1560 // `IMAGE_TYPE` is an image.
1561 case WebView.HitTestResult.IMAGE_TYPE:
1562 // Get the image URL.
1563 imageUrl = hitTestResult.getExtra();
1565 // Set the image URL as the title of the `ContextMenu`.
1566 menu.setHeaderTitle(imageUrl);
1568 // Add a `View Image` entry.
1569 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1571 public boolean onMenuItemClick(MenuItem item) {
1577 // Add a `Download Image` entry.
1578 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1580 public boolean onMenuItemClick(MenuItem item) {
1581 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
1582 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
1583 downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1588 // Add a `Copy URL` entry.
1589 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1591 public boolean onMenuItemClick(MenuItem item) {
1592 // Save the image URL in a `ClipData`.
1593 ClipData srcImageTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1595 // Set the `ClipData` as the clipboard's primary clip.
1596 clipboardManager.setPrimaryClip(srcImageTypeClipData);
1601 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1602 menu.add(R.string.cancel);
1606 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
1607 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1608 // Get the image URL.
1609 imageUrl = hitTestResult.getExtra();
1611 // Set the image URL as the title of the `ContextMenu`.
1612 menu.setHeaderTitle(imageUrl);
1614 // Add a `View Image` entry.
1615 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1617 public boolean onMenuItemClick(MenuItem item) {
1623 // Add a `Download Image` entry.
1624 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1626 public boolean onMenuItemClick(MenuItem item) {
1627 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
1628 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
1629 downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1634 // Add a `Copy URL` entry.
1635 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1637 public boolean onMenuItemClick(MenuItem item) {
1638 // Save the image URL in a `ClipData`.
1639 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1641 // Set the `ClipData` as the clipboard's primary clip.
1642 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
1647 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1648 menu.add(R.string.cancel);
1654 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
1655 // Get shortcutNameEditText from the alert dialog.
1656 EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
1658 // Create the bookmark shortcut based on formattedUrlString.
1659 Intent bookmarkShortcut = new Intent();
1660 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
1661 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
1663 // Place the bookmark shortcut on the home screen.
1664 Intent placeBookmarkShortcut = new Intent();
1665 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
1666 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
1667 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIconBitmap);
1668 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
1669 sendBroadcast(placeBookmarkShortcut);
1673 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
1674 // Download the image if it has an HTTP or HTTPS URI.
1675 if (imageUrl.startsWith("http")) {
1676 // Get a handle for the system `DOWNLOAD_SERVICE`.
1677 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
1679 // Parse `imageUrl`.
1680 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
1682 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
1683 if (firstPartyCookiesEnabled) {
1684 // Get the cookies for `imageUrl`.
1685 String cookies = cookieManager.getCookie(imageUrl);
1687 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
1688 downloadRequest.addRequestHeader("Cookie", cookies);
1691 // Get the file name from `dialogFragment`.
1692 EditText downloadImageNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_image_name);
1693 String imageName = downloadImageNameEditText.getText().toString();
1695 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
1696 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `imageName`.
1697 downloadRequest.setDestinationInExternalFilesDir(this, "/", imageName);
1698 } else { // Only set the title using `imageName`.
1699 downloadRequest.setTitle(imageName);
1702 // Allow `MediaScanner` to index the download if it is a media file.
1703 downloadRequest.allowScanningByMediaScanner();
1705 // Add the URL as the description for the download.
1706 downloadRequest.setDescription(imageUrl);
1708 // Show the download notification after the download is completed.
1709 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
1711 // Initiate the download.
1712 downloadManager.enqueue(downloadRequest);
1713 } else { // The image is not an HTTP or HTTPS URI.
1714 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
1719 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
1720 // Download the file if it has an HTTP or HTTPS URI.
1721 if (downloadUrl.startsWith("http")) {
1723 // Get a handle for the system `DOWNLOAD_SERVICE`.
1724 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
1726 // Parse `downloadUrl`.
1727 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
1729 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
1730 if (firstPartyCookiesEnabled) {
1731 // Get the cookies for `downloadUrl`.
1732 String cookies = cookieManager.getCookie(downloadUrl);
1734 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
1735 downloadRequest.addRequestHeader("Cookie", cookies);
1738 // Get the file name from `dialogFragment`.
1739 EditText downloadFileNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_file_name);
1740 String fileName = downloadFileNameEditText.getText().toString();
1742 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
1743 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download location to `/sdcard/Android/data/com.stoutner.privacybrowser.standard/files` named `fileName`.
1744 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
1745 } else { // Only set the title using `fileName`.
1746 downloadRequest.setTitle(fileName);
1749 // Allow `MediaScanner` to index the download if it is a media file.
1750 downloadRequest.allowScanningByMediaScanner();
1752 // Add the URL as the description for the download.
1753 downloadRequest.setDescription(downloadUrl);
1755 // Show the download notification after the download is completed.
1756 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
1758 // Initiate the download.
1759 downloadManager.enqueue(downloadRequest);
1760 } else { // The download is not an HTTP or HTTPS URI.
1761 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
1765 public void viewSslCertificate(View view) {
1766 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
1767 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
1768 viewSslCertificateDialogFragment.show(getFragmentManager(), getResources().getString(R.string.view_ssl_certificate));
1772 public void onSslErrorCancel() {
1773 sslErrorHandler.cancel();
1777 public void onSslErrorProceed() {
1778 sslErrorHandler.proceed();
1782 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
1783 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1784 navigatingHistory = true;
1786 // Load the history entry.
1787 mainWebView.goBackOrForward(moveBackOrForwardSteps);
1791 public void onClearHistory() {
1792 // Clear the history.
1793 mainWebView.clearHistory();
1796 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
1798 public void onBackPressed() {
1799 // Close the navigation drawer if it is available. GravityCompat.START is the drawer on the left on Left-to-Right layout text.
1800 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1801 drawerLayout.closeDrawer(GravityCompat.START);
1803 // Load the previous URL if available.
1804 if (mainWebView.canGoBack()) {
1805 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1806 navigatingHistory = true;
1809 mainWebView.goBack();
1811 // Pass `onBackPressed()` to the system.
1812 super.onBackPressed();
1818 public void onPause() {
1819 // Pause `mainWebView`.
1820 mainWebView.onPause();
1822 // Stop all JavaScript.
1823 mainWebView.pauseTimers();
1825 // Pause the adView or it will continue to consume resources in the background on the free flavor.
1826 if (BuildConfig.FLAVOR.contentEquals("free")) {
1827 BannerAd.pauseAd(adView);
1834 public void onResume() { // `onResume()` also runs every time the app starts after `onCreate()` and `onStart()`.
1837 // Resume JavaScript (if enabled).
1838 mainWebView.resumeTimers();
1840 // Resume `mainWebView`.
1841 mainWebView.onResume();
1843 // Resume the adView for the free flavor.
1844 if (BuildConfig.FLAVOR.contentEquals("free")) {
1845 BannerAd.resumeAd(adView);
1850 public void onRestart() {
1853 // Apply the settings from shared preferences, which might have been changed in `SettingsActivity`.
1856 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1857 updatePrivacyIcons(true);
1861 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
1862 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
1863 String unformattedUrlString = urlTextBox.getText().toString().trim();
1865 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
1866 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.contains("localhost"))) {
1867 // Add `http://` at the beginning if it is missing. Otherwise the app will segfault.
1868 if (!unformattedUrlString.startsWith("http")) {
1869 unformattedUrlString = "http://" + unformattedUrlString;
1872 // Initialize `unformattedUrl`.
1873 URL unformattedUrl = null;
1875 // 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.
1877 unformattedUrl = new URL(unformattedUrlString);
1878 } catch (MalformedURLException e) {
1879 e.printStackTrace();
1882 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
1883 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
1884 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
1885 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
1886 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
1887 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
1890 Uri.Builder formattedUri = new Uri.Builder();
1891 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
1893 // Decode `formattedUri` as a `String` in `UTF-8`.
1894 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
1896 // Sanitize the search input and convert it to a search.
1897 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
1899 // Use the correct search URL.
1900 if (javaScriptEnabled) { // JavaScript is enabled.
1901 formattedUrlString = javaScriptEnabledSearchURL + encodedUrlString;
1902 } else { // JavaScript is disabled.
1903 formattedUrlString = javaScriptDisabledSearchURL + encodedUrlString;
1907 loadUrl(formattedUrlString);
1909 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
1910 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1914 private void loadUrl(String url) {
1915 // Apply any custom domain settings.
1916 applyDomainSettings(url);
1919 mainWebView.loadUrl(url, customHeaders);
1922 // We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
1923 @SuppressWarnings("deprecation")
1924 private void applyDomainSettings(String url) {
1925 // Reset `navigatingHistory`.
1926 navigatingHistory = false;
1928 // Parse the URL into a URI.
1929 Uri uri = Uri.parse(url);
1931 // Extract the domain from `uri`.
1932 String hostName = uri.getHost();
1934 // Initialize `loadingNewDomainName`.
1935 boolean loadingNewDomainName;
1937 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
1938 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
1939 //noinspection SimplifiableIfStatement
1940 if ((hostName == null) || (currentDomainName == null)) {
1941 loadingNewDomainName = true;
1942 } else { // Determine if `hostName` equals `currentDomainName`.
1943 loadingNewDomainName = !hostName.equals(currentDomainName);
1946 // 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.
1947 if (loadingNewDomainName) {
1948 // Set the new `hostname` as the `currentDomainName`.
1949 currentDomainName = hostName;
1951 // Reset `favoriteIconBitmap` and display it in the `appbar`.
1952 favoriteIconBitmap = favoriteIconDefaultBitmap;
1953 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
1955 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
1956 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1957 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1959 // Get a full cursor from `domainsDatabaseHelper`.
1960 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
1962 // Initialize `domainSettingsSet`.
1963 Set<String> domainSettingsSet = new HashSet<>();
1965 // Get the domain name column index.
1966 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
1968 // Populate `domainSettingsSet`.
1969 for (int i = 0; i < domainNameCursor.getCount(); i++) {
1970 // Move `domainsCursor` to the current row.
1971 domainNameCursor.moveToPosition(i);
1973 // Store the domain name in `domainSettingsSet`.
1974 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
1977 // Close `domainNameCursor.
1978 domainNameCursor.close();
1980 // Initialize variables to track if this domain has stored domain settings, and if so, under which name.
1981 boolean hostHasDomainSettings = false;
1982 String domainNameInDatabase = null;
1984 // Check the hostname.
1985 if (domainSettingsSet.contains(hostName)) {
1986 hostHasDomainSettings = true;
1987 domainNameInDatabase = hostName;
1990 // If `hostName` is not `null`, check all the subdomains of `hostName` against wildcard domains in `domainCursor`.
1991 if (hostName != null) {
1992 while (hostName.contains(".") && !hostHasDomainSettings) { // Stop checking if we run out of `.` or if we already know that `hostHasDomainSettings` is `true`.
1993 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
1994 hostHasDomainSettings = true;
1995 domainNameInDatabase = "*." + hostName;
1998 // Strip out the lowest subdomain of `host`.
1999 hostName = hostName.substring(hostName.indexOf(".") + 1);
2003 if (hostHasDomainSettings) { // The url we are loading has custom domain settings.
2004 // Get a cursor for the current host and move it to the first position.
2005 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
2006 currentHostDomainSettingsCursor.moveToFirst();
2008 // Get the settings from the cursor.
2009 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
2010 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
2011 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
2012 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
2013 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
2014 String userAgentString = (currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT)));
2015 int fontSize = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE)));
2017 // Close `currentHostDomainSettingsCursor`.
2018 currentHostDomainSettingsCursor.close();
2020 // Apply the domain settings.
2021 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2022 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2023 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2024 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2025 mainWebView.getSettings().setTextZoom(fontSize);
2027 // Set third-party cookies status if API >= 21.
2028 if (Build.VERSION.SDK_INT >= 21) {
2029 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2032 // Set the user agent.
2033 if (userAgentString.equals("WebView default user agent")) {
2034 // Set the user agent to `""`, which uses the default value.
2035 mainWebView.getSettings().setUserAgentString("");
2037 // Use the selected user agent.
2038 mainWebView.getSettings().setUserAgentString(userAgentString);
2041 // 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.
2042 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_green));
2043 } else { // The URL we are loading does not have custom domain settings. Load the defaults.
2044 // Get the shared preference values. `this` references the current context.
2045 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2047 // Store the values from `sharedPreferences` in variables.
2048 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
2049 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
2050 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
2051 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
2052 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
2053 String userAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
2054 String customUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
2055 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
2057 // Apply the default settings.
2058 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2059 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2060 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2061 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2062 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
2064 // Set third-party cookies status if API >= 21.
2065 if (Build.VERSION.SDK_INT >= 21) {
2066 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2069 // Set the default user agent.
2070 switch (userAgentString) {
2071 case "WebView default user agent":
2072 // Set the user agent to `""`, which uses the default value.
2073 mainWebView.getSettings().setUserAgentString("");
2076 case "Custom user agent":
2077 // Set the custom user agent.
2078 mainWebView.getSettings().setUserAgentString(customUserAgentString);
2082 // Use the selected user agent.
2083 mainWebView.getSettings().setUserAgentString(userAgentString);
2087 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2088 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.url_bar_background_transparent));
2091 // Close `domainsDatabaseHelper`.
2092 domainsDatabaseHelper.close();
2094 // Update the privacy icons, but only if `mainMenu` has already been populated.
2095 if (mainMenu != null) {
2096 updatePrivacyIcons(true);
2101 public void findPreviousOnPage(View view) {
2102 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
2103 mainWebView.findNext(false);
2106 public void findNextOnPage(View view) {
2107 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2108 mainWebView.findNext(true);
2111 public void closeFindOnPage(View view) {
2112 // Delete the contents of `find_on_page_edittext`.
2113 findOnPageEditText.setText(null);
2115 // Clear the highlighted phrases.
2116 mainWebView.clearMatches();
2118 // Hide the Find on Page `RelativeLayout`.
2119 findOnPageLinearLayout.setVisibility(View.GONE);
2121 // Show the URL app bar.
2122 supportAppBar.setVisibility(View.VISIBLE);
2124 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
2125 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2128 private void applyAppSettings() {
2129 // Get the shared preference values. `this` references the current context.
2130 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2132 // Store the values from `sharedPreferences` in variables.
2133 String javaScriptDisabledSearchString = sharedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=");
2134 String javaScriptDisabledSearchCustomURLString = sharedPreferences.getString("javascript_disabled_search_custom_url", "");
2135 String javaScriptEnabledSearchString = sharedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=");
2136 String javaScriptEnabledSearchCustomURLString = sharedPreferences.getString("javascript_enabled_search_custom_url", "");
2137 String homepageString = sharedPreferences.getString("homepage", "https://duckduckgo.com");
2138 String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
2139 String torJavaScriptDisabledSearchString = sharedPreferences.getString("tor_javascript_disabled_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
2140 String torJavaScriptDisabledSearchCustomURLString = sharedPreferences.getString("tor_javascript_disabled_search_custom_url", "");
2141 String torJavaScriptEnabledSearchString = sharedPreferences.getString("tor_javascript_enabled_search", "https://3g2upl4pq6kufc4m.onion/?q=");
2142 String torJavaScriptEnabledSearchCustomURLString = sharedPreferences.getString("tor_javascript_enabled_search_custom_url", "");
2143 adBlockerEnabled = sharedPreferences.getBoolean("block_ads", true);
2144 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
2145 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
2146 boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
2147 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("enable_full_screen_browsing_mode", false);
2148 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
2149 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
2150 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh", false);
2152 // Set the homepage, search, and proxy options.
2153 if (proxyThroughOrbot) { // Set the Tor options.
2154 // Set `torHomepageString` as `homepage`.
2155 homepage = torHomepageString;
2157 // If formattedUrlString is null assign the homepage to it.
2158 if (formattedUrlString == null) {
2159 formattedUrlString = homepage;
2162 // Set JavaScript disabled search.
2163 if (torJavaScriptDisabledSearchString.equals("Custom URL")) { // Get the custom URL string.
2164 javaScriptDisabledSearchURL = torJavaScriptDisabledSearchCustomURLString;
2165 } else { // Use the string from the pre-built list.
2166 javaScriptDisabledSearchURL = torJavaScriptDisabledSearchString;
2169 // Set JavaScript enabled search.
2170 if (torJavaScriptEnabledSearchString.equals("Custom URL")) { // Get the custom URL string.
2171 javaScriptEnabledSearchURL = torJavaScriptEnabledSearchCustomURLString;
2172 } else { // Use the string from the pre-built list.
2173 javaScriptEnabledSearchURL = torJavaScriptEnabledSearchString;
2176 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
2177 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
2179 // Display a message to the user if we are waiting on Orbot.
2180 if (!orbotStatus.equals("ON")) {
2181 // Set `waitingForOrbot`.
2182 waitingForOrbot = true;
2184 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
2185 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
2187 } else { // Set the non-Tor options.
2188 // Set `homepageString` as `homepage`.
2189 homepage = homepageString;
2191 // If formattedUrlString is null assign the homepage to it.
2192 if (formattedUrlString == null) {
2193 formattedUrlString = homepage;
2196 // Set JavaScript disabled search.
2197 if (javaScriptDisabledSearchString.equals("Custom URL")) { // Get the custom URL string.
2198 javaScriptDisabledSearchURL = javaScriptDisabledSearchCustomURLString;
2199 } else { // Use the string from the pre-built list.
2200 javaScriptDisabledSearchURL = javaScriptDisabledSearchString;
2203 // Set JavaScript enabled search.
2204 if (javaScriptEnabledSearchString.equals("Custom URL")) { // Get the custom URL string.
2205 javaScriptEnabledSearchURL = javaScriptEnabledSearchCustomURLString;
2206 } else { // Use the string from the pre-built list.
2207 javaScriptEnabledSearchURL = javaScriptEnabledSearchString;
2210 // Reset the proxy to default. The host is `""` and the port is `"0"`.
2211 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
2213 // Reset `waitingForOrbot.
2214 waitingForOrbot = false;
2217 // Set swipe to refresh.
2218 swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
2220 // Set Do Not Track status.
2221 if (doNotTrackEnabled) {
2222 customHeaders.put("DNT", "1");
2224 customHeaders.remove("DNT");
2227 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
2228 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
2229 if (hideSystemBarsOnFullscreen) { // Hide everything.
2230 // Remove the translucent navigation setting if it is currently flagged.
2231 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2233 // Remove the translucent status bar overlay.
2234 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2236 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
2237 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
2239 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
2240 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
2241 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
2243 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
2244 } else { // Hide everything except the status and navigation bars.
2245 // Add the translucent status flag if it is unset.
2246 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2248 if (translucentNavigationBarOnFullscreen) {
2249 // Set the navigation bar to be translucent.
2250 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2252 // Set the navigation bar to be black.
2253 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2256 } else { // Switch to normal viewing mode.
2257 // Reset `inFullScreenBrowsingMode` to `false`.
2258 inFullScreenBrowsingMode = false;
2260 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
2261 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
2265 // Show the `BannerAd` in the free flavor.
2266 if (BuildConfig.FLAVOR.contentEquals("free")) {
2267 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
2268 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2270 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2271 adView = findViewById(R.id.adview);
2274 // Remove the translucent navigation bar flag if it is set.
2275 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2277 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
2278 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2280 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
2281 rootCoordinatorLayout.setSystemUiVisibility(0);
2283 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
2284 rootCoordinatorLayout.setFitsSystemWindows(true);
2288 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
2289 // Get handles for the icons.
2290 MenuItem privacyIcon = mainMenu.findItem(R.id.toggleJavaScript);
2291 MenuItem firstPartyCookiesIcon = mainMenu.findItem(R.id.toggleFirstPartyCookies);
2292 MenuItem domStorageIcon = mainMenu.findItem(R.id.toggleDomStorage);
2293 MenuItem formDataIcon = mainMenu.findItem(R.id.toggleSaveFormData);
2295 // Update `privacyIcon`.
2296 if (javaScriptEnabled) { // JavaScript is enabled.
2297 privacyIcon.setIcon(R.drawable.javascript_enabled);
2298 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
2299 privacyIcon.setIcon(R.drawable.warning);
2300 } else { // All the dangerous features are disabled.
2301 privacyIcon.setIcon(R.drawable.privacy_mode);
2304 // Update `firstPartyCookiesIcon`.
2305 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
2306 firstPartyCookiesIcon.setIcon(R.drawable.cookies_enabled);
2307 } else { // First-party cookies are disabled.
2308 firstPartyCookiesIcon.setIcon(R.drawable.cookies_disabled);
2311 // Update `domStorageIcon`.
2312 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
2313 domStorageIcon.setIcon(R.drawable.dom_storage_enabled);
2314 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
2315 domStorageIcon.setIcon(R.drawable.dom_storage_disabled);
2316 } else { // JavaScript is disabled, so DOM storage is ghosted.
2317 domStorageIcon.setIcon(R.drawable.dom_storage_ghosted);
2320 // Update `formDataIcon`.
2321 if (saveFormDataEnabled) { // Form data is enabled.
2322 formDataIcon.setIcon(R.drawable.form_data_enabled);
2323 } else { // Form data is disabled.
2324 formDataIcon.setIcon(R.drawable.form_data_disabled);
2327 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`. `this` references the current activity.
2328 if (runInvalidateOptionsMenu) {
2329 ActivityCompat.invalidateOptionsMenu(this);