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 // `appBar` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applyAppSettings()`.
126 public static ActionBar appBar;
128 // `favoriteIconBitmap` is public static so it can be accessed from `CreateHomeScreenShortcutDialog`, `BookmarksActivity`, `CreateBookmarkDialog`, `CreateBookmarkFolderDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`, `ViewSslCertificateDialog`.
129 // It is also used in `onCreate()`, `onCreateHomeScreenShortcutCreate()`, and `applyDomainSettings`.
130 public static Bitmap favoriteIconBitmap;
132 // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`, `CreateBookmarkDialog`, and `AddDomainDialog`.
133 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
134 public static String formattedUrlString;
136 // `sslCertificate` is public static so it can be accessed from `ViewSslCertificateDialog`. It is also used in `onCreate()`.
137 public static SslCertificate sslCertificate;
139 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`.
140 public static String orbotStatus;
142 // `webViewTitle` is public static so it can be accessed from `CreateBookmarkDialog` and `CreateHomeScreenShortcutDialog`. It is also used in `onCreate()`.
143 public static String webViewTitle;
145 // `displayWebpageImagesBoolean` is public static so it can be accessed from `DomainSettingsFragment`. It is also used in `applyAppSettings()` and `applyDomainSettings()`.
146 public static boolean displayWebpageImagesBoolean;
148 // `reloadOnRestartBoolean` is public static so it can be accessed from `SettingsFragment`. It is also used in `onRestart()`
149 public static boolean reloadOnRestartBoolean;
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;
296 // 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.
297 @SuppressLint("SetJavaScriptEnabled")
298 // Remove Android Studio's warning about deprecations. We have to use the deprecated `getColor()` until API >= 23.
299 @SuppressWarnings("deprecation")
300 protected void onCreate(Bundle savedInstanceState) {
301 super.onCreate(savedInstanceState);
302 setContentView(R.layout.main_drawerlayout);
304 // Get a handle for `inputMethodManager`.
305 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
307 // We need to use the `SupportActionBar` from `android.support.v7.app.ActionBar` until the minimum API is >= 21.
308 supportAppBar = (Toolbar) findViewById(R.id.app_bar);
309 setSupportActionBar(supportAppBar);
310 appBar = getSupportActionBar();
312 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
313 assert appBar != null;
315 // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
316 appBar.setCustomView(R.layout.url_app_bar);
317 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
319 // Initialize the `ForegroundColorSpans` and `StyleSpan` for highlighting `urlTextBox`. We have to use the deprecated `getColor()` until API >= 23.
320 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
321 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
322 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
323 boldStyleSpan = new StyleSpan(Typeface.BOLD);
325 // Get a handle for `urlTextBox`.
326 urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.url_edittext);
328 // Remove the formatting from `urlTextBar` when the user is editing the text.
329 urlTextBox.setOnFocusChangeListener(new View.OnFocusChangeListener() {
331 public void onFocusChange(View v, boolean hasFocus) {
332 if (hasFocus) { // The user is editing `urlTextBox`.
333 // Remove the highlighting.
334 urlTextBox.getText().removeSpan(redColorSpan);
335 urlTextBox.getText().removeSpan(initialGrayColorSpan);
336 urlTextBox.getText().removeSpan(finalGrayColorSpan);
337 urlTextBox.getText().removeSpan(boldStyleSpan);
338 } else { // The user has stopped editing `urlTextBox`.
339 // Reapply the highlighting.
342 // Scroll to the beginning of the text.
343 urlTextBox.setScrollX(0);
348 // Set the `Go` button on the keyboard to load the URL in `urlTextBox`.
349 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
351 public boolean onKey(View v, int keyCode, KeyEvent event) {
352 // If the event is a key-down event on the `enter` button, load the URL.
353 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
354 // Load the URL into the mainWebView and consume the event.
356 loadUrlFromTextBox();
357 } catch (UnsupportedEncodingException e) {
360 // If the enter key was pressed, consume the event.
363 // If any other key was pressed, do not consume the event.
369 // Set `waitingForOrbotHTMLString`.
370 waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
372 // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
373 currentDomainName = "";
374 orbotStatus = "unknown";
375 waitingForOrbot = false;
377 // Create an Orbot status `BroadcastReceiver`.
378 BroadcastReceiver orbotStatusBroadcastReceiver = new BroadcastReceiver() {
380 public void onReceive(Context context, Intent intent) {
381 // Store the content of the status message in `orbotStatus`.
382 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
384 // If we are waiting on Orbot, load the website now that Orbot is connected.
385 if (orbotStatus.equals("ON") && waitingForOrbot) {
386 // Reset `waitingForOrbot`.
387 waitingForOrbot = false;
389 // Load `formattedUrlString
390 loadUrl(formattedUrlString);
395 // Register `orbotStatusBroadcastReceiver` on `this` context.
396 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
398 // Get handles for views that need to be accessed.
399 drawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout);
400 rootCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.root_coordinatorlayout);
401 mainWebViewRelativeLayout = (RelativeLayout) findViewById(R.id.main_webview_relativelayout);
402 mainWebView = (WebView) findViewById(R.id.main_webview);
403 findOnPageLinearLayout = (LinearLayout) findViewById(R.id.find_on_page_linearlayout);
404 findOnPageEditText = (EditText) findViewById(R.id.find_on_page_edittext);
405 fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.full_screen_video_framelayout);
406 urlAppBarRelativeLayout = (RelativeLayout) findViewById(R.id.url_app_bar_relativelayout);
407 favoriteIconImageView = (ImageView) findViewById(R.id.favorite_icon);
409 // Create a double-tap listener to toggle full-screen mode.
410 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
411 // Override `onDoubleTap()`. All other events are handled using the default settings.
413 public boolean onDoubleTap(MotionEvent event) {
414 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
415 // Toggle `inFullScreenBrowsingMode`.
416 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
418 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
419 // Hide the `appBar`.
422 // Hide the `BannerAd` in the free flavor.
423 if (BuildConfig.FLAVOR.contentEquals("free")) {
424 BannerAd.hideAd(adView);
427 // Modify the system bars.
428 if (hideSystemBarsOnFullscreen) { // Hide everything.
429 // Remove the translucent overlays.
430 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
432 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
433 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
435 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
436 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
437 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
439 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
441 // Set `rootCoordinatorLayout` to fill the whole screen.
442 rootCoordinatorLayout.setFitsSystemWindows(false);
443 } else { // Hide everything except the status and navigation bars.
444 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
445 rootCoordinatorLayout.setFitsSystemWindows(false);
447 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.
448 // Set the navigation bar to be translucent.
449 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
452 } else { // Switch to normal viewing mode.
453 // Show the `appBar`.
456 // Show the `BannerAd` in the free flavor.
457 if (BuildConfig.FLAVOR.contentEquals("free")) {
458 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
459 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
461 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
462 adView = findViewById(R.id.adview);
465 // Remove the translucent navigation bar flag if it is set.
466 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
468 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
469 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
471 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
472 rootCoordinatorLayout.setSystemUiVisibility(0);
474 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
475 rootCoordinatorLayout.setFitsSystemWindows(true);
478 // Consume the double-tap.
480 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
486 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
487 mainWebView.setOnTouchListener(new View.OnTouchListener() {
489 public boolean onTouch(View v, MotionEvent event) {
490 // Send the `event` to `gestureDetector`.
491 return gestureDetector.onTouchEvent(event);
495 // Update `findOnPageCountTextView`.
496 mainWebView.setFindListener(new WebView.FindListener() {
497 // Get a handle for `findOnPageCountTextView`.
498 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
501 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
502 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
503 // Set `findOnPageCountTextView` to `0/0`.
504 findOnPageCountTextView.setText(R.string.zero_of_zero);
505 } else if (isDoneCounting) { // There are matches.
506 // `activeMatchOrdinal` is zero-based.
507 int activeMatch = activeMatchOrdinal + 1;
509 // Set `findOnPageCountTextView`.
510 findOnPageCountTextView.setText(activeMatch + "/" + numberOfMatches);
515 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
516 findOnPageEditText.addTextChangedListener(new TextWatcher() {
518 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
523 public void onTextChanged(CharSequence s, int start, int before, int count) {
528 public void afterTextChanged(Editable s) {
529 // Search for the text in `mainWebView`.
530 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
534 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
535 findOnPageEditText.setOnKeyListener(new View.OnKeyListener() {
537 public boolean onKey(View v, int keyCode, KeyEvent event) {
538 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
539 // Hide the soft keyboard. `0` indicates no additional flags.
540 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
542 // Consume the event.
544 } else { // A different key was pressed.
545 // Do not consume the event.
551 // Implement swipe to refresh
552 swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refreshlayout);
553 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
554 swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
556 public void onRefresh() {
557 mainWebView.reload();
561 // `DrawerTitle` identifies the `DrawerLayout` in accessibility mode.
562 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
564 // Listen for touches on the navigation menu.
565 final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationview);
566 navigationView.setNavigationItemSelectedListener(this);
568 // 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.
569 final Menu navigationMenu = navigationView.getMenu();
570 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
571 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
572 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
574 // The `DrawerListener` allows us to update the Navigation Menu.
575 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
577 public void onDrawerSlide(View drawerView, float slideOffset) {
581 public void onDrawerOpened(View drawerView) {
585 public void onDrawerClosed(View drawerView) {
589 public void onDrawerStateChanged(int newState) {
590 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // The drawer is opening or closing.
591 // Update the `Back`, `Forward`, and `History` menu items.
592 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
593 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
594 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
596 // Hide the keyboard (if displayed) so we can see the navigation menu. `0` indicates no additional flags.
597 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
599 // Clear the focus from `urlTextBox` if it has it.
600 urlTextBox.clearFocus();
605 // drawerToggle creates the hamburger icon at the start of the AppBar.
606 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
608 // Initialize `adServerSet`.
609 final Set<String> adServersSet = new HashSet<>();
611 // Load the list of ad servers into memory.
613 // Load `pgl.yoyo.org_adservers.txt` into a `BufferedReader`.
614 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(getAssets().open("pgl.yoyo.org_adservers.txt")));
616 // Create a string for storing each ad server.
619 // Populate `adServersSet`.
620 while ((adServer = bufferedReader.readLine()) != null) {
621 adServersSet.add(adServer);
624 // Close `bufferedReader`.
625 bufferedReader.close();
626 } catch (IOException ioException) {
627 // We're pretty sure the asset exists, so we don't need to worry about the `IOException` ever being thrown.
630 mainWebView.setWebViewClient(new WebViewClient() {
631 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
632 // We have to use the deprecated `shouldOverrideUrlLoading` until API >= 24.
633 @SuppressWarnings("deprecation")
635 public boolean shouldOverrideUrlLoading(WebView view, String url) {
636 if (url.startsWith("mailto:")) { // Load the URL in an external email program because it begins with `mailto:`.
637 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
638 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
640 // Parse the url and set it as the data for the `Intent`.
641 emailIntent.setData(Uri.parse(url));
643 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
644 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
647 startActivity(emailIntent);
649 // Returning `true` indicates the application is handling the URL.
651 } else { // Load the URL in Privacy Browser.
652 // Apply the domain settings for the new URL.
653 applyDomainSettings(url);
655 // Returning `false` causes the current `WebView` to handle the URL and prevents it from adding redirects to the history list.
660 // Block ads. We have to use the deprecated `shouldInterceptRequest` until minimum API >= 21.
661 @SuppressWarnings("deprecation")
663 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
664 if (adBlockerEnabled) { // Block ads.
665 // Extract the host from `url`.
666 Uri requestUri = Uri.parse(url);
667 String requestHost = requestUri.getHost();
669 // Initialize a variable to track if this is an ad server.
670 boolean requestHostIsAdServer = false;
672 // Check all the subdomains of `requestHost` if it is not `null` against the ad server database.
673 if (requestHost != null) {
674 while (requestHost.contains(".") && !requestHostIsAdServer) { // Stop checking if we run out of `.` or if we already know that `requestHostIsAdServer` is `true`.
675 if (adServersSet.contains(requestHost)) {
676 requestHostIsAdServer = true;
679 // Strip out the lowest subdomain of `requestHost`.
680 requestHost = requestHost.substring(requestHost.indexOf(".") + 1);
684 if (requestHostIsAdServer) { // It is an ad server.
685 // Return an empty `WebResourceResponse`.
686 return new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
687 } else { // It is not an ad server.
688 // `return null` loads the requested resource.
691 } else { // Ad blocking is disabled.
692 // `return null` loads the requested resource.
697 // Update the URL in urlTextBox when the page starts to load.
699 public void onPageStarted(WebView view, String url, Bitmap favicon) {
700 // Reset `webViewTitle`
701 webViewTitle = getString(R.string.no_title);
703 // Check to see if we are waiting on Orbot.
704 if (!waitingForOrbot) { // We are not waiting on Orbot, so we need to process the URL.
705 // 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.
706 formattedUrlString = url;
708 // Display the formatted URL text.
709 urlTextBox.setText(formattedUrlString);
711 // Apply text highlighting to `urlTextBox`.
714 // Apply any custom domain settings if the URL was loaded by navigating history.
715 if (navigatingHistory) {
716 applyDomainSettings(url);
721 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
723 public void onPageFinished(WebView view, String url) {
724 // Clear the cache and history if Incognito Mode is enabled.
725 if (incognitoModeEnabled) {
726 // Clear the cache. `true` includes disk files.
727 mainWebView.clearCache(true);
729 // Clear the back/forward history.
730 mainWebView.clearHistory();
732 // Manually delete cache folders.
734 // Delete the main `cache` folder.
735 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
737 // 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`.
738 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
739 } catch (IOException e) {
740 // Do nothing if an error is thrown.
744 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
745 if (!waitingForOrbot) {
746 // Check to see if `WebView` has set `url` to be `about:blank`.
747 if (url.equals("about:blank")) { // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
748 // Set `formattedUrlString` to `""`.
749 formattedUrlString = "";
751 urlTextBox.setText(formattedUrlString);
753 // Request focus for `urlTextBox`.
754 urlTextBox.requestFocus();
756 // Display the keyboard.
757 inputMethodManager.showSoftInput(urlTextBox, 0);
759 // Apply the domain settings. This clears any settings from the previous domain.
760 applyDomainSettings(formattedUrlString);
761 } else { // `WebView` has loaded a webpage.
762 // Set `formattedUrlString`.
763 formattedUrlString = url;
765 // Only update `urlTextBox` if the user is not typing in it.
766 if (!urlTextBox.hasFocus()) {
767 // Display the formatted URL text.
768 urlTextBox.setText(formattedUrlString);
770 // Apply text highlighting to `urlTextBox`.
775 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog`.
776 sslCertificate = mainWebView.getCertificate();
780 // Handle SSL Certificate errors.
782 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
783 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
784 sslErrorHandler = handler;
786 // Display the SSL error `AlertDialog`.
787 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
788 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.ssl_certificate_error));
792 // Get a handle for the progress bar.
793 final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress_bar);
795 mainWebView.setWebChromeClient(new WebChromeClient() {
796 // Update the progress bar when a page is loading.
798 public void onProgressChanged(WebView view, int progress) {
799 progressBar.setProgress(progress);
800 if (progress < 100) {
801 progressBar.setVisibility(View.VISIBLE);
803 progressBar.setVisibility(View.GONE);
805 //Stop the `SwipeToRefresh` indicator if it is running
806 swipeRefreshLayout.setRefreshing(false);
810 // Set the favorite icon when it changes.
812 public void onReceivedIcon(WebView view, Bitmap icon) {
813 // Only update the favorite icon if the website has finished loading.
814 if (progressBar.getVisibility() == View.GONE) {
815 // Save a copy of the favorite icon.
816 favoriteIconBitmap = icon;
818 // Place the favorite icon in the appBar.
819 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
823 // Save a copy of the title when it changes.
825 public void onReceivedTitle(WebView view, String title) {
826 // Save a copy of the title.
827 webViewTitle = title;
830 // Enter full screen video
832 public void onShowCustomView(View view, CustomViewCallback callback) {
833 // Pause the ad if this is the free flavor.
834 if (BuildConfig.FLAVOR.contentEquals("free")) {
835 BannerAd.pauseAd(adView);
838 // Remove the translucent overlays.
839 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
841 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
842 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
844 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
845 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
846 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
848 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
850 // Set `rootCoordinatorLayout` to fill the entire screen.
851 rootCoordinatorLayout.setFitsSystemWindows(false);
853 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
854 fullScreenVideoFrameLayout.addView(view);
855 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
858 // Exit full screen video
859 public void onHideCustomView() {
860 // Hide `fullScreenVideoFrameLayout`.
861 fullScreenVideoFrameLayout.removeAllViews();
862 fullScreenVideoFrameLayout.setVisibility(View.GONE);
864 // Add the translucent status flag. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
865 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
867 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars. This also clears the `SYSTEM_UI` flags.
868 rootCoordinatorLayout.setFitsSystemWindows(true);
870 // Show the ad if this is the free flavor.
871 if (BuildConfig.FLAVOR.contentEquals("free")) {
872 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
873 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
875 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
876 adView = findViewById(R.id.adview);
881 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
882 registerForContextMenu(mainWebView);
884 // Allow the downloading of files.
885 mainWebView.setDownloadListener(new DownloadListener() {
887 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
888 // Show the `DownloadFileDialog` `AlertDialog` and name this instance `@string/download`.
889 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
890 downloadFileDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
894 // Allow pinch to zoom.
895 mainWebView.getSettings().setBuiltInZoomControls(true);
897 // Hide zoom controls.
898 mainWebView.getSettings().setDisplayZoomControls(false);
900 // Set `mainWebView` to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
901 mainWebView.getSettings().setUseWideViewPort(true);
903 // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
904 mainWebView.getSettings().setLoadWithOverviewMode(true);
906 // Initialize cookieManager.
907 cookieManager = CookieManager.getInstance();
909 // 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).
910 customHeaders.put("X-Requested-With", "");
912 // 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.
913 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
915 // Get the intent that started the app.
916 final Intent launchingIntent = getIntent();
918 // Extract the launching intent data as `launchingIntentUriData`.
919 final Uri launchingIntentUriData = launchingIntent.getData();
921 // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
922 if (launchingIntentUriData != null) {
923 formattedUrlString = launchingIntentUriData.toString();
926 // Get a handle for the `Runtime`.
927 privacyBrowserRuntime = Runtime.getRuntime();
929 // Store the application's private data directory.
930 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`.
932 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
933 inFullScreenBrowsingMode = false;
935 // Initialize AdView for the free flavor.
936 adView = findViewById(R.id.adview);
938 // Initialize the privacy settings variables.
939 javaScriptEnabled = false;
940 firstPartyCookiesEnabled = false;
941 thirdPartyCookiesEnabled = false;
942 domStorageEnabled = false;
943 saveFormDataEnabled = false;
945 // Initialize `webViewTitle`.
946 webViewTitle = getString(R.string.no_title);
948 // Initialize `favoriteIconBitmap`. We have to use `ContextCompat` until API >= 21.
949 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
950 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
951 favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
953 // If the favorite icon is null, load the default.
954 if (favoriteIconBitmap == null) {
955 favoriteIconBitmap = favoriteIconDefaultBitmap;
958 // Apply the app settings from the shared preferences.
961 // Load `formattedUrlString` if we are not waiting for Orbot to connect.
962 if (!waitingForOrbot) {
963 loadUrl(formattedUrlString);
968 protected void onNewIntent(Intent intent) {
969 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
972 if (intent.getData() != null) {
973 // Get the intent data and convert it to a string.
974 final Uri intentUriData = intent.getData();
975 formattedUrlString = intentUriData.toString();
978 // Close the navigation drawer if it is open.
979 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
980 drawerLayout.closeDrawer(GravityCompat.START);
984 loadUrl(formattedUrlString);
986 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
987 mainWebView.requestFocus();
991 public void onRestart() {
994 // Apply the app settings, which may have been changed in `SettingsActivity`.
997 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
998 updatePrivacyIcons(true);
1000 // Set the display webpage images mode.
1001 setDisplayWebpageImages();
1003 // Reload the webpage if displaying of images has been disabled in `SettingsFragment`.
1004 if (reloadOnRestartBoolean) {
1005 // Reload `mainWebView`.
1006 mainWebView.reload();
1008 // Reset `reloadOnRestartBoolean`.
1009 reloadOnRestartBoolean = false;
1013 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1015 public void onResume() {
1018 // Resume JavaScript (if enabled).
1019 mainWebView.resumeTimers();
1021 // Resume `mainWebView`.
1022 mainWebView.onResume();
1024 // Resume the adView for the free flavor.
1025 if (BuildConfig.FLAVOR.contentEquals("free")) {
1026 BannerAd.resumeAd(adView);
1031 public void onPause() {
1032 // Pause `mainWebView`.
1033 mainWebView.onPause();
1035 // Stop all JavaScript.
1036 mainWebView.pauseTimers();
1038 // Pause the adView or it will continue to consume resources in the background on the free flavor.
1039 if (BuildConfig.FLAVOR.contentEquals("free")) {
1040 BannerAd.pauseAd(adView);
1047 public boolean onCreateOptionsMenu(Menu menu) {
1048 // Inflate the menu; this adds items to the action bar if it is present.
1049 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1051 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1054 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1055 updatePrivacyIcons(false);
1057 // Get handles for the menu items.
1058 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1059 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1060 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1061 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1063 // Only display third-party cookies if SDK >= 21
1064 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1066 // Get the shared preference values. `this` references the current context.
1067 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1069 // Set the status of the additional app bar icons. The default is `false`.
1070 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
1071 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1072 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1073 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1074 } else { //Do not display the additional icons.
1075 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1076 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1077 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1084 public boolean onPrepareOptionsMenu(Menu menu) {
1085 // Hide the keyboard (if displayed) so we can see the options menu. `0` indicates no additional flags.
1086 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1088 // Get handles for the menu items.
1089 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1090 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1091 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1092 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1093 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1094 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);
1095 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1096 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1097 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1099 // Set the status of the menu item checkboxes.
1100 toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1101 toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1102 toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1103 toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);
1104 displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1106 // Enable third-party cookies if first-party cookies are enabled.
1107 toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1109 // Enable DOM Storage if JavaScript is enabled.
1110 toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
1112 // Enable Clear Cookies if there are any.
1113 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1115 // Enable Clear Form Data is there is any.
1116 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1117 clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
1119 // Initialize font size variables.
1120 int fontSize = mainWebView.getSettings().getTextZoom();
1121 String fontSizeTitle;
1122 MenuItem selectedFontSizeMenuItem;
1124 // Prepare the font size title and current size menu item.
1127 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.twenty_five_percent);
1128 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1132 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.fifty_percent);
1133 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1137 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.seventy_five_percent);
1138 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1142 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
1143 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1147 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_twenty_five_percent);
1148 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1152 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_fifty_percent);
1153 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1157 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_seventy_five_percent);
1158 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1162 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.two_hundred_percent);
1163 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1167 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
1168 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1172 // Set the font size title and select the current size menu item.
1173 fontSizeMenuItem.setTitle(fontSizeTitle);
1174 selectedFontSizeMenuItem.setChecked(true);
1176 // Only show `Refresh` if `swipeToRefresh` is disabled.
1177 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
1179 // Run all the other default commands.
1180 super.onPrepareOptionsMenu(menu);
1182 // `return true` displays the menu.
1187 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1188 @SuppressLint("SetJavaScriptEnabled")
1189 // removeAllCookies is deprecated, but it is required for API < 21.
1190 @SuppressWarnings("deprecation")
1191 public boolean onOptionsItemSelected(MenuItem menuItem) {
1192 int menuItemId = menuItem.getItemId();
1194 // Set the commands that relate to the menu entries.
1195 switch (menuItemId) {
1196 case R.id.toggle_javascript:
1197 // Switch the status of javaScriptEnabled.
1198 javaScriptEnabled = !javaScriptEnabled;
1200 // Apply the new JavaScript status.
1201 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1203 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1204 updatePrivacyIcons(true);
1206 // Display a `Snackbar`.
1207 if (javaScriptEnabled) { // JavaScrip is enabled.
1208 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1209 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
1210 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1211 } else { // Privacy mode.
1212 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1215 // Reload the WebView.
1216 mainWebView.reload();
1219 case R.id.toggle_first_party_cookies:
1220 // Switch the status of firstPartyCookiesEnabled.
1221 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1223 // Update the menu checkbox.
1224 menuItem.setChecked(firstPartyCookiesEnabled);
1226 // Apply the new cookie status.
1227 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1229 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1230 updatePrivacyIcons(true);
1232 // Display a `Snackbar`.
1233 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1234 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1235 } else if (javaScriptEnabled){ // JavaScript is still enabled.
1236 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1237 } else { // Privacy mode.
1238 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1241 // Reload the WebView.
1242 mainWebView.reload();
1245 case R.id.toggle_third_party_cookies:
1246 if (Build.VERSION.SDK_INT >= 21) {
1247 // Switch the status of thirdPartyCookiesEnabled.
1248 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1250 // Update the menu checkbox.
1251 menuItem.setChecked(thirdPartyCookiesEnabled);
1253 // Apply the new cookie status.
1254 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1256 // Display a `Snackbar`.
1257 if (thirdPartyCookiesEnabled) {
1258 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1260 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1263 // Reload the WebView.
1264 mainWebView.reload();
1265 } // Else do nothing because SDK < 21.
1268 case R.id.toggle_dom_storage:
1269 // Switch the status of domStorageEnabled.
1270 domStorageEnabled = !domStorageEnabled;
1272 // Update the menu checkbox.
1273 menuItem.setChecked(domStorageEnabled);
1275 // Apply the new DOM Storage status.
1276 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1278 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1279 updatePrivacyIcons(true);
1281 // Display a `Snackbar`.
1282 if (domStorageEnabled) {
1283 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1285 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1288 // Reload the WebView.
1289 mainWebView.reload();
1292 case R.id.toggle_save_form_data:
1293 // Switch the status of saveFormDataEnabled.
1294 saveFormDataEnabled = !saveFormDataEnabled;
1296 // Update the menu checkbox.
1297 menuItem.setChecked(saveFormDataEnabled);
1299 // Apply the new form data status.
1300 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1302 // Display a `Snackbar`.
1303 if (saveFormDataEnabled) {
1304 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1306 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1309 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1310 updatePrivacyIcons(true);
1312 // Reload the WebView.
1313 mainWebView.reload();
1316 case R.id.clear_cookies:
1317 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1318 .setAction(R.string.undo, new View.OnClickListener() {
1320 public void onClick(View v) {
1321 // Do nothing because everything will be handled by `onDismissed()` below.
1324 .addCallback(new Snackbar.Callback() {
1326 public void onDismissed(Snackbar snackbar, int event) {
1328 // The user pushed the `Undo` button.
1329 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1333 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1335 // `cookieManager.removeAllCookie()` varies by SDK.
1336 if (Build.VERSION.SDK_INT < 21) {
1337 cookieManager.removeAllCookie();
1339 // `null` indicates no callback.
1340 cookieManager.removeAllCookies(null);
1348 case R.id.clear_dom_storage:
1349 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1350 .setAction(R.string.undo, new View.OnClickListener() {
1352 public void onClick(View v) {
1353 // Do nothing because everything will be handled by `onDismissed()` below.
1356 .addCallback(new Snackbar.Callback() {
1358 public void onDismissed(Snackbar snackbar, int event) {
1360 // The user pushed the `Undo` button.
1361 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1365 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1367 // Delete the DOM Storage.
1368 WebStorage webStorage = WebStorage.getInstance();
1369 webStorage.deleteAllData();
1376 case R.id.clear_form_data:
1377 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1378 .setAction(R.string.undo, new View.OnClickListener() {
1380 public void onClick(View v) {
1381 // Do nothing because everything will be handled by `onDismissed()` below.
1384 .addCallback(new Snackbar.Callback() {
1386 public void onDismissed(Snackbar snackbar, int event) {
1388 // The user pushed the `Undo` button.
1389 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1393 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1395 // Delete the form data.
1396 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1397 mainWebViewDatabase.clearFormData();
1404 case R.id.font_size_twenty_five_percent:
1405 mainWebView.getSettings().setTextZoom(25);
1408 case R.id.font_size_fifty_percent:
1409 mainWebView.getSettings().setTextZoom(50);
1412 case R.id.font_size_seventy_five_percent:
1413 mainWebView.getSettings().setTextZoom(75);
1416 case R.id.font_size_one_hundred_percent:
1417 mainWebView.getSettings().setTextZoom(100);
1420 case R.id.font_size_one_hundred_twenty_five_percent:
1421 mainWebView.getSettings().setTextZoom(125);
1424 case R.id.font_size_one_hundred_fifty_percent:
1425 mainWebView.getSettings().setTextZoom(150);
1428 case R.id.font_size_one_hundred_seventy_five_percent:
1429 mainWebView.getSettings().setTextZoom(175);
1432 case R.id.font_size_two_hundred_percent:
1433 mainWebView.getSettings().setTextZoom(200);
1436 case R.id.display_images:
1437 if (mainWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1438 mainWebView.getSettings().setLoadsImagesAutomatically(false);
1439 mainWebView.reload();
1440 } else { // Images are not currently loaded automatically.
1441 mainWebView.getSettings().setLoadsImagesAutomatically(true);
1444 // Set `onTheFlyDisplayImagesSet`.
1445 onTheFlyDisplayImagesSet = true;
1449 // Setup the share string.
1451 if (webViewTitle != null) {
1452 shareString = webViewTitle + " – " + urlTextBox.getText().toString();
1454 shareString = urlTextBox.getText().toString();
1457 // Create the share intent.
1458 Intent shareIntent = new Intent();
1459 shareIntent.setAction(Intent.ACTION_SEND);
1460 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1461 shareIntent.setType("text/plain");
1464 startActivity(Intent.createChooser(shareIntent, "Share URL"));
1467 case R.id.find_on_page:
1468 // Hide the URL app bar.
1469 supportAppBar.setVisibility(View.GONE);
1471 // Show the Find on Page `RelativeLayout`.
1472 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1474 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android.
1475 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1476 findOnPageEditText.postDelayed(new Runnable()
1481 // Set the focus on `findOnPageEditText`.
1482 findOnPageEditText.requestFocus();
1484 // Display the keyboard.
1485 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1491 // Get a `PrintManager` instance.
1492 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1494 // Convert `mainWebView` to `printDocumentAdapter`.
1495 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
1497 // Print the document. The print attributes are `null`.
1498 printManager.print(getResources().getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1501 case R.id.add_to_homescreen:
1502 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
1503 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
1504 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.create_shortcut));
1506 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
1510 mainWebView.reload();
1514 // Don't consume the event.
1515 return super.onOptionsItemSelected(menuItem);
1519 // removeAllCookies is deprecated, but it is required for API < 21.
1520 @SuppressWarnings("deprecation")
1522 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1523 int menuItemId = menuItem.getItemId();
1525 switch (menuItemId) {
1531 if (mainWebView.canGoBack()) {
1532 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1533 navigatingHistory = true;
1535 // Load the previous website in the history.
1536 mainWebView.goBack();
1541 if (mainWebView.canGoForward()) {
1542 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1543 navigatingHistory = true;
1545 // Load the next website in the history.
1546 mainWebView.goForward();
1551 // Get the `WebBackForwardList`.
1552 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
1554 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
1555 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
1556 urlHistoryDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.history));
1559 case R.id.bookmarks:
1560 // Launch BookmarksActivity.
1561 Intent bookmarksIntent = new Intent(this, BookmarksActivity.class);
1562 startActivity(bookmarksIntent);
1565 case R.id.downloads:
1566 // Launch the system Download Manager.
1567 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1569 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1570 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1572 startActivity(downloadManagerIntent);
1576 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1577 currentDomainName = "";
1579 // Launch `SettingsActivity`.
1580 Intent settingsIntent = new Intent(this, SettingsActivity.class);
1581 startActivity(settingsIntent);
1585 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1586 currentDomainName = "";
1588 // Launch `DomainsActivity`.
1589 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1590 startActivity(domainsIntent);
1594 // Launch `GuideActivity`.
1595 Intent guideIntent = new Intent(this, GuideActivity.class);
1596 startActivity(guideIntent);
1600 // Launch `AboutActivity`.
1601 Intent aboutIntent = new Intent(this, AboutActivity.class);
1602 startActivity(aboutIntent);
1605 case R.id.clearAndExit:
1606 // Get a handle for `sharedPreferences`. `this` references the current context.
1607 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1609 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
1612 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
1613 // The command to remove cookies changed slightly in API 21.
1614 if (Build.VERSION.SDK_INT >= 21) {
1615 cookieManager.removeAllCookies(null);
1617 cookieManager.removeAllCookie();
1620 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1622 // We have to use two commands because `Runtime.exec()` does not like `*`.
1623 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
1624 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
1625 } catch (IOException e) {
1626 // Do nothing if an error is thrown.
1630 // Clear DOM storage.
1631 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
1632 // Ask `WebStorage` to clear the DOM storage.
1633 WebStorage webStorage = WebStorage.getInstance();
1634 webStorage.deleteAllData();
1636 // Manually delete the DOM storage directory, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1638 // We have to use a `String[]` because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1639 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1640 } catch (IOException e) {
1641 // Do nothing if an error is thrown.
1646 if (clearEverything || sharedPreferences.getBoolean("clear_form_data", true)) {
1647 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1648 webViewDatabase.clearFormData();
1650 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1652 // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1653 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
1654 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
1655 } catch (IOException e) {
1656 // Do nothing if an error is thrown.
1661 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
1662 // `true` includes disk files.
1663 mainWebView.clearCache(true);
1665 // Manually delete the cache directories.
1667 // Delete the main cache directory.
1668 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1670 // 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.
1671 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1672 } catch (IOException e) {
1673 // Do nothing if an error is thrown.
1677 // Clear SSL certificate preferences.
1678 mainWebView.clearSslPreferences();
1680 // Clear the back/forward history.
1681 mainWebView.clearHistory();
1683 // Clear `formattedUrlString`.
1684 formattedUrlString = null;
1686 // Clear `customHeaders`.
1687 customHeaders.clear();
1689 // Detach all views from `mainWebViewRelativeLayout`.
1690 mainWebViewRelativeLayout.removeAllViews();
1692 // Destroy the internal state of `mainWebView`.
1693 mainWebView.destroy();
1695 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
1696 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
1697 if (clearEverything) {
1699 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
1700 } catch (IOException e) {
1701 // Do nothing if an error is thrown.
1705 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
1706 if (Build.VERSION.SDK_INT >= 21) {
1707 finishAndRemoveTask();
1712 // Remove the terminated program from RAM. The status code is `0`.
1717 // Close the navigation drawer.
1718 drawerLayout.closeDrawer(GravityCompat.START);
1723 public void onPostCreate(Bundle savedInstanceState) {
1724 super.onPostCreate(savedInstanceState);
1726 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
1727 drawerToggle.syncState();
1731 public void onConfigurationChanged(Configuration newConfig) {
1732 super.onConfigurationChanged(newConfig);
1734 // Reload the ad for the free flavor if we are not in full screen mode.
1735 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
1737 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1739 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1740 adView = findViewById(R.id.adview);
1743 // `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
1744 // ActivityCompat.invalidateOptionsMenu(this);
1748 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
1749 // Store the `HitTestResult`.
1750 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
1753 final String imageUrl;
1754 final String linkUrl;
1756 // Get a handle for the `ClipboardManager`.
1757 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
1759 switch (hitTestResult.getType()) {
1760 // `SRC_ANCHOR_TYPE` is a link.
1761 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1762 // Get the target URL.
1763 linkUrl = hitTestResult.getExtra();
1765 // Set the target URL as the title of the `ContextMenu`.
1766 menu.setHeaderTitle(linkUrl);
1768 // Add a `Load URL` entry.
1769 menu.add(R.string.load_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1771 public boolean onMenuItemClick(MenuItem item) {
1777 // Add a `Copy URL` entry.
1778 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1780 public boolean onMenuItemClick(MenuItem item) {
1781 // Save the link URL in a `ClipData`.
1782 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), linkUrl);
1784 // Set the `ClipData` as the clipboard's primary clip.
1785 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
1790 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1791 menu.add(R.string.cancel);
1794 case WebView.HitTestResult.EMAIL_TYPE:
1795 // Get the target URL.
1796 linkUrl = hitTestResult.getExtra();
1798 // Set the target URL as the title of the `ContextMenu`.
1799 menu.setHeaderTitle(linkUrl);
1801 // Add a `Write Email` entry.
1802 menu.add(R.string.write_email).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1804 public boolean onMenuItemClick(MenuItem item) {
1805 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1806 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1808 // Parse the url and set it as the data for the `Intent`.
1809 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
1811 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
1812 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1815 startActivity(emailIntent);
1820 // Add a `Copy Email Address` entry.
1821 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1823 public boolean onMenuItemClick(MenuItem item) {
1824 // Save the email address in a `ClipData`.
1825 ClipData srcEmailTypeClipData = ClipData.newPlainText(getResources().getString(R.string.email_address), linkUrl);
1827 // Set the `ClipData` as the clipboard's primary clip.
1828 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
1833 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1834 menu.add(R.string.cancel);
1837 // `IMAGE_TYPE` is an image.
1838 case WebView.HitTestResult.IMAGE_TYPE:
1839 // Get the image URL.
1840 imageUrl = hitTestResult.getExtra();
1842 // Set the image URL as the title of the `ContextMenu`.
1843 menu.setHeaderTitle(imageUrl);
1845 // Add a `View Image` entry.
1846 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1848 public boolean onMenuItemClick(MenuItem item) {
1854 // Add a `Download Image` entry.
1855 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1857 public boolean onMenuItemClick(MenuItem item) {
1858 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
1859 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
1860 downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1865 // Add a `Copy URL` entry.
1866 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1868 public boolean onMenuItemClick(MenuItem item) {
1869 // Save the image URL in a `ClipData`.
1870 ClipData srcImageTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1872 // Set the `ClipData` as the clipboard's primary clip.
1873 clipboardManager.setPrimaryClip(srcImageTypeClipData);
1878 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1879 menu.add(R.string.cancel);
1883 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
1884 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1885 // Get the image URL.
1886 imageUrl = hitTestResult.getExtra();
1888 // Set the image URL as the title of the `ContextMenu`.
1889 menu.setHeaderTitle(imageUrl);
1891 // Add a `View Image` entry.
1892 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1894 public boolean onMenuItemClick(MenuItem item) {
1900 // Add a `Download Image` entry.
1901 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1903 public boolean onMenuItemClick(MenuItem item) {
1904 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
1905 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
1906 downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1911 // Add a `Copy URL` entry.
1912 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1914 public boolean onMenuItemClick(MenuItem item) {
1915 // Save the image URL in a `ClipData`.
1916 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1918 // Set the `ClipData` as the clipboard's primary clip.
1919 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
1924 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1925 menu.add(R.string.cancel);
1931 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
1932 // Get shortcutNameEditText from the alert dialog.
1933 EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
1935 // Create the bookmark shortcut based on formattedUrlString.
1936 Intent bookmarkShortcut = new Intent();
1937 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
1938 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
1940 // Place the bookmark shortcut on the home screen.
1941 Intent placeBookmarkShortcut = new Intent();
1942 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
1943 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
1944 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIconBitmap);
1945 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
1946 sendBroadcast(placeBookmarkShortcut);
1950 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
1951 // Download the image if it has an HTTP or HTTPS URI.
1952 if (imageUrl.startsWith("http")) {
1953 // Get a handle for the system `DOWNLOAD_SERVICE`.
1954 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
1956 // Parse `imageUrl`.
1957 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
1959 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
1960 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
1961 if (firstPartyCookiesEnabled) {
1962 // Get the cookies for `imageUrl`.
1963 String cookies = cookieManager.getCookie(imageUrl);
1965 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
1966 downloadRequest.addRequestHeader("Cookie", cookies);
1969 // Get the file name from `dialogFragment`.
1970 EditText downloadImageNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_image_name);
1971 String imageName = downloadImageNameEditText.getText().toString();
1973 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
1974 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `imageName`.
1975 downloadRequest.setDestinationInExternalFilesDir(this, "/", imageName);
1976 } else { // Only set the title using `imageName`.
1977 downloadRequest.setTitle(imageName);
1980 // Allow `MediaScanner` to index the download if it is a media file.
1981 downloadRequest.allowScanningByMediaScanner();
1983 // Add the URL as the description for the download.
1984 downloadRequest.setDescription(imageUrl);
1986 // Show the download notification after the download is completed.
1987 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
1989 // Initiate the download.
1990 downloadManager.enqueue(downloadRequest);
1991 } else { // The image is not an HTTP or HTTPS URI.
1992 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
1997 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
1998 // Download the file if it has an HTTP or HTTPS URI.
1999 if (downloadUrl.startsWith("http")) {
2001 // Get a handle for the system `DOWNLOAD_SERVICE`.
2002 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2004 // Parse `downloadUrl`.
2005 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
2007 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
2008 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2009 if (firstPartyCookiesEnabled) {
2010 // Get the cookies for `downloadUrl`.
2011 String cookies = cookieManager.getCookie(downloadUrl);
2013 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2014 downloadRequest.addRequestHeader("Cookie", cookies);
2017 // Get the file name from `dialogFragment`.
2018 EditText downloadFileNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_file_name);
2019 String fileName = downloadFileNameEditText.getText().toString();
2021 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
2022 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download location to `/sdcard/Android/data/com.stoutner.privacybrowser.standard/files` named `fileName`.
2023 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
2024 } else { // Only set the title using `fileName`.
2025 downloadRequest.setTitle(fileName);
2028 // Allow `MediaScanner` to index the download if it is a media file.
2029 downloadRequest.allowScanningByMediaScanner();
2031 // Add the URL as the description for the download.
2032 downloadRequest.setDescription(downloadUrl);
2034 // Show the download notification after the download is completed.
2035 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2037 // Initiate the download.
2038 downloadManager.enqueue(downloadRequest);
2039 } else { // The download is not an HTTP or HTTPS URI.
2040 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
2044 public void viewSslCertificate(View view) {
2045 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
2046 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
2047 viewSslCertificateDialogFragment.show(getFragmentManager(), getResources().getString(R.string.view_ssl_certificate));
2051 public void onSslErrorCancel() {
2052 sslErrorHandler.cancel();
2056 public void onSslErrorProceed() {
2057 sslErrorHandler.proceed();
2061 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
2062 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2063 navigatingHistory = true;
2065 // Load the history entry.
2066 mainWebView.goBackOrForward(moveBackOrForwardSteps);
2070 public void onClearHistory() {
2071 // Clear the history.
2072 mainWebView.clearHistory();
2075 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
2077 public void onBackPressed() {
2078 // Close the navigation drawer if it is available. GravityCompat.START is the drawer on the left on Left-to-Right layout text.
2079 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
2080 drawerLayout.closeDrawer(GravityCompat.START);
2082 // Load the previous URL if available.
2083 if (mainWebView.canGoBack()) {
2084 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2085 navigatingHistory = true;
2088 mainWebView.goBack();
2090 // Pass `onBackPressed()` to the system.
2091 super.onBackPressed();
2096 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
2097 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
2098 String unformattedUrlString = urlTextBox.getText().toString().trim();
2100 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
2101 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
2102 // Add `http://` at the beginning if it is missing. Otherwise the app will segfault.
2103 if (!unformattedUrlString.startsWith("http")) {
2104 unformattedUrlString = "http://" + unformattedUrlString;
2107 // Initialize `unformattedUrl`.
2108 URL unformattedUrl = null;
2110 // 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.
2112 unformattedUrl = new URL(unformattedUrlString);
2113 } catch (MalformedURLException e) {
2114 e.printStackTrace();
2117 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2118 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2119 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2120 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2121 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2122 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2125 Uri.Builder formattedUri = new Uri.Builder();
2126 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2128 // Decode `formattedUri` as a `String` in `UTF-8`.
2129 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
2131 // Sanitize the search input and convert it to a search.
2132 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2134 // Add the base search URL.
2135 formattedUrlString = searchURL + encodedUrlString;
2138 loadUrl(formattedUrlString);
2140 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
2141 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2145 private void loadUrl(String url) {
2146 // Apply any custom domain settings.
2147 applyDomainSettings(url);
2150 mainWebView.loadUrl(url, customHeaders);
2153 public void findPreviousOnPage(View view) {
2154 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
2155 mainWebView.findNext(false);
2158 public void findNextOnPage(View view) {
2159 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2160 mainWebView.findNext(true);
2163 public void closeFindOnPage(View view) {
2164 // Delete the contents of `find_on_page_edittext`.
2165 findOnPageEditText.setText(null);
2167 // Clear the highlighted phrases.
2168 mainWebView.clearMatches();
2170 // Hide the Find on Page `RelativeLayout`.
2171 findOnPageLinearLayout.setVisibility(View.GONE);
2173 // Show the URL app bar.
2174 supportAppBar.setVisibility(View.VISIBLE);
2176 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
2177 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2180 private void applyAppSettings() {
2181 // Get a handle for `sharedPreferences`. `this` references the current context.
2182 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2184 // Store the values from `sharedPreferences` in variables.
2185 String homepageString = sharedPreferences.getString("homepage", "https://start.duckduckgo.com");
2186 String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
2187 String torSearchString = sharedPreferences.getString("tor_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
2188 String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
2189 String searchString = sharedPreferences.getString("search", "https://duckduckgo.com/html/?q=");
2190 String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
2191 adBlockerEnabled = sharedPreferences.getBoolean("block_ads", true);
2192 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
2193 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
2194 boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
2195 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
2196 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
2197 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
2198 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh", false);
2199 displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
2201 // Set the homepage, search, and proxy options.
2202 if (proxyThroughOrbot) { // Set the Tor options.
2203 // Set `torHomepageString` as `homepage`.
2204 homepage = torHomepageString;
2206 // If formattedUrlString is null assign the homepage to it.
2207 if (formattedUrlString == null) {
2208 formattedUrlString = homepage;
2211 // Set the search URL.
2212 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
2213 searchURL = torSearchCustomURLString;
2214 } else { // Use the string from the pre-built list.
2215 searchURL = torSearchString;
2218 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
2219 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
2221 // Display a message to the user if we are waiting on Orbot.
2222 if (!orbotStatus.equals("ON")) {
2223 // Set `waitingForOrbot`.
2224 waitingForOrbot = true;
2226 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
2227 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
2229 } else { // Set the non-Tor options.
2230 // Set `homepageString` as `homepage`.
2231 homepage = homepageString;
2233 // If formattedUrlString is null assign the homepage to it.
2234 if (formattedUrlString == null) {
2235 formattedUrlString = homepage;
2238 // Set the search URL.
2239 if (searchString.equals("Custom URL")) { // Get the custom URL string.
2240 searchURL = searchCustomURLString;
2241 } else { // Use the string from the pre-built list.
2242 searchURL = searchString;
2245 // Reset the proxy to default. The host is `""` and the port is `"0"`.
2246 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
2248 // Reset `waitingForOrbot.
2249 waitingForOrbot = false;
2252 // Set swipe to refresh.
2253 swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
2255 // Set Do Not Track status.
2256 if (doNotTrackEnabled) {
2257 customHeaders.put("DNT", "1");
2259 customHeaders.remove("DNT");
2262 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
2263 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
2264 if (hideSystemBarsOnFullscreen) { // Hide everything.
2265 // Remove the translucent navigation setting if it is currently flagged.
2266 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2268 // Remove the translucent status bar overlay.
2269 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2271 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
2272 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
2274 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
2275 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
2276 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
2278 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
2279 } else { // Hide everything except the status and navigation bars.
2280 // Add the translucent status flag if it is unset.
2281 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2283 if (translucentNavigationBarOnFullscreen) {
2284 // Set the navigation bar to be translucent.
2285 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2287 // Set the navigation bar to be black.
2288 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2291 } else { // Switch to normal viewing mode.
2292 // Reset `inFullScreenBrowsingMode` to `false`.
2293 inFullScreenBrowsingMode = false;
2295 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
2296 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
2300 // Show the `BannerAd` in the free flavor.
2301 if (BuildConfig.FLAVOR.contentEquals("free")) {
2302 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
2303 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2305 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2306 adView = findViewById(R.id.adview);
2309 // Remove the translucent navigation bar flag if it is set.
2310 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2312 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
2313 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2315 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
2316 rootCoordinatorLayout.setSystemUiVisibility(0);
2318 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
2319 rootCoordinatorLayout.setFitsSystemWindows(true);
2323 // We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2324 @SuppressWarnings("deprecation")
2325 private void applyDomainSettings(String url) {
2326 // Reset `navigatingHistory`.
2327 navigatingHistory = false;
2329 // Parse the URL into a URI.
2330 Uri uri = Uri.parse(url);
2332 // Extract the domain from `uri`.
2333 String hostName = uri.getHost();
2335 // Initialize `loadingNewDomainName`.
2336 boolean loadingNewDomainName;
2338 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
2339 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
2340 //noinspection SimplifiableIfStatement
2341 if ((hostName == null) || (currentDomainName == null)) {
2342 loadingNewDomainName = true;
2343 } else { // Determine if `hostName` equals `currentDomainName`.
2344 loadingNewDomainName = !hostName.equals(currentDomainName);
2347 // 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.
2348 if (loadingNewDomainName) {
2349 // Set the new `hostname` as the `currentDomainName`.
2350 currentDomainName = hostName;
2352 // Reset `favoriteIconBitmap` and display it in the `appbar`.
2353 favoriteIconBitmap = favoriteIconDefaultBitmap;
2354 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
2356 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
2357 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2358 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2360 // Get a full cursor from `domainsDatabaseHelper`.
2361 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
2363 // Initialize `domainSettingsSet`.
2364 Set<String> domainSettingsSet = new HashSet<>();
2366 // Get the domain name column index.
2367 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
2369 // Populate `domainSettingsSet`.
2370 for (int i = 0; i < domainNameCursor.getCount(); i++) {
2371 // Move `domainsCursor` to the current row.
2372 domainNameCursor.moveToPosition(i);
2374 // Store the domain name in `domainSettingsSet`.
2375 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
2378 // Close `domainNameCursor.
2379 domainNameCursor.close();
2381 // Initialize variables to track if domain settings will be applied and, if so, under which name.
2382 domainSettingsApplied = false;
2383 String domainNameInDatabase = null;
2385 // Check the hostname.
2386 if (domainSettingsSet.contains(hostName)) {
2387 domainSettingsApplied = true;
2388 domainNameInDatabase = hostName;
2391 // If `hostName` is not `null`, check all the subdomains of `hostName` against wildcard domains in `domainCursor`.
2392 if (hostName != null) {
2393 while (hostName.contains(".") && !domainSettingsApplied) { // Stop checking if we run out of `.` or if we already know that `domainSettingsApplied` is `true`.
2394 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
2395 domainSettingsApplied = true;
2396 domainNameInDatabase = "*." + hostName;
2399 // Strip out the lowest subdomain of `host`.
2400 hostName = hostName.substring(hostName.indexOf(".") + 1);
2404 // Get a handle for the shared preference. `this` references the current context.
2405 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2407 if (domainSettingsApplied) { // The url we are loading has custom domain settings.
2408 // Get a cursor for the current host and move it to the first position.
2409 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
2410 currentHostDomainSettingsCursor.moveToFirst();
2412 // Get the settings from the cursor.
2413 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
2414 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
2415 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
2416 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
2417 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
2418 String userAgentString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
2419 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
2420 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
2422 // Close `currentHostDomainSettingsCursor`.
2423 currentHostDomainSettingsCursor.close();
2425 // Apply the domain settings.
2426 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2427 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2428 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2429 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2430 mainWebView.getSettings().setTextZoom(fontSize);
2432 // Set third-party cookies status if API >= 21.
2433 if (Build.VERSION.SDK_INT >= 21) {
2434 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2437 // Set the user agent.
2438 if (userAgentString.equals("WebView default user agent")) {
2439 // Set the user agent to `""`, which uses the default value.
2440 mainWebView.getSettings().setUserAgentString("");
2442 // Use the selected user agent.
2443 mainWebView.getSettings().setUserAgentString(userAgentString);
2446 // 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.
2447 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_green));
2448 } else { // The URL we are loading does not have custom domain settings. Load the defaults.
2449 // Store the values from `sharedPreferences` in variables.
2450 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
2451 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
2452 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
2453 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
2454 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
2455 String userAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
2456 String customUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
2457 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
2459 // Apply the default settings.
2460 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2461 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2462 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2463 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2464 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
2466 // Set third-party cookies status if API >= 21.
2467 if (Build.VERSION.SDK_INT >= 21) {
2468 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2471 // Set the default user agent.
2472 switch (userAgentString) {
2473 case "WebView default user agent":
2474 // Set the user agent to `""`, which uses the default value.
2475 mainWebView.getSettings().setUserAgentString("");
2478 case "Custom user agent":
2479 // Set the custom user agent.
2480 mainWebView.getSettings().setUserAgentString(customUserAgentString);
2484 // Use the selected user agent.
2485 mainWebView.getSettings().setUserAgentString(userAgentString);
2489 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2490 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.url_bar_background_transparent));
2493 // Close `domainsDatabaseHelper`.
2494 domainsDatabaseHelper.close();
2496 // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode. `true` indicates that custom domain settings are applied.
2497 onTheFlyDisplayImagesSet = false;
2498 setDisplayWebpageImages();
2500 // Update the privacy icons, but only if `mainMenu` has already been populated.
2501 if (mainMenu != null) {
2502 updatePrivacyIcons(true);
2507 private void setDisplayWebpageImages() {
2508 if (!onTheFlyDisplayImagesSet) {
2509 if (domainSettingsApplied) { // Custom domain settings are applied.
2510 switch (displayWebpageImagesInt) {
2511 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
2512 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
2515 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
2516 mainWebView.getSettings().setLoadsImagesAutomatically(true);
2519 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
2520 mainWebView.getSettings().setLoadsImagesAutomatically(false);
2523 } else { // Default settings are applied.
2524 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
2529 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
2530 // Get handles for the icons.
2531 MenuItem privacyIconMenuItem = mainMenu.findItem(R.id.toggle_javascript);
2532 MenuItem firstPartyCookiesIconMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
2533 MenuItem domStorageIconMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
2534 MenuItem formDataIconMenuItem = mainMenu.findItem(R.id.toggle_save_form_data);
2536 // Update `privacyIcon`.
2537 if (javaScriptEnabled) { // JavaScript is enabled.
2538 privacyIconMenuItem.setIcon(R.drawable.javascript_enabled);
2539 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
2540 privacyIconMenuItem.setIcon(R.drawable.warning);
2541 } else { // All the dangerous features are disabled.
2542 privacyIconMenuItem.setIcon(R.drawable.privacy_mode);
2545 // Update `firstPartyCookiesIcon`.
2546 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
2547 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_enabled);
2548 } else { // First-party cookies are disabled.
2549 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled);
2552 // Update `domStorageIcon`.
2553 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
2554 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_enabled);
2555 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
2556 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled);
2557 } else { // JavaScript is disabled, so DOM storage is ghosted.
2558 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted);
2561 // Update `formDataIcon`.
2562 if (saveFormDataEnabled) { // Form data is enabled.
2563 formDataIconMenuItem.setIcon(R.drawable.form_data_enabled);
2564 } else { // Form data is disabled.
2565 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled);
2568 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`. `this` references the current activity.
2569 if (runInvalidateOptionsMenu) {
2570 ActivityCompat.invalidateOptionsMenu(this);
2574 private void highlightUrlText() {
2575 String urlString = urlTextBox.getText().toString();
2577 if (urlString.startsWith("http://")) { // Highlight connections that are not encrypted.
2578 urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
2579 urlTextBox.getText().setSpan(boldStyleSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
2580 } else if (urlString.startsWith("https://")) { // Highlight connections that are encrypted.
2581 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
2584 // Get the index of the `/` immediately after the domain name.
2585 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
2587 // De-emphasize the text after the domain name.
2588 if (endOfDomainName > 0) {
2589 urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);