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.Typeface;
38 import android.graphics.drawable.BitmapDrawable;
39 import android.graphics.drawable.Drawable;
40 import android.net.Uri;
41 import android.net.http.SslCertificate;
42 import android.net.http.SslError;
43 import android.os.Build;
44 import android.os.Bundle;
45 import android.preference.PreferenceManager;
46 import android.print.PrintDocumentAdapter;
47 import android.print.PrintManager;
48 import android.support.annotation.NonNull;
49 import android.support.design.widget.CoordinatorLayout;
50 import android.support.design.widget.NavigationView;
51 import android.support.design.widget.Snackbar;
52 import android.support.v4.app.ActivityCompat;
53 import android.support.v4.content.ContextCompat;
54 import android.support.v4.view.GravityCompat;
55 import android.support.v4.widget.DrawerLayout;
56 import android.support.v4.widget.SwipeRefreshLayout;
57 import android.support.v7.app.ActionBar;
58 import android.support.v7.app.ActionBarDrawerToggle;
59 import android.support.v7.app.AppCompatActivity;
60 import android.support.v7.app.AppCompatDialogFragment;
61 import android.support.v7.widget.Toolbar;
62 import android.text.Editable;
63 import android.text.Spanned;
64 import android.text.TextWatcher;
65 import android.text.style.ForegroundColorSpan;
66 import android.text.style.StyleSpan;
67 import android.util.Patterns;
68 import android.view.ContextMenu;
69 import android.view.GestureDetector;
70 import android.view.KeyEvent;
71 import android.view.Menu;
72 import android.view.MenuItem;
73 import android.view.MotionEvent;
74 import android.view.View;
75 import android.view.WindowManager;
76 import android.view.inputmethod.InputMethodManager;
77 import android.webkit.CookieManager;
78 import android.webkit.DownloadListener;
79 import android.webkit.SslErrorHandler;
80 import android.webkit.WebBackForwardList;
81 import android.webkit.WebChromeClient;
82 import android.webkit.WebResourceResponse;
83 import android.webkit.WebStorage;
84 import android.webkit.WebView;
85 import android.webkit.WebViewClient;
86 import android.webkit.WebViewDatabase;
87 import android.widget.EditText;
88 import android.widget.FrameLayout;
89 import android.widget.ImageView;
90 import android.widget.LinearLayout;
91 import android.widget.ProgressBar;
92 import android.widget.RelativeLayout;
93 import android.widget.TextView;
95 import com.stoutner.privacybrowser.BannerAd;
96 import com.stoutner.privacybrowser.BuildConfig;
97 import com.stoutner.privacybrowser.R;
98 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
99 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
100 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
101 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
102 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
103 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
104 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
105 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
107 import java.io.BufferedReader;
108 import java.io.ByteArrayInputStream;
109 import java.io.IOException;
110 import java.io.InputStreamReader;
111 import java.io.UnsupportedEncodingException;
112 import java.net.MalformedURLException;
114 import java.net.URLDecoder;
115 import java.net.URLEncoder;
116 import java.util.HashMap;
117 import java.util.HashSet;
118 import java.util.Map;
119 import java.util.Set;
121 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
122 public class MainWebViewActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, CreateHomeScreenShortcutDialog.CreateHomeScreenSchortcutListener,
123 SslCertificateErrorDialog.SslCertificateErrorListener, DownloadFileDialog.DownloadFileListener, DownloadImageDialog.DownloadImageListener, UrlHistoryDialog.UrlHistoryListener {
125 // `favoriteIconBitmap` is public static so it can be accessed from `CreateHomeScreenShortcutDialog`, `BookmarksActivity`, `CreateBookmarkDialog`, `CreateBookmarkFolderDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`, `ViewSslCertificateDialog`.
126 // It is also used in `onCreate()`, `onCreateHomeScreenShortcutCreate()`, and `applyDomainSettings`.
127 public static Bitmap favoriteIconBitmap;
129 // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`, `CreateBookmarkDialog`, and `AddDomainDialog`.
130 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
131 public static String formattedUrlString;
133 // `sslCertificate` is public static so it can be accessed from `ViewSslCertificateDialog`. It is also used in `onCreate()`.
134 public static SslCertificate sslCertificate;
136 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`.
137 public static String orbotStatus;
139 // `webViewTitle` is public static so it can be accessed from `CreateBookmarkDialog` and `CreateHomeScreenShortcutDialog`. It is also used in `onCreate()`.
140 public static String webViewTitle;
142 // `displayWebpageImagesBoolean` is public static so it can be accessed from `DomainSettingsFragment`. It is also used in `applyAppSettings()` and `applyDomainSettings()`.
143 public static boolean displayWebpageImagesBoolean;
145 // `reloadOnRestartBoolean` is public static so it can be accessed from `SettingsFragment`. It is also used in `onRestart()`
146 public static boolean reloadOnRestartBoolean;
149 // `appBar` is used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applyAppSettings()`.
150 private ActionBar appBar;
152 // `navigatingHistory` is used in `onCreate()`, `onNavigationItemSelected()`, and `applyDomainSettings()`.
153 private boolean navigatingHistory;
155 // `favoriteIconDefaultBitmap` is used in `onCreate()` and `applyDomainSettings`.
156 private Bitmap favoriteIconDefaultBitmap;
158 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, and `onBackPressed()`.
159 private DrawerLayout drawerLayout;
161 // `rootCoordinatorLayout` is used in `onCreate()` and `applyAppSettings()`.
162 private CoordinatorLayout rootCoordinatorLayout;
164 // `mainWebView` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`, `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`
165 // and `setDisplayWebpageImages()`.
166 private WebView mainWebView;
168 // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
169 private FrameLayout fullScreenVideoFrameLayout;
171 // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu`, and `onRestart()`.
172 private SwipeRefreshLayout swipeRefreshLayout;
174 // `urlAppBarRelativeLayout` is used in `onCreate()` and `applyDomainSettings()`.
175 private RelativeLayout urlAppBarRelativeLayout;
177 // `favoriteIconImageView` is used in `onCreate()` and `applyDomainSettings()`
178 private ImageView favoriteIconImageView;
180 // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `loadUrlFromTextBox()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
181 private CookieManager cookieManager;
183 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
184 private final Map<String, String> customHeaders = new HashMap<>();
186 // `javaScriptEnabled` is also used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `applyAppSettings()`.
187 // It is `Boolean` instead of `boolean` because `applyAppSettings()` needs to know if it is `null`.
188 private Boolean javaScriptEnabled;
190 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applyAppSettings()`.
191 private boolean firstPartyCookiesEnabled;
193 // `thirdPartyCookiesEnabled` used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
194 private boolean thirdPartyCookiesEnabled;
196 // `domStorageEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
197 private boolean domStorageEnabled;
199 // `saveFormDataEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
200 private boolean saveFormDataEnabled;
202 // `swipeToRefreshEnabled` is used in `onPrepareOptionsMenu()` and `applyAppSettings()`.
203 private boolean swipeToRefreshEnabled;
205 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applyAppSettings()`.
206 private String homepage;
208 // `searchURL` is used in `loadURLFromTextBox()` and `applyAppSettings()`.
209 private String searchURL;
211 // `adBlockerEnabled` is used in `onCreate()` and `applyAppSettings()`.
212 private boolean adBlockerEnabled;
214 // `privacyBrowserRuntime` is used in `onCreate()` and `applyAppSettings()`.
215 private Runtime privacyBrowserRuntime;
217 // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
218 private boolean incognitoModeEnabled;
220 // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
221 private boolean fullScreenBrowsingModeEnabled;
223 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
224 private boolean inFullScreenBrowsingMode;
226 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
227 private boolean hideSystemBarsOnFullscreen;
229 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
230 private boolean translucentNavigationBarOnFullscreen;
232 // `currentDomainName` is used in `onCreate()`, `onNavigationItemSelected()`, and `applyDomainSettings()`.
233 private String currentDomainName;
235 // `waitingForOrbot` is used in `onCreate()` and `applyAppSettings()`.
236 private boolean waitingForOrbot;
238 // `domainSettingsApplied` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
239 private boolean domainSettingsApplied;
241 // `displayWebpageImagesInt` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
242 private int displayWebpageImagesInt;
244 // `onTheFlyDisplayImagesSet` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
245 private boolean onTheFlyDisplayImagesSet;
247 // `waitingForOrbotData` is used in `onCreate()` and `applyAppSettings()`.
248 private String waitingForOrbotHTMLString;
250 // `privateDataDirectoryString` is used in `onCreate()` and `onNavigationItemSelected()`.
251 private String privateDataDirectoryString;
253 // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
254 private LinearLayout findOnPageLinearLayout;
256 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
257 private EditText findOnPageEditText;
259 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
260 private Menu mainMenu;
262 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
263 private ActionBarDrawerToggle drawerToggle;
265 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
266 private Toolbar supportAppBar;
268 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, `loadUrl()`, and `highlightUrlText()`.
269 private EditText urlTextBox;
271 // `redColorSpan` is used in `onCreate()` and `highlightUrlText()`.
272 private ForegroundColorSpan redColorSpan;
274 // `initialGrayColorSpan` is sued in `onCreate()` and `highlightUrlText()`.
275 private ForegroundColorSpan initialGrayColorSpan;
277 // `finalGrayColorSpam` is used in `onCreate()` and `highlightUrlText()`.
278 private ForegroundColorSpan finalGrayColorSpan;
280 // `boldStyleSpan` is used in `onCreate()` and `highlightUrlText()`.
281 private StyleSpan boldStyleSpan;
283 // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
286 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
287 private SslErrorHandler sslErrorHandler;
289 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
290 private InputMethodManager inputMethodManager;
292 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
293 private RelativeLayout mainWebViewRelativeLayout;
295 // `darkTheme` is used in `onCreate()`, `applyAppSettings()`, and `applyDomainSettings()`.
296 private boolean darkTheme;
299 // 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.
300 @SuppressLint("SetJavaScriptEnabled")
301 // Remove Android Studio's warning about deprecations. We have to use the deprecated `getColor()` until API >= 23.
302 @SuppressWarnings("deprecation")
303 protected void onCreate(Bundle savedInstanceState) {
304 // Get a handle for `sharedPreferences`. `this` references the current context.
305 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
307 // Get the theme preference.
308 darkTheme = sharedPreferences.getBoolean("dark_theme", false);
310 // Set the activity theme.
312 setTheme(R.style.PrivacyBrowserDark);
314 setTheme(R.style.PrivacyBrowserLight);
317 // Run the default commands.
318 super.onCreate(savedInstanceState);
320 // Set the content view according to the theme..
322 setContentView(R.layout.main_drawerlayout_dark);
324 setContentView(R.layout.main_drawerlayout_light);
327 // Get a handle for `inputMethodManager`.
328 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
330 // We need to use the `SupportActionBar` from `android.support.v7.app.ActionBar` until the minimum API is >= 21.
331 supportAppBar = (Toolbar) findViewById(R.id.app_bar);
332 setSupportActionBar(supportAppBar);
333 appBar = getSupportActionBar();
335 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
336 assert appBar != null;
338 // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
339 appBar.setCustomView(R.layout.url_app_bar);
340 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
342 // Initialize the `ForegroundColorSpans` and `StyleSpan` for highlighting `urlTextBox`. We have to use the deprecated `getColor()` until API >= 23.
343 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
344 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
345 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
346 boldStyleSpan = new StyleSpan(Typeface.BOLD);
348 // Get a handle for `urlTextBox`.
349 urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.url_edittext);
351 // Remove the formatting from `urlTextBar` when the user is editing the text.
352 urlTextBox.setOnFocusChangeListener(new View.OnFocusChangeListener() {
354 public void onFocusChange(View v, boolean hasFocus) {
355 if (hasFocus) { // The user is editing `urlTextBox`.
356 // Remove the highlighting.
357 urlTextBox.getText().removeSpan(redColorSpan);
358 urlTextBox.getText().removeSpan(initialGrayColorSpan);
359 urlTextBox.getText().removeSpan(finalGrayColorSpan);
360 urlTextBox.getText().removeSpan(boldStyleSpan);
361 } else { // The user has stopped editing `urlTextBox`.
362 // Reapply the highlighting.
365 // Scroll to the beginning of the text.
366 urlTextBox.setScrollX(0);
371 // Set the `Go` button on the keyboard to load the URL in `urlTextBox`.
372 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
374 public boolean onKey(View v, int keyCode, KeyEvent event) {
375 // If the event is a key-down event on the `enter` button, load the URL.
376 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
377 // Load the URL into the mainWebView and consume the event.
379 loadUrlFromTextBox();
380 } catch (UnsupportedEncodingException e) {
383 // If the enter key was pressed, consume the event.
386 // If any other key was pressed, do not consume the event.
392 // Set `waitingForOrbotHTMLString`.
393 waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
395 // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
396 currentDomainName = "";
397 orbotStatus = "unknown";
398 waitingForOrbot = false;
400 // Create an Orbot status `BroadcastReceiver`.
401 BroadcastReceiver orbotStatusBroadcastReceiver = new BroadcastReceiver() {
403 public void onReceive(Context context, Intent intent) {
404 // Store the content of the status message in `orbotStatus`.
405 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
407 // If we are waiting on Orbot, load the website now that Orbot is connected.
408 if (orbotStatus.equals("ON") && waitingForOrbot) {
409 // Reset `waitingForOrbot`.
410 waitingForOrbot = false;
412 // Load `formattedUrlString
413 loadUrl(formattedUrlString);
418 // Register `orbotStatusBroadcastReceiver` on `this` context.
419 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
421 // Get handles for views that need to be accessed.
422 drawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout);
423 rootCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.root_coordinatorlayout);
424 mainWebViewRelativeLayout = (RelativeLayout) findViewById(R.id.main_webview_relativelayout);
425 mainWebView = (WebView) findViewById(R.id.main_webview);
426 findOnPageLinearLayout = (LinearLayout) findViewById(R.id.find_on_page_linearlayout);
427 findOnPageEditText = (EditText) findViewById(R.id.find_on_page_edittext);
428 fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.full_screen_video_framelayout);
429 urlAppBarRelativeLayout = (RelativeLayout) findViewById(R.id.url_app_bar_relativelayout);
430 favoriteIconImageView = (ImageView) findViewById(R.id.favorite_icon);
432 // Create a double-tap listener to toggle full-screen mode.
433 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
434 // Override `onDoubleTap()`. All other events are handled using the default settings.
436 public boolean onDoubleTap(MotionEvent event) {
437 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
438 // Toggle `inFullScreenBrowsingMode`.
439 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
441 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
442 // Hide the `appBar`.
445 // Hide the `BannerAd` in the free flavor.
446 if (BuildConfig.FLAVOR.contentEquals("free")) {
447 BannerAd.hideAd(adView);
450 // Modify the system bars.
451 if (hideSystemBarsOnFullscreen) { // Hide everything.
452 // Remove the translucent overlays.
453 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
455 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
456 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
458 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
459 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
460 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
462 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
464 // Set `rootCoordinatorLayout` to fill the whole screen.
465 rootCoordinatorLayout.setFitsSystemWindows(false);
466 } else { // Hide everything except the status and navigation bars.
467 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
468 rootCoordinatorLayout.setFitsSystemWindows(false);
470 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.
471 // Set the navigation bar to be translucent.
472 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
475 } else { // Switch to normal viewing mode.
476 // Show the `appBar`.
479 // Show the `BannerAd` in the free flavor.
480 if (BuildConfig.FLAVOR.contentEquals("free")) {
481 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
482 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
484 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
485 adView = findViewById(R.id.adview);
488 // Remove the translucent navigation bar flag if it is set.
489 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
491 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
492 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
494 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
495 rootCoordinatorLayout.setSystemUiVisibility(0);
497 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
498 rootCoordinatorLayout.setFitsSystemWindows(true);
501 // Consume the double-tap.
503 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
509 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
510 mainWebView.setOnTouchListener(new View.OnTouchListener() {
512 public boolean onTouch(View v, MotionEvent event) {
513 // Send the `event` to `gestureDetector`.
514 return gestureDetector.onTouchEvent(event);
518 // Update `findOnPageCountTextView`.
519 mainWebView.setFindListener(new WebView.FindListener() {
520 // Get a handle for `findOnPageCountTextView`.
521 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
524 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
525 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
526 // Set `findOnPageCountTextView` to `0/0`.
527 findOnPageCountTextView.setText(R.string.zero_of_zero);
528 } else if (isDoneCounting) { // There are matches.
529 // `activeMatchOrdinal` is zero-based.
530 int activeMatch = activeMatchOrdinal + 1;
532 // Set `findOnPageCountTextView`.
533 findOnPageCountTextView.setText(activeMatch + "/" + numberOfMatches);
538 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
539 findOnPageEditText.addTextChangedListener(new TextWatcher() {
541 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
546 public void onTextChanged(CharSequence s, int start, int before, int count) {
551 public void afterTextChanged(Editable s) {
552 // Search for the text in `mainWebView`.
553 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
557 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
558 findOnPageEditText.setOnKeyListener(new View.OnKeyListener() {
560 public boolean onKey(View v, int keyCode, KeyEvent event) {
561 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
562 // Hide the soft keyboard. `0` indicates no additional flags.
563 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
565 // Consume the event.
567 } else { // A different key was pressed.
568 // Do not consume the event.
574 // Implement swipe to refresh
575 swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refreshlayout);
576 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
577 swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
579 public void onRefresh() {
580 mainWebView.reload();
584 // `DrawerTitle` identifies the `DrawerLayout` in accessibility mode.
585 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
587 // Listen for touches on the navigation menu.
588 final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationview);
589 navigationView.setNavigationItemSelectedListener(this);
591 // 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.
592 final Menu navigationMenu = navigationView.getMenu();
593 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
594 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
595 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
597 // The `DrawerListener` allows us to update the Navigation Menu.
598 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
600 public void onDrawerSlide(View drawerView, float slideOffset) {
604 public void onDrawerOpened(View drawerView) {
608 public void onDrawerClosed(View drawerView) {
612 public void onDrawerStateChanged(int newState) {
613 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // The drawer is opening or closing.
614 // Update the `Back`, `Forward`, and `History` menu items.
615 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
616 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
617 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
619 // Hide the keyboard (if displayed) so we can see the navigation menu. `0` indicates no additional flags.
620 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
622 // Clear the focus from `urlTextBox` if it has it.
623 urlTextBox.clearFocus();
628 // drawerToggle creates the hamburger icon at the start of the AppBar.
629 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
631 // Initialize `adServerSet`.
632 final Set<String> adServersSet = new HashSet<>();
634 // Load the list of ad servers into memory.
636 // Load `pgl.yoyo.org_adservers.txt` into a `BufferedReader`.
637 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(getAssets().open("pgl.yoyo.org_adservers.txt")));
639 // Create a string for storing each ad server.
642 // Populate `adServersSet`.
643 while ((adServer = bufferedReader.readLine()) != null) {
644 adServersSet.add(adServer);
647 // Close `bufferedReader`.
648 bufferedReader.close();
649 } catch (IOException ioException) {
650 // We're pretty sure the asset exists, so we don't need to worry about the `IOException` ever being thrown.
653 mainWebView.setWebViewClient(new WebViewClient() {
654 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
655 // We have to use the deprecated `shouldOverrideUrlLoading` until API >= 24.
656 @SuppressWarnings("deprecation")
658 public boolean shouldOverrideUrlLoading(WebView view, String url) {
659 if (url.startsWith("mailto:")) { // Load the URL in an external email program because it begins with `mailto:`.
660 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
661 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
663 // Parse the url and set it as the data for the `Intent`.
664 emailIntent.setData(Uri.parse(url));
666 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
667 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
670 startActivity(emailIntent);
672 // Returning `true` indicates the application is handling the URL.
674 } else { // Load the URL in Privacy Browser.
675 // Apply the domain settings for the new URL.
676 applyDomainSettings(url);
678 // Returning `false` causes the current `WebView` to handle the URL and prevents it from adding redirects to the history list.
683 // Block ads. We have to use the deprecated `shouldInterceptRequest` until minimum API >= 21.
684 @SuppressWarnings("deprecation")
686 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
687 if (adBlockerEnabled) { // Block ads.
688 // Extract the host from `url`.
689 Uri requestUri = Uri.parse(url);
690 String requestHost = requestUri.getHost();
692 // Initialize a variable to track if this is an ad server.
693 boolean requestHostIsAdServer = false;
695 // Check all the subdomains of `requestHost` if it is not `null` against the ad server database.
696 if (requestHost != null) {
697 while (requestHost.contains(".") && !requestHostIsAdServer) { // Stop checking if we run out of `.` or if we already know that `requestHostIsAdServer` is `true`.
698 if (adServersSet.contains(requestHost)) {
699 requestHostIsAdServer = true;
702 // Strip out the lowest subdomain of `requestHost`.
703 requestHost = requestHost.substring(requestHost.indexOf(".") + 1);
707 if (requestHostIsAdServer) { // It is an ad server.
708 // Return an empty `WebResourceResponse`.
709 return new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
710 } else { // It is not an ad server.
711 // `return null` loads the requested resource.
714 } else { // Ad blocking is disabled.
715 // `return null` loads the requested resource.
720 // Update the URL in urlTextBox when the page starts to load.
722 public void onPageStarted(WebView view, String url, Bitmap favicon) {
723 // Reset `webViewTitle`
724 webViewTitle = getString(R.string.no_title);
726 // Check to see if we are waiting on Orbot.
727 if (!waitingForOrbot) { // We are not waiting on Orbot, so we need to process the URL.
728 // 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.
729 formattedUrlString = url;
731 // Display the formatted URL text.
732 urlTextBox.setText(formattedUrlString);
734 // Apply text highlighting to `urlTextBox`.
737 // Apply any custom domain settings if the URL was loaded by navigating history.
738 if (navigatingHistory) {
739 applyDomainSettings(url);
744 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
746 public void onPageFinished(WebView view, String url) {
747 // Clear the cache and history if Incognito Mode is enabled.
748 if (incognitoModeEnabled) {
749 // Clear the cache. `true` includes disk files.
750 mainWebView.clearCache(true);
752 // Clear the back/forward history.
753 mainWebView.clearHistory();
755 // Manually delete cache folders.
757 // Delete the main `cache` folder.
758 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
760 // 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`.
761 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
762 } catch (IOException e) {
763 // Do nothing if an error is thrown.
767 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
768 if (!waitingForOrbot) {
769 // Check to see if `WebView` has set `url` to be `about:blank`.
770 if (url.equals("about:blank")) { // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
771 // Set `formattedUrlString` to `""`.
772 formattedUrlString = "";
774 urlTextBox.setText(formattedUrlString);
776 // Request focus for `urlTextBox`.
777 urlTextBox.requestFocus();
779 // Display the keyboard.
780 inputMethodManager.showSoftInput(urlTextBox, 0);
782 // Apply the domain settings. This clears any settings from the previous domain.
783 applyDomainSettings(formattedUrlString);
784 } else { // `WebView` has loaded a webpage.
785 // Set `formattedUrlString`.
786 formattedUrlString = url;
788 // Only update `urlTextBox` if the user is not typing in it.
789 if (!urlTextBox.hasFocus()) {
790 // Display the formatted URL text.
791 urlTextBox.setText(formattedUrlString);
793 // Apply text highlighting to `urlTextBox`.
798 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog`.
799 sslCertificate = mainWebView.getCertificate();
803 // Handle SSL Certificate errors.
805 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
806 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
807 sslErrorHandler = handler;
809 // Display the SSL error `AlertDialog`.
810 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
811 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.ssl_certificate_error));
815 // Get a handle for the progress bar.
816 final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress_bar);
818 mainWebView.setWebChromeClient(new WebChromeClient() {
819 // Update the progress bar when a page is loading.
821 public void onProgressChanged(WebView view, int progress) {
822 progressBar.setProgress(progress);
823 if (progress < 100) {
824 progressBar.setVisibility(View.VISIBLE);
826 progressBar.setVisibility(View.GONE);
828 //Stop the `SwipeToRefresh` indicator if it is running
829 swipeRefreshLayout.setRefreshing(false);
833 // Set the favorite icon when it changes.
835 public void onReceivedIcon(WebView view, Bitmap icon) {
836 // Only update the favorite icon if the website has finished loading.
837 if (progressBar.getVisibility() == View.GONE) {
838 // Save a copy of the favorite icon.
839 favoriteIconBitmap = icon;
841 // Place the favorite icon in the appBar.
842 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
846 // Save a copy of the title when it changes.
848 public void onReceivedTitle(WebView view, String title) {
849 // Save a copy of the title.
850 webViewTitle = title;
853 // Enter full screen video
855 public void onShowCustomView(View view, CustomViewCallback callback) {
856 // Pause the ad if this is the free flavor.
857 if (BuildConfig.FLAVOR.contentEquals("free")) {
858 BannerAd.pauseAd(adView);
861 // Remove the translucent overlays.
862 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
864 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
865 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
867 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
868 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
869 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
871 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
873 // Set `rootCoordinatorLayout` to fill the entire screen.
874 rootCoordinatorLayout.setFitsSystemWindows(false);
876 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
877 fullScreenVideoFrameLayout.addView(view);
878 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
881 // Exit full screen video
882 public void onHideCustomView() {
883 // Hide `fullScreenVideoFrameLayout`.
884 fullScreenVideoFrameLayout.removeAllViews();
885 fullScreenVideoFrameLayout.setVisibility(View.GONE);
887 // Add the translucent status flag. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
888 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
890 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars. This also clears the `SYSTEM_UI` flags.
891 rootCoordinatorLayout.setFitsSystemWindows(true);
893 // Show the ad if this is the free flavor.
894 if (BuildConfig.FLAVOR.contentEquals("free")) {
895 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
896 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
898 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
899 adView = findViewById(R.id.adview);
904 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
905 registerForContextMenu(mainWebView);
907 // Allow the downloading of files.
908 mainWebView.setDownloadListener(new DownloadListener() {
910 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
911 // Show the `DownloadFileDialog` `AlertDialog` and name this instance `@string/download`.
912 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
913 downloadFileDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
917 // Allow pinch to zoom.
918 mainWebView.getSettings().setBuiltInZoomControls(true);
920 // Hide zoom controls.
921 mainWebView.getSettings().setDisplayZoomControls(false);
923 // Set `mainWebView` to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
924 mainWebView.getSettings().setUseWideViewPort(true);
926 // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
927 mainWebView.getSettings().setLoadWithOverviewMode(true);
929 // Initialize cookieManager.
930 cookieManager = CookieManager.getInstance();
932 // 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).
933 customHeaders.put("X-Requested-With", "");
935 // 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.
936 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
938 // Get the intent that started the app.
939 final Intent launchingIntent = getIntent();
941 // Extract the launching intent data as `launchingIntentUriData`.
942 final Uri launchingIntentUriData = launchingIntent.getData();
944 // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
945 if (launchingIntentUriData != null) {
946 formattedUrlString = launchingIntentUriData.toString();
949 // Get a handle for the `Runtime`.
950 privacyBrowserRuntime = Runtime.getRuntime();
952 // Store the application's private data directory.
953 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`.
955 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
956 inFullScreenBrowsingMode = false;
958 // Initialize AdView for the free flavor.
959 adView = findViewById(R.id.adview);
961 // Initialize the privacy settings variables.
962 javaScriptEnabled = false;
963 firstPartyCookiesEnabled = false;
964 thirdPartyCookiesEnabled = false;
965 domStorageEnabled = false;
966 saveFormDataEnabled = false;
968 // Initialize `webViewTitle`.
969 webViewTitle = getString(R.string.no_title);
971 // Initialize `favoriteIconBitmap`. We have to use `ContextCompat` until API >= 21.
972 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
973 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
974 favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
976 // If the favorite icon is null, load the default.
977 if (favoriteIconBitmap == null) {
978 favoriteIconBitmap = favoriteIconDefaultBitmap;
981 // Apply the app settings from the shared preferences.
984 // Load `formattedUrlString` if we are not waiting for Orbot to connect.
985 if (!waitingForOrbot) {
986 loadUrl(formattedUrlString);
991 protected void onNewIntent(Intent intent) {
992 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
995 if (intent.getData() != null) {
996 // Get the intent data and convert it to a string.
997 final Uri intentUriData = intent.getData();
998 formattedUrlString = intentUriData.toString();
1001 // Close the navigation drawer if it is open.
1002 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1003 drawerLayout.closeDrawer(GravityCompat.START);
1006 // Load the website.
1007 loadUrl(formattedUrlString);
1009 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1010 mainWebView.requestFocus();
1014 public void onRestart() {
1017 // Apply the app settings, which may have been changed in `SettingsActivity`.
1020 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1021 updatePrivacyIcons(true);
1023 // Set the display webpage images mode.
1024 setDisplayWebpageImages();
1026 // Reload the webpage if displaying of images has been disabled in `SettingsFragment`.
1027 if (reloadOnRestartBoolean) {
1028 // Reload `mainWebView`.
1029 mainWebView.reload();
1031 // Reset `reloadOnRestartBoolean`.
1032 reloadOnRestartBoolean = false;
1036 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1038 public void onResume() {
1041 // Resume JavaScript (if enabled).
1042 mainWebView.resumeTimers();
1044 // Resume `mainWebView`.
1045 mainWebView.onResume();
1047 // Resume the adView for the free flavor.
1048 if (BuildConfig.FLAVOR.contentEquals("free")) {
1049 BannerAd.resumeAd(adView);
1054 public void onPause() {
1055 // Pause `mainWebView`.
1056 mainWebView.onPause();
1058 // Stop all JavaScript.
1059 mainWebView.pauseTimers();
1061 // Pause the adView or it will continue to consume resources in the background on the free flavor.
1062 if (BuildConfig.FLAVOR.contentEquals("free")) {
1063 BannerAd.pauseAd(adView);
1070 public boolean onCreateOptionsMenu(Menu menu) {
1071 // Inflate the menu; this adds items to the action bar if it is present.
1072 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1074 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1077 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1078 updatePrivacyIcons(false);
1080 // Get handles for the menu items.
1081 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1082 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1083 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1084 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1086 // Only display third-party cookies if SDK >= 21
1087 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1089 // Get the shared preference values. `this` references the current context.
1090 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1092 // Set the status of the additional app bar icons. The default is `false`.
1093 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
1094 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1095 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1096 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1097 } else { //Do not display the additional icons.
1098 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1099 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1100 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1107 public boolean onPrepareOptionsMenu(Menu menu) {
1108 // Hide the keyboard (if displayed) so we can see the options menu. `0` indicates no additional flags.
1109 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1111 // Get handles for the menu items.
1112 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1113 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1114 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1115 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1116 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1117 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);
1118 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1119 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1120 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1122 // Set the status of the menu item checkboxes.
1123 toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1124 toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1125 toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1126 toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);
1127 displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1129 // Enable third-party cookies if first-party cookies are enabled.
1130 toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1132 // Enable DOM Storage if JavaScript is enabled.
1133 toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
1135 // Enable Clear Cookies if there are any.
1136 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1138 // Enable Clear Form Data is there is any.
1139 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1140 clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
1142 // Initialize font size variables.
1143 int fontSize = mainWebView.getSettings().getTextZoom();
1144 String fontSizeTitle;
1145 MenuItem selectedFontSizeMenuItem;
1147 // Prepare the font size title and current size menu item.
1150 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.twenty_five_percent);
1151 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1155 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.fifty_percent);
1156 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1160 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.seventy_five_percent);
1161 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1165 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
1166 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1170 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_twenty_five_percent);
1171 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1175 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_fifty_percent);
1176 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1180 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_seventy_five_percent);
1181 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1185 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.two_hundred_percent);
1186 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1190 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
1191 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1195 // Set the font size title and select the current size menu item.
1196 fontSizeMenuItem.setTitle(fontSizeTitle);
1197 selectedFontSizeMenuItem.setChecked(true);
1199 // Only show `Refresh` if `swipeToRefresh` is disabled.
1200 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
1202 // Run all the other default commands.
1203 super.onPrepareOptionsMenu(menu);
1205 // `return true` displays the menu.
1210 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1211 @SuppressLint("SetJavaScriptEnabled")
1212 // removeAllCookies is deprecated, but it is required for API < 21.
1213 @SuppressWarnings("deprecation")
1214 public boolean onOptionsItemSelected(MenuItem menuItem) {
1215 int menuItemId = menuItem.getItemId();
1217 // Set the commands that relate to the menu entries.
1218 switch (menuItemId) {
1219 case R.id.toggle_javascript:
1220 // Switch the status of javaScriptEnabled.
1221 javaScriptEnabled = !javaScriptEnabled;
1223 // Apply the new JavaScript status.
1224 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1226 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1227 updatePrivacyIcons(true);
1229 // Display a `Snackbar`.
1230 if (javaScriptEnabled) { // JavaScrip is enabled.
1231 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1232 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
1233 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1234 } else { // Privacy mode.
1235 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1238 // Reload the WebView.
1239 mainWebView.reload();
1242 case R.id.toggle_first_party_cookies:
1243 // Switch the status of firstPartyCookiesEnabled.
1244 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1246 // Update the menu checkbox.
1247 menuItem.setChecked(firstPartyCookiesEnabled);
1249 // Apply the new cookie status.
1250 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1252 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1253 updatePrivacyIcons(true);
1255 // Display a `Snackbar`.
1256 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1257 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1258 } else if (javaScriptEnabled){ // JavaScript is still enabled.
1259 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1260 } else { // Privacy mode.
1261 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1264 // Reload the WebView.
1265 mainWebView.reload();
1268 case R.id.toggle_third_party_cookies:
1269 if (Build.VERSION.SDK_INT >= 21) {
1270 // Switch the status of thirdPartyCookiesEnabled.
1271 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1273 // Update the menu checkbox.
1274 menuItem.setChecked(thirdPartyCookiesEnabled);
1276 // Apply the new cookie status.
1277 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1279 // Display a `Snackbar`.
1280 if (thirdPartyCookiesEnabled) {
1281 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1283 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1286 // Reload the WebView.
1287 mainWebView.reload();
1288 } // Else do nothing because SDK < 21.
1291 case R.id.toggle_dom_storage:
1292 // Switch the status of domStorageEnabled.
1293 domStorageEnabled = !domStorageEnabled;
1295 // Update the menu checkbox.
1296 menuItem.setChecked(domStorageEnabled);
1298 // Apply the new DOM Storage status.
1299 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1301 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1302 updatePrivacyIcons(true);
1304 // Display a `Snackbar`.
1305 if (domStorageEnabled) {
1306 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1308 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1311 // Reload the WebView.
1312 mainWebView.reload();
1315 case R.id.toggle_save_form_data:
1316 // Switch the status of saveFormDataEnabled.
1317 saveFormDataEnabled = !saveFormDataEnabled;
1319 // Update the menu checkbox.
1320 menuItem.setChecked(saveFormDataEnabled);
1322 // Apply the new form data status.
1323 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1325 // Display a `Snackbar`.
1326 if (saveFormDataEnabled) {
1327 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1329 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1332 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1333 updatePrivacyIcons(true);
1335 // Reload the WebView.
1336 mainWebView.reload();
1339 case R.id.clear_cookies:
1340 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1341 .setAction(R.string.undo, new View.OnClickListener() {
1343 public void onClick(View v) {
1344 // Do nothing because everything will be handled by `onDismissed()` below.
1347 .addCallback(new Snackbar.Callback() {
1349 public void onDismissed(Snackbar snackbar, int event) {
1351 // The user pushed the `Undo` button.
1352 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1356 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1358 // `cookieManager.removeAllCookie()` varies by SDK.
1359 if (Build.VERSION.SDK_INT < 21) {
1360 cookieManager.removeAllCookie();
1362 // `null` indicates no callback.
1363 cookieManager.removeAllCookies(null);
1371 case R.id.clear_dom_storage:
1372 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1373 .setAction(R.string.undo, new View.OnClickListener() {
1375 public void onClick(View v) {
1376 // Do nothing because everything will be handled by `onDismissed()` below.
1379 .addCallback(new Snackbar.Callback() {
1381 public void onDismissed(Snackbar snackbar, int event) {
1383 // The user pushed the `Undo` button.
1384 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1388 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1390 // Delete the DOM Storage.
1391 WebStorage webStorage = WebStorage.getInstance();
1392 webStorage.deleteAllData();
1399 case R.id.clear_form_data:
1400 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1401 .setAction(R.string.undo, new View.OnClickListener() {
1403 public void onClick(View v) {
1404 // Do nothing because everything will be handled by `onDismissed()` below.
1407 .addCallback(new Snackbar.Callback() {
1409 public void onDismissed(Snackbar snackbar, int event) {
1411 // The user pushed the `Undo` button.
1412 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1416 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1418 // Delete the form data.
1419 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1420 mainWebViewDatabase.clearFormData();
1427 case R.id.font_size_twenty_five_percent:
1428 mainWebView.getSettings().setTextZoom(25);
1431 case R.id.font_size_fifty_percent:
1432 mainWebView.getSettings().setTextZoom(50);
1435 case R.id.font_size_seventy_five_percent:
1436 mainWebView.getSettings().setTextZoom(75);
1439 case R.id.font_size_one_hundred_percent:
1440 mainWebView.getSettings().setTextZoom(100);
1443 case R.id.font_size_one_hundred_twenty_five_percent:
1444 mainWebView.getSettings().setTextZoom(125);
1447 case R.id.font_size_one_hundred_fifty_percent:
1448 mainWebView.getSettings().setTextZoom(150);
1451 case R.id.font_size_one_hundred_seventy_five_percent:
1452 mainWebView.getSettings().setTextZoom(175);
1455 case R.id.font_size_two_hundred_percent:
1456 mainWebView.getSettings().setTextZoom(200);
1459 case R.id.display_images:
1460 if (mainWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1461 mainWebView.getSettings().setLoadsImagesAutomatically(false);
1462 mainWebView.reload();
1463 } else { // Images are not currently loaded automatically.
1464 mainWebView.getSettings().setLoadsImagesAutomatically(true);
1467 // Set `onTheFlyDisplayImagesSet`.
1468 onTheFlyDisplayImagesSet = true;
1472 // Setup the share string.
1474 if (webViewTitle != null) {
1475 shareString = webViewTitle + " – " + urlTextBox.getText().toString();
1477 shareString = urlTextBox.getText().toString();
1480 // Create the share intent.
1481 Intent shareIntent = new Intent();
1482 shareIntent.setAction(Intent.ACTION_SEND);
1483 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1484 shareIntent.setType("text/plain");
1487 startActivity(Intent.createChooser(shareIntent, "Share URL"));
1490 case R.id.find_on_page:
1491 // Hide the URL app bar.
1492 supportAppBar.setVisibility(View.GONE);
1494 // Show the Find on Page `RelativeLayout`.
1495 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1497 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android.
1498 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1499 findOnPageEditText.postDelayed(new Runnable()
1504 // Set the focus on `findOnPageEditText`.
1505 findOnPageEditText.requestFocus();
1507 // Display the keyboard.
1508 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1514 // Get a `PrintManager` instance.
1515 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1517 // Convert `mainWebView` to `printDocumentAdapter`.
1518 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
1520 // Print the document. The print attributes are `null`.
1521 printManager.print(getResources().getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1524 case R.id.add_to_homescreen:
1525 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
1526 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
1527 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.create_shortcut));
1529 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
1533 mainWebView.reload();
1537 // Don't consume the event.
1538 return super.onOptionsItemSelected(menuItem);
1542 // removeAllCookies is deprecated, but it is required for API < 21.
1543 @SuppressWarnings("deprecation")
1545 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1546 int menuItemId = menuItem.getItemId();
1548 switch (menuItemId) {
1554 if (mainWebView.canGoBack()) {
1555 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1556 navigatingHistory = true;
1558 // Load the previous website in the history.
1559 mainWebView.goBack();
1564 if (mainWebView.canGoForward()) {
1565 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1566 navigatingHistory = true;
1568 // Load the next website in the history.
1569 mainWebView.goForward();
1574 // Get the `WebBackForwardList`.
1575 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
1577 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
1578 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
1579 urlHistoryDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.history));
1582 case R.id.bookmarks:
1583 // Launch BookmarksActivity.
1584 Intent bookmarksIntent = new Intent(this, BookmarksActivity.class);
1585 startActivity(bookmarksIntent);
1588 case R.id.downloads:
1589 // Launch the system Download Manager.
1590 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1592 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1593 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1595 startActivity(downloadManagerIntent);
1599 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1600 currentDomainName = "";
1602 // Launch `SettingsActivity`.
1603 Intent settingsIntent = new Intent(this, SettingsActivity.class);
1604 startActivity(settingsIntent);
1608 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1609 currentDomainName = "";
1611 // Launch `DomainsActivity`.
1612 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1613 startActivity(domainsIntent);
1617 // Launch `GuideActivity`.
1618 Intent guideIntent = new Intent(this, GuideActivity.class);
1619 startActivity(guideIntent);
1623 // Launch `AboutActivity`.
1624 Intent aboutIntent = new Intent(this, AboutActivity.class);
1625 startActivity(aboutIntent);
1628 case R.id.clearAndExit:
1629 // Get a handle for `sharedPreferences`. `this` references the current context.
1630 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1632 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
1635 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
1636 // The command to remove cookies changed slightly in API 21.
1637 if (Build.VERSION.SDK_INT >= 21) {
1638 cookieManager.removeAllCookies(null);
1640 cookieManager.removeAllCookie();
1643 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1645 // We have to use two commands because `Runtime.exec()` does not like `*`.
1646 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
1647 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
1648 } catch (IOException e) {
1649 // Do nothing if an error is thrown.
1653 // Clear DOM storage.
1654 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
1655 // Ask `WebStorage` to clear the DOM storage.
1656 WebStorage webStorage = WebStorage.getInstance();
1657 webStorage.deleteAllData();
1659 // Manually delete the DOM storage directory, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1661 // We have to use a `String[]` because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1662 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1663 } catch (IOException e) {
1664 // Do nothing if an error is thrown.
1669 if (clearEverything || sharedPreferences.getBoolean("clear_form_data", true)) {
1670 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1671 webViewDatabase.clearFormData();
1673 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1675 // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1676 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
1677 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
1678 } catch (IOException e) {
1679 // Do nothing if an error is thrown.
1684 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
1685 // `true` includes disk files.
1686 mainWebView.clearCache(true);
1688 // Manually delete the cache directories.
1690 // Delete the main cache directory.
1691 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1693 // Delete the secondary `Service Worker` cache directory. We have to use a `String[]` because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1694 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1695 } catch (IOException e) {
1696 // Do nothing if an error is thrown.
1700 // Clear SSL certificate preferences.
1701 mainWebView.clearSslPreferences();
1703 // Clear the back/forward history.
1704 mainWebView.clearHistory();
1706 // Clear `formattedUrlString`.
1707 formattedUrlString = null;
1709 // Clear `customHeaders`.
1710 customHeaders.clear();
1712 // Detach all views from `mainWebViewRelativeLayout`.
1713 mainWebViewRelativeLayout.removeAllViews();
1715 // Destroy the internal state of `mainWebView`.
1716 mainWebView.destroy();
1718 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
1719 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
1720 if (clearEverything) {
1722 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
1723 } catch (IOException e) {
1724 // Do nothing if an error is thrown.
1728 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
1729 if (Build.VERSION.SDK_INT >= 21) {
1730 finishAndRemoveTask();
1735 // Remove the terminated program from RAM. The status code is `0`.
1740 // Close the navigation drawer.
1741 drawerLayout.closeDrawer(GravityCompat.START);
1746 public void onPostCreate(Bundle savedInstanceState) {
1747 super.onPostCreate(savedInstanceState);
1749 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
1750 drawerToggle.syncState();
1754 public void onConfigurationChanged(Configuration newConfig) {
1755 super.onConfigurationChanged(newConfig);
1757 // Reload the ad for the free flavor if we are not in full screen mode.
1758 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
1760 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1762 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1763 adView = findViewById(R.id.adview);
1766 // `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
1767 // ActivityCompat.invalidateOptionsMenu(this);
1771 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
1772 // Store the `HitTestResult`.
1773 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
1776 final String imageUrl;
1777 final String linkUrl;
1779 // Get a handle for the `ClipboardManager`.
1780 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
1782 switch (hitTestResult.getType()) {
1783 // `SRC_ANCHOR_TYPE` is a link.
1784 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1785 // Get the target URL.
1786 linkUrl = hitTestResult.getExtra();
1788 // Set the target URL as the title of the `ContextMenu`.
1789 menu.setHeaderTitle(linkUrl);
1791 // Add a `Load URL` entry.
1792 menu.add(R.string.load_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1794 public boolean onMenuItemClick(MenuItem item) {
1800 // Add a `Copy URL` entry.
1801 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1803 public boolean onMenuItemClick(MenuItem item) {
1804 // Save the link URL in a `ClipData`.
1805 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), linkUrl);
1807 // Set the `ClipData` as the clipboard's primary clip.
1808 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
1813 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1814 menu.add(R.string.cancel);
1817 case WebView.HitTestResult.EMAIL_TYPE:
1818 // Get the target URL.
1819 linkUrl = hitTestResult.getExtra();
1821 // Set the target URL as the title of the `ContextMenu`.
1822 menu.setHeaderTitle(linkUrl);
1824 // Add a `Write Email` entry.
1825 menu.add(R.string.write_email).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1827 public boolean onMenuItemClick(MenuItem item) {
1828 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1829 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1831 // Parse the url and set it as the data for the `Intent`.
1832 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
1834 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
1835 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1838 startActivity(emailIntent);
1843 // Add a `Copy Email Address` entry.
1844 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1846 public boolean onMenuItemClick(MenuItem item) {
1847 // Save the email address in a `ClipData`.
1848 ClipData srcEmailTypeClipData = ClipData.newPlainText(getResources().getString(R.string.email_address), linkUrl);
1850 // Set the `ClipData` as the clipboard's primary clip.
1851 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
1856 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1857 menu.add(R.string.cancel);
1860 // `IMAGE_TYPE` is an image.
1861 case WebView.HitTestResult.IMAGE_TYPE:
1862 // Get the image URL.
1863 imageUrl = hitTestResult.getExtra();
1865 // Set the image URL as the title of the `ContextMenu`.
1866 menu.setHeaderTitle(imageUrl);
1868 // Add a `View Image` entry.
1869 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1871 public boolean onMenuItemClick(MenuItem item) {
1877 // Add a `Download Image` entry.
1878 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1880 public boolean onMenuItemClick(MenuItem item) {
1881 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
1882 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
1883 downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1888 // Add a `Copy URL` entry.
1889 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1891 public boolean onMenuItemClick(MenuItem item) {
1892 // Save the image URL in a `ClipData`.
1893 ClipData srcImageTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1895 // Set the `ClipData` as the clipboard's primary clip.
1896 clipboardManager.setPrimaryClip(srcImageTypeClipData);
1901 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1902 menu.add(R.string.cancel);
1906 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
1907 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1908 // Get the image URL.
1909 imageUrl = hitTestResult.getExtra();
1911 // Set the image URL as the title of the `ContextMenu`.
1912 menu.setHeaderTitle(imageUrl);
1914 // Add a `View Image` entry.
1915 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1917 public boolean onMenuItemClick(MenuItem item) {
1923 // Add a `Download Image` entry.
1924 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1926 public boolean onMenuItemClick(MenuItem item) {
1927 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
1928 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
1929 downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1934 // Add a `Copy URL` entry.
1935 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1937 public boolean onMenuItemClick(MenuItem item) {
1938 // Save the image URL in a `ClipData`.
1939 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1941 // Set the `ClipData` as the clipboard's primary clip.
1942 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
1947 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1948 menu.add(R.string.cancel);
1954 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
1955 // Get shortcutNameEditText from the alert dialog.
1956 EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
1958 // Create the bookmark shortcut based on formattedUrlString.
1959 Intent bookmarkShortcut = new Intent();
1960 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
1961 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
1963 // Place the bookmark shortcut on the home screen.
1964 Intent placeBookmarkShortcut = new Intent();
1965 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
1966 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
1967 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIconBitmap);
1968 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
1969 sendBroadcast(placeBookmarkShortcut);
1973 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
1974 // Download the image if it has an HTTP or HTTPS URI.
1975 if (imageUrl.startsWith("http")) {
1976 // Get a handle for the system `DOWNLOAD_SERVICE`.
1977 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
1979 // Parse `imageUrl`.
1980 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
1982 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
1983 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
1984 if (firstPartyCookiesEnabled) {
1985 // Get the cookies for `imageUrl`.
1986 String cookies = cookieManager.getCookie(imageUrl);
1988 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
1989 downloadRequest.addRequestHeader("Cookie", cookies);
1992 // Get the file name from `dialogFragment`.
1993 EditText downloadImageNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_image_name);
1994 String imageName = downloadImageNameEditText.getText().toString();
1996 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
1997 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `imageName`.
1998 downloadRequest.setDestinationInExternalFilesDir(this, "/", imageName);
1999 } else { // Only set the title using `imageName`.
2000 downloadRequest.setTitle(imageName);
2003 // Allow `MediaScanner` to index the download if it is a media file.
2004 downloadRequest.allowScanningByMediaScanner();
2006 // Add the URL as the description for the download.
2007 downloadRequest.setDescription(imageUrl);
2009 // Show the download notification after the download is completed.
2010 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2012 // Initiate the download.
2013 downloadManager.enqueue(downloadRequest);
2014 } else { // The image is not an HTTP or HTTPS URI.
2015 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
2020 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
2021 // Download the file if it has an HTTP or HTTPS URI.
2022 if (downloadUrl.startsWith("http")) {
2024 // Get a handle for the system `DOWNLOAD_SERVICE`.
2025 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2027 // Parse `downloadUrl`.
2028 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
2030 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
2031 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2032 if (firstPartyCookiesEnabled) {
2033 // Get the cookies for `downloadUrl`.
2034 String cookies = cookieManager.getCookie(downloadUrl);
2036 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2037 downloadRequest.addRequestHeader("Cookie", cookies);
2040 // Get the file name from `dialogFragment`.
2041 EditText downloadFileNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_file_name);
2042 String fileName = downloadFileNameEditText.getText().toString();
2044 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
2045 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download location to `/sdcard/Android/data/com.stoutner.privacybrowser.standard/files` named `fileName`.
2046 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
2047 } else { // Only set the title using `fileName`.
2048 downloadRequest.setTitle(fileName);
2051 // Allow `MediaScanner` to index the download if it is a media file.
2052 downloadRequest.allowScanningByMediaScanner();
2054 // Add the URL as the description for the download.
2055 downloadRequest.setDescription(downloadUrl);
2057 // Show the download notification after the download is completed.
2058 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2060 // Initiate the download.
2061 downloadManager.enqueue(downloadRequest);
2062 } else { // The download is not an HTTP or HTTPS URI.
2063 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
2067 public void viewSslCertificate(View view) {
2068 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
2069 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
2070 viewSslCertificateDialogFragment.show(getFragmentManager(), getResources().getString(R.string.view_ssl_certificate));
2074 public void onSslErrorCancel() {
2075 sslErrorHandler.cancel();
2079 public void onSslErrorProceed() {
2080 sslErrorHandler.proceed();
2084 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
2085 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2086 navigatingHistory = true;
2088 // Load the history entry.
2089 mainWebView.goBackOrForward(moveBackOrForwardSteps);
2093 public void onClearHistory() {
2094 // Clear the history.
2095 mainWebView.clearHistory();
2098 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
2100 public void onBackPressed() {
2101 // Close the navigation drawer if it is available. GravityCompat.START is the drawer on the left on Left-to-Right layout text.
2102 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
2103 drawerLayout.closeDrawer(GravityCompat.START);
2105 // Load the previous URL if available.
2106 if (mainWebView.canGoBack()) {
2107 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2108 navigatingHistory = true;
2111 mainWebView.goBack();
2113 // Pass `onBackPressed()` to the system.
2114 super.onBackPressed();
2119 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
2120 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
2121 String unformattedUrlString = urlTextBox.getText().toString().trim();
2123 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
2124 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
2125 // Add `http://` at the beginning if it is missing. Otherwise the app will segfault.
2126 if (!unformattedUrlString.startsWith("http")) {
2127 unformattedUrlString = "http://" + unformattedUrlString;
2130 // Initialize `unformattedUrl`.
2131 URL unformattedUrl = null;
2133 // 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.
2135 unformattedUrl = new URL(unformattedUrlString);
2136 } catch (MalformedURLException e) {
2137 e.printStackTrace();
2140 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2141 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2142 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2143 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2144 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2145 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2148 Uri.Builder formattedUri = new Uri.Builder();
2149 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2151 // Decode `formattedUri` as a `String` in `UTF-8`.
2152 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
2154 // Sanitize the search input and convert it to a search.
2155 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2157 // Add the base search URL.
2158 formattedUrlString = searchURL + encodedUrlString;
2161 loadUrl(formattedUrlString);
2163 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
2164 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2168 private void loadUrl(String url) {
2169 // Apply any custom domain settings.
2170 applyDomainSettings(url);
2173 mainWebView.loadUrl(url, customHeaders);
2176 public void findPreviousOnPage(View view) {
2177 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
2178 mainWebView.findNext(false);
2181 public void findNextOnPage(View view) {
2182 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2183 mainWebView.findNext(true);
2186 public void closeFindOnPage(View view) {
2187 // Delete the contents of `find_on_page_edittext`.
2188 findOnPageEditText.setText(null);
2190 // Clear the highlighted phrases.
2191 mainWebView.clearMatches();
2193 // Hide the Find on Page `RelativeLayout`.
2194 findOnPageLinearLayout.setVisibility(View.GONE);
2196 // Show the URL app bar.
2197 supportAppBar.setVisibility(View.VISIBLE);
2199 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
2200 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2203 private void applyAppSettings() {
2204 // Get a handle for `sharedPreferences`. `this` references the current context.
2205 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2207 // Store the values from `sharedPreferences` in variables.
2208 String homepageString = sharedPreferences.getString("homepage", "https://start.duckduckgo.com");
2209 String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
2210 String torSearchString = sharedPreferences.getString("tor_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
2211 String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
2212 String searchString = sharedPreferences.getString("search", "https://duckduckgo.com/html/?q=");
2213 String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
2214 adBlockerEnabled = sharedPreferences.getBoolean("block_ads", true);
2215 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
2216 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
2217 boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
2218 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
2219 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
2220 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
2221 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh", false);
2222 displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
2224 // Set the homepage, search, and proxy options.
2225 if (proxyThroughOrbot) { // Set the Tor options.
2226 // Set `torHomepageString` as `homepage`.
2227 homepage = torHomepageString;
2229 // If formattedUrlString is null assign the homepage to it.
2230 if (formattedUrlString == null) {
2231 formattedUrlString = homepage;
2234 // Set the search URL.
2235 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
2236 searchURL = torSearchCustomURLString;
2237 } else { // Use the string from the pre-built list.
2238 searchURL = torSearchString;
2241 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
2242 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
2244 // Set the `appBar` background to indicate proxying through Orbot is enabled. `this` refers to the context.
2246 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
2248 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
2251 // Display a message to the user if we are waiting on Orbot.
2252 if (!orbotStatus.equals("ON")) {
2253 // Set `waitingForOrbot`.
2254 waitingForOrbot = true;
2256 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
2257 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
2259 } else { // Set the non-Tor options.
2260 // Set `homepageString` as `homepage`.
2261 homepage = homepageString;
2263 // If formattedUrlString is null assign the homepage to it.
2264 if (formattedUrlString == null) {
2265 formattedUrlString = homepage;
2268 // Set the search URL.
2269 if (searchString.equals("Custom URL")) { // Get the custom URL string.
2270 searchURL = searchCustomURLString;
2271 } else { // Use the string from the pre-built list.
2272 searchURL = searchString;
2275 // Reset the proxy to default. The host is `""` and the port is `"0"`.
2276 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
2278 // Set the default `appBar` background. `this` refers to the context.
2280 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
2282 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
2285 // Reset `waitingForOrbot.
2286 waitingForOrbot = false;
2289 // Set swipe to refresh.
2290 swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
2292 // Set Do Not Track status.
2293 if (doNotTrackEnabled) {
2294 customHeaders.put("DNT", "1");
2296 customHeaders.remove("DNT");
2299 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
2300 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
2301 if (hideSystemBarsOnFullscreen) { // Hide everything.
2302 // Remove the translucent navigation setting if it is currently flagged.
2303 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2305 // Remove the translucent status bar overlay.
2306 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2308 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
2309 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
2311 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
2312 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
2313 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
2315 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
2316 } else { // Hide everything except the status and navigation bars.
2317 // Add the translucent status flag if it is unset.
2318 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2320 if (translucentNavigationBarOnFullscreen) {
2321 // Set the navigation bar to be translucent.
2322 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2324 // Set the navigation bar to be black.
2325 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2328 } else { // Switch to normal viewing mode.
2329 // Reset `inFullScreenBrowsingMode` to `false`.
2330 inFullScreenBrowsingMode = false;
2332 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
2333 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
2337 // Show the `BannerAd` in the free flavor.
2338 if (BuildConfig.FLAVOR.contentEquals("free")) {
2339 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
2340 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2342 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2343 adView = findViewById(R.id.adview);
2346 // Remove the translucent navigation bar flag if it is set.
2347 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2349 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
2350 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2352 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
2353 rootCoordinatorLayout.setSystemUiVisibility(0);
2355 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
2356 rootCoordinatorLayout.setFitsSystemWindows(true);
2360 // We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2361 @SuppressWarnings("deprecation")
2362 private void applyDomainSettings(String url) {
2363 // Reset `navigatingHistory`.
2364 navigatingHistory = false;
2366 // Parse the URL into a URI.
2367 Uri uri = Uri.parse(url);
2369 // Extract the domain from `uri`.
2370 String hostName = uri.getHost();
2372 // Initialize `loadingNewDomainName`.
2373 boolean loadingNewDomainName;
2375 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
2376 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
2377 //noinspection SimplifiableIfStatement
2378 if ((hostName == null) || (currentDomainName == null)) {
2379 loadingNewDomainName = true;
2380 } else { // Determine if `hostName` equals `currentDomainName`.
2381 loadingNewDomainName = !hostName.equals(currentDomainName);
2384 // 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.
2385 if (loadingNewDomainName) {
2386 // Set the new `hostname` as the `currentDomainName`.
2387 currentDomainName = hostName;
2389 // Reset `favoriteIconBitmap` and display it in the `appbar`.
2390 favoriteIconBitmap = favoriteIconDefaultBitmap;
2391 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
2393 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
2394 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2395 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2397 // Get a full cursor from `domainsDatabaseHelper`.
2398 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
2400 // Initialize `domainSettingsSet`.
2401 Set<String> domainSettingsSet = new HashSet<>();
2403 // Get the domain name column index.
2404 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
2406 // Populate `domainSettingsSet`.
2407 for (int i = 0; i < domainNameCursor.getCount(); i++) {
2408 // Move `domainsCursor` to the current row.
2409 domainNameCursor.moveToPosition(i);
2411 // Store the domain name in `domainSettingsSet`.
2412 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
2415 // Close `domainNameCursor.
2416 domainNameCursor.close();
2418 // Initialize variables to track if domain settings will be applied and, if so, under which name.
2419 domainSettingsApplied = false;
2420 String domainNameInDatabase = null;
2422 // Check the hostname.
2423 if (domainSettingsSet.contains(hostName)) {
2424 domainSettingsApplied = true;
2425 domainNameInDatabase = hostName;
2428 // If `hostName` is not `null`, check all the subdomains of `hostName` against wildcard domains in `domainCursor`.
2429 if (hostName != null) {
2430 while (hostName.contains(".") && !domainSettingsApplied) { // Stop checking if we run out of `.` or if we already know that `domainSettingsApplied` is `true`.
2431 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
2432 domainSettingsApplied = true;
2433 domainNameInDatabase = "*." + hostName;
2436 // Strip out the lowest subdomain of `host`.
2437 hostName = hostName.substring(hostName.indexOf(".") + 1);
2441 // Get a handle for the shared preference. `this` references the current context.
2442 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2444 if (domainSettingsApplied) { // The url we are loading has custom domain settings.
2445 // Get a cursor for the current host and move it to the first position.
2446 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
2447 currentHostDomainSettingsCursor.moveToFirst();
2449 // Get the settings from the cursor.
2450 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
2451 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
2452 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
2453 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
2454 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
2455 String userAgentString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
2456 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
2457 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
2459 // Close `currentHostDomainSettingsCursor`.
2460 currentHostDomainSettingsCursor.close();
2462 // Apply the domain settings.
2463 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2464 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2465 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2466 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2467 mainWebView.getSettings().setTextZoom(fontSize);
2469 // Set third-party cookies status if API >= 21.
2470 if (Build.VERSION.SDK_INT >= 21) {
2471 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2474 // Set the user agent.
2475 if (userAgentString.equals("WebView default user agent")) {
2476 // Set the user agent to `""`, which uses the default value.
2477 mainWebView.getSettings().setUserAgentString("");
2479 // Use the selected user agent.
2480 mainWebView.getSettings().setUserAgentString(userAgentString);
2483 // 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.
2485 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
2487 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
2489 } else { // The URL we are loading does not have custom domain settings. Load the defaults.
2490 // Store the values from `sharedPreferences` in variables.
2491 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
2492 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
2493 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
2494 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
2495 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
2496 String userAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
2497 String customUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
2498 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
2500 // Apply the default settings.
2501 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2502 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2503 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2504 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2505 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
2507 // Set third-party cookies status if API >= 21.
2508 if (Build.VERSION.SDK_INT >= 21) {
2509 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2512 // Set the default user agent.
2513 switch (userAgentString) {
2514 case "WebView default user agent":
2515 // Set the user agent to `""`, which uses the default value.
2516 mainWebView.getSettings().setUserAgentString("");
2519 case "Custom user agent":
2520 // Set the custom user agent.
2521 mainWebView.getSettings().setUserAgentString(customUserAgentString);
2525 // Use the selected user agent.
2526 mainWebView.getSettings().setUserAgentString(userAgentString);
2530 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2531 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.url_bar_background_transparent));
2534 // Close `domainsDatabaseHelper`.
2535 domainsDatabaseHelper.close();
2537 // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode. `true` indicates that custom domain settings are applied.
2538 onTheFlyDisplayImagesSet = false;
2539 setDisplayWebpageImages();
2541 // Update the privacy icons, but only if `mainMenu` has already been populated.
2542 if (mainMenu != null) {
2543 updatePrivacyIcons(true);
2548 private void setDisplayWebpageImages() {
2549 if (!onTheFlyDisplayImagesSet) {
2550 if (domainSettingsApplied) { // Custom domain settings are applied.
2551 switch (displayWebpageImagesInt) {
2552 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
2553 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
2556 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
2557 mainWebView.getSettings().setLoadsImagesAutomatically(true);
2560 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
2561 mainWebView.getSettings().setLoadsImagesAutomatically(false);
2564 } else { // Default settings are applied.
2565 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
2570 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
2571 // Get handles for the icons.
2572 MenuItem privacyIconMenuItem = mainMenu.findItem(R.id.toggle_javascript);
2573 MenuItem firstPartyCookiesIconMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
2574 MenuItem domStorageIconMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
2575 MenuItem formDataIconMenuItem = mainMenu.findItem(R.id.toggle_save_form_data);
2577 // Update `privacyIcon`.
2578 if (javaScriptEnabled) { // JavaScript is enabled.
2579 privacyIconMenuItem.setIcon(R.drawable.javascript_enabled);
2580 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
2581 privacyIconMenuItem.setIcon(R.drawable.warning);
2582 } else { // All the dangerous features are disabled.
2583 privacyIconMenuItem.setIcon(R.drawable.privacy_mode);
2586 // Update `firstPartyCookiesIcon`.
2587 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
2588 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_enabled);
2589 } else { // First-party cookies are disabled.
2590 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled);
2593 // Update `domStorageIcon`.
2594 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
2595 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_enabled);
2596 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
2597 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled);
2598 } else { // JavaScript is disabled, so DOM storage is ghosted.
2599 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted);
2602 // Update `formDataIcon`.
2603 if (saveFormDataEnabled) { // Form data is enabled.
2604 formDataIconMenuItem.setIcon(R.drawable.form_data_enabled);
2605 } else { // Form data is disabled.
2606 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled);
2609 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`. `this` references the current activity.
2610 if (runInvalidateOptionsMenu) {
2611 ActivityCompat.invalidateOptionsMenu(this);
2615 private void highlightUrlText() {
2616 String urlString = urlTextBox.getText().toString();
2618 if (urlString.startsWith("http://")) { // Highlight connections that are not encrypted.
2619 urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
2620 urlTextBox.getText().setSpan(boldStyleSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
2621 } else if (urlString.startsWith("https://")) { // Highlight connections that are encrypted.
2622 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
2625 // Get the index of the `/` immediately after the domain name.
2626 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
2628 // De-emphasize the text after the domain name.
2629 if (endOfDomainName > 0) {
2630 urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);