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.scrollTo(0, 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 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 // Get handles for the menu items.
1086 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1087 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1088 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1089 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1090 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1091 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);
1092 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1093 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1094 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1096 // Set the status of the menu item checkboxes.
1097 toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1098 toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1099 toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1100 toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);
1101 displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1103 // Enable third-party cookies if first-party cookies are enabled.
1104 toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1106 // Enable DOM Storage if JavaScript is enabled.
1107 toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
1109 // Enable Clear Cookies if there are any.
1110 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1112 // Enable Clear Form Data is there is any.
1113 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1114 clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
1116 // Initialize font size variables.
1117 int fontSize = mainWebView.getSettings().getTextZoom();
1118 String fontSizeTitle;
1119 MenuItem selectedFontSizeMenuItem;
1121 // Prepare the font size title and current size menu item.
1124 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.twenty_five_percent);
1125 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1129 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.fifty_percent);
1130 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1134 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.seventy_five_percent);
1135 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1139 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
1140 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1144 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_twenty_five_percent);
1145 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1149 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_fifty_percent);
1150 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1154 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_seventy_five_percent);
1155 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1159 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.two_hundred_percent);
1160 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1164 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
1165 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1169 // Set the font size title and select the current size menu item.
1170 fontSizeMenuItem.setTitle(fontSizeTitle);
1171 selectedFontSizeMenuItem.setChecked(true);
1173 // Only show `Refresh` if `swipeToRefresh` is disabled.
1174 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
1176 // Run all the other default commands.
1177 super.onPrepareOptionsMenu(menu);
1179 // `return true` displays the menu.
1184 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1185 @SuppressLint("SetJavaScriptEnabled")
1186 // removeAllCookies is deprecated, but it is required for API < 21.
1187 @SuppressWarnings("deprecation")
1188 public boolean onOptionsItemSelected(MenuItem menuItem) {
1189 int menuItemId = menuItem.getItemId();
1191 // Set the commands that relate to the menu entries.
1192 switch (menuItemId) {
1193 case R.id.toggle_javascript:
1194 // Switch the status of javaScriptEnabled.
1195 javaScriptEnabled = !javaScriptEnabled;
1197 // Apply the new JavaScript status.
1198 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1200 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1201 updatePrivacyIcons(true);
1203 // Display a `Snackbar`.
1204 if (javaScriptEnabled) { // JavaScrip is enabled.
1205 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1206 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
1207 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1208 } else { // Privacy mode.
1209 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1212 // Reload the WebView.
1213 mainWebView.reload();
1216 case R.id.toggle_first_party_cookies:
1217 // Switch the status of firstPartyCookiesEnabled.
1218 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1220 // Update the menu checkbox.
1221 menuItem.setChecked(firstPartyCookiesEnabled);
1223 // Apply the new cookie status.
1224 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1226 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1227 updatePrivacyIcons(true);
1229 // Display a `Snackbar`.
1230 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1231 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1232 } else if (javaScriptEnabled){ // JavaScript is still enabled.
1233 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1234 } else { // Privacy mode.
1235 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1238 // Reload the WebView.
1239 mainWebView.reload();
1242 case R.id.toggle_third_party_cookies:
1243 if (Build.VERSION.SDK_INT >= 21) {
1244 // Switch the status of thirdPartyCookiesEnabled.
1245 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1247 // Update the menu checkbox.
1248 menuItem.setChecked(thirdPartyCookiesEnabled);
1250 // Apply the new cookie status.
1251 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1253 // Display a `Snackbar`.
1254 if (thirdPartyCookiesEnabled) {
1255 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1257 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1260 // Reload the WebView.
1261 mainWebView.reload();
1262 } // Else do nothing because SDK < 21.
1265 case R.id.toggle_dom_storage:
1266 // Switch the status of domStorageEnabled.
1267 domStorageEnabled = !domStorageEnabled;
1269 // Update the menu checkbox.
1270 menuItem.setChecked(domStorageEnabled);
1272 // Apply the new DOM Storage status.
1273 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1275 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1276 updatePrivacyIcons(true);
1278 // Display a `Snackbar`.
1279 if (domStorageEnabled) {
1280 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1282 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1285 // Reload the WebView.
1286 mainWebView.reload();
1289 case R.id.toggle_save_form_data:
1290 // Switch the status of saveFormDataEnabled.
1291 saveFormDataEnabled = !saveFormDataEnabled;
1293 // Update the menu checkbox.
1294 menuItem.setChecked(saveFormDataEnabled);
1296 // Apply the new form data status.
1297 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1299 // Display a `Snackbar`.
1300 if (saveFormDataEnabled) {
1301 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1303 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1306 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1307 updatePrivacyIcons(true);
1309 // Reload the WebView.
1310 mainWebView.reload();
1313 case R.id.clear_cookies:
1314 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1315 .setAction(R.string.undo, new View.OnClickListener() {
1317 public void onClick(View v) {
1318 // Do nothing because everything will be handled by `onDismissed()` below.
1321 .addCallback(new Snackbar.Callback() {
1323 public void onDismissed(Snackbar snackbar, int event) {
1325 // The user pushed the `Undo` button.
1326 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1330 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1332 // `cookieManager.removeAllCookie()` varies by SDK.
1333 if (Build.VERSION.SDK_INT < 21) {
1334 cookieManager.removeAllCookie();
1336 // `null` indicates no callback.
1337 cookieManager.removeAllCookies(null);
1345 case R.id.clear_dom_storage:
1346 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1347 .setAction(R.string.undo, new View.OnClickListener() {
1349 public void onClick(View v) {
1350 // Do nothing because everything will be handled by `onDismissed()` below.
1353 .addCallback(new Snackbar.Callback() {
1355 public void onDismissed(Snackbar snackbar, int event) {
1357 // The user pushed the `Undo` button.
1358 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1362 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1364 // Delete the DOM Storage.
1365 WebStorage webStorage = WebStorage.getInstance();
1366 webStorage.deleteAllData();
1373 case R.id.clear_form_data:
1374 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1375 .setAction(R.string.undo, new View.OnClickListener() {
1377 public void onClick(View v) {
1378 // Do nothing because everything will be handled by `onDismissed()` below.
1381 .addCallback(new Snackbar.Callback() {
1383 public void onDismissed(Snackbar snackbar, int event) {
1385 // The user pushed the `Undo` button.
1386 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1390 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1392 // Delete the form data.
1393 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1394 mainWebViewDatabase.clearFormData();
1401 case R.id.font_size_twenty_five_percent:
1402 mainWebView.getSettings().setTextZoom(25);
1405 case R.id.font_size_fifty_percent:
1406 mainWebView.getSettings().setTextZoom(50);
1409 case R.id.font_size_seventy_five_percent:
1410 mainWebView.getSettings().setTextZoom(75);
1413 case R.id.font_size_one_hundred_percent:
1414 mainWebView.getSettings().setTextZoom(100);
1417 case R.id.font_size_one_hundred_twenty_five_percent:
1418 mainWebView.getSettings().setTextZoom(125);
1421 case R.id.font_size_one_hundred_fifty_percent:
1422 mainWebView.getSettings().setTextZoom(150);
1425 case R.id.font_size_one_hundred_seventy_five_percent:
1426 mainWebView.getSettings().setTextZoom(175);
1429 case R.id.font_size_two_hundred_percent:
1430 mainWebView.getSettings().setTextZoom(200);
1433 case R.id.display_images:
1434 if (mainWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1435 mainWebView.getSettings().setLoadsImagesAutomatically(false);
1436 mainWebView.reload();
1437 } else { // Images are not currently loaded automatically.
1438 mainWebView.getSettings().setLoadsImagesAutomatically(true);
1441 // Set `onTheFlyDisplayImagesSet`.
1442 onTheFlyDisplayImagesSet = true;
1446 // Setup the share string.
1448 if (webViewTitle != null) {
1449 shareString = webViewTitle + " – " + urlTextBox.getText().toString();
1451 shareString = urlTextBox.getText().toString();
1454 // Create the share intent.
1455 Intent shareIntent = new Intent();
1456 shareIntent.setAction(Intent.ACTION_SEND);
1457 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1458 shareIntent.setType("text/plain");
1461 startActivity(Intent.createChooser(shareIntent, "Share URL"));
1464 case R.id.find_on_page:
1465 // Hide the URL app bar.
1466 supportAppBar.setVisibility(View.GONE);
1468 // Show the Find on Page `RelativeLayout`.
1469 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1471 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android.
1472 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1473 findOnPageEditText.postDelayed(new Runnable()
1478 // Set the focus on `findOnPageEditText`.
1479 findOnPageEditText.requestFocus();
1481 // Display the keyboard.
1482 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1488 // Get a `PrintManager` instance.
1489 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1491 // Convert `mainWebView` to `printDocumentAdapter`.
1492 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
1494 // Print the document. The print attributes are `null`.
1495 printManager.print(getResources().getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1498 case R.id.add_to_homescreen:
1499 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
1500 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
1501 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.create_shortcut));
1503 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
1507 mainWebView.reload();
1511 // Don't consume the event.
1512 return super.onOptionsItemSelected(menuItem);
1516 // removeAllCookies is deprecated, but it is required for API < 21.
1517 @SuppressWarnings("deprecation")
1519 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1520 int menuItemId = menuItem.getItemId();
1522 switch (menuItemId) {
1528 if (mainWebView.canGoBack()) {
1529 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1530 navigatingHistory = true;
1532 // Load the previous website in the history.
1533 mainWebView.goBack();
1538 if (mainWebView.canGoForward()) {
1539 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1540 navigatingHistory = true;
1542 // Load the next website in the history.
1543 mainWebView.goForward();
1548 // Get the `WebBackForwardList`.
1549 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
1551 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
1552 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
1553 urlHistoryDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.history));
1556 case R.id.bookmarks:
1557 // Launch BookmarksActivity.
1558 Intent bookmarksIntent = new Intent(this, BookmarksActivity.class);
1559 startActivity(bookmarksIntent);
1562 case R.id.downloads:
1563 // Launch the system Download Manager.
1564 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1566 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1567 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1569 startActivity(downloadManagerIntent);
1573 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1574 currentDomainName = "";
1576 // Launch `SettingsActivity`.
1577 Intent settingsIntent = new Intent(this, SettingsActivity.class);
1578 startActivity(settingsIntent);
1582 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1583 currentDomainName = "";
1585 // Launch `DomainsActivity`.
1586 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1587 startActivity(domainsIntent);
1591 // Launch `GuideActivity`.
1592 Intent guideIntent = new Intent(this, GuideActivity.class);
1593 startActivity(guideIntent);
1597 // Launch `AboutActivity`.
1598 Intent aboutIntent = new Intent(this, AboutActivity.class);
1599 startActivity(aboutIntent);
1602 case R.id.clearAndExit:
1603 // Get a handle for `sharedPreferences`. `this` references the current context.
1604 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1606 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
1609 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
1610 // The command to remove cookies changed slightly in API 21.
1611 if (Build.VERSION.SDK_INT >= 21) {
1612 cookieManager.removeAllCookies(null);
1614 cookieManager.removeAllCookie();
1617 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1619 // We have to use two commands because `Runtime.exec()` does not like `*`.
1620 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
1621 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
1622 } catch (IOException e) {
1623 // Do nothing if an error is thrown.
1627 // Clear DOM storage.
1628 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
1629 // Ask `WebStorage` to clear the DOM storage.
1630 WebStorage webStorage = WebStorage.getInstance();
1631 webStorage.deleteAllData();
1633 // Manually delete the DOM storage directory, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1635 // We have to use a `String[]` because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1636 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1637 } catch (IOException e) {
1638 // Do nothing if an error is thrown.
1643 if (clearEverything || sharedPreferences.getBoolean("clear_form_data", true)) {
1644 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1645 webViewDatabase.clearFormData();
1647 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1649 // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1650 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
1651 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
1652 } catch (IOException e) {
1653 // Do nothing if an error is thrown.
1658 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
1659 // `true` includes disk files.
1660 mainWebView.clearCache(true);
1662 // Manually delete the cache directories.
1664 // Delete the main cache directory.
1665 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1667 // 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.
1668 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1669 } catch (IOException e) {
1670 // Do nothing if an error is thrown.
1674 // Clear SSL certificate preferences.
1675 mainWebView.clearSslPreferences();
1677 // Clear the back/forward history.
1678 mainWebView.clearHistory();
1680 // Clear `formattedUrlString`.
1681 formattedUrlString = null;
1683 // Clear `customHeaders`.
1684 customHeaders.clear();
1686 // Detach all views from `mainWebViewRelativeLayout`.
1687 mainWebViewRelativeLayout.removeAllViews();
1689 // Destroy the internal state of `mainWebView`.
1690 mainWebView.destroy();
1692 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
1693 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
1694 if (clearEverything) {
1696 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
1697 } catch (IOException e) {
1698 // Do nothing if an error is thrown.
1702 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
1703 if (Build.VERSION.SDK_INT >= 21) {
1704 finishAndRemoveTask();
1709 // Remove the terminated program from RAM. The status code is `0`.
1714 // Close the navigation drawer.
1715 drawerLayout.closeDrawer(GravityCompat.START);
1720 public void onPostCreate(Bundle savedInstanceState) {
1721 super.onPostCreate(savedInstanceState);
1723 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
1724 drawerToggle.syncState();
1728 public void onConfigurationChanged(Configuration newConfig) {
1729 super.onConfigurationChanged(newConfig);
1731 // Reload the ad for the free flavor if we are not in full screen mode.
1732 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
1734 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1736 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1737 adView = findViewById(R.id.adview);
1740 // `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
1741 // ActivityCompat.invalidateOptionsMenu(this);
1745 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
1746 // Store the `HitTestResult`.
1747 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
1750 final String imageUrl;
1751 final String linkUrl;
1753 // Get a handle for the `ClipboardManager`.
1754 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
1756 switch (hitTestResult.getType()) {
1757 // `SRC_ANCHOR_TYPE` is a link.
1758 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1759 // Get the target URL.
1760 linkUrl = hitTestResult.getExtra();
1762 // Set the target URL as the title of the `ContextMenu`.
1763 menu.setHeaderTitle(linkUrl);
1765 // Add a `Load URL` entry.
1766 menu.add(R.string.load_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1768 public boolean onMenuItemClick(MenuItem item) {
1774 // Add a `Copy URL` entry.
1775 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1777 public boolean onMenuItemClick(MenuItem item) {
1778 // Save the link URL in a `ClipData`.
1779 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), linkUrl);
1781 // Set the `ClipData` as the clipboard's primary clip.
1782 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
1787 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1788 menu.add(R.string.cancel);
1791 case WebView.HitTestResult.EMAIL_TYPE:
1792 // Get the target URL.
1793 linkUrl = hitTestResult.getExtra();
1795 // Set the target URL as the title of the `ContextMenu`.
1796 menu.setHeaderTitle(linkUrl);
1798 // Add a `Write Email` entry.
1799 menu.add(R.string.write_email).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1801 public boolean onMenuItemClick(MenuItem item) {
1802 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1803 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1805 // Parse the url and set it as the data for the `Intent`.
1806 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
1808 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
1809 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1812 startActivity(emailIntent);
1817 // Add a `Copy Email Address` entry.
1818 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1820 public boolean onMenuItemClick(MenuItem item) {
1821 // Save the email address in a `ClipData`.
1822 ClipData srcEmailTypeClipData = ClipData.newPlainText(getResources().getString(R.string.email_address), linkUrl);
1824 // Set the `ClipData` as the clipboard's primary clip.
1825 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
1830 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1831 menu.add(R.string.cancel);
1834 // `IMAGE_TYPE` is an image.
1835 case WebView.HitTestResult.IMAGE_TYPE:
1836 // Get the image URL.
1837 imageUrl = hitTestResult.getExtra();
1839 // Set the image URL as the title of the `ContextMenu`.
1840 menu.setHeaderTitle(imageUrl);
1842 // Add a `View Image` entry.
1843 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1845 public boolean onMenuItemClick(MenuItem item) {
1851 // Add a `Download Image` entry.
1852 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1854 public boolean onMenuItemClick(MenuItem item) {
1855 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
1856 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
1857 downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1862 // Add a `Copy URL` entry.
1863 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1865 public boolean onMenuItemClick(MenuItem item) {
1866 // Save the image URL in a `ClipData`.
1867 ClipData srcImageTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1869 // Set the `ClipData` as the clipboard's primary clip.
1870 clipboardManager.setPrimaryClip(srcImageTypeClipData);
1875 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1876 menu.add(R.string.cancel);
1880 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
1881 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1882 // Get the image URL.
1883 imageUrl = hitTestResult.getExtra();
1885 // Set the image URL as the title of the `ContextMenu`.
1886 menu.setHeaderTitle(imageUrl);
1888 // Add a `View Image` entry.
1889 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1891 public boolean onMenuItemClick(MenuItem item) {
1897 // Add a `Download Image` entry.
1898 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1900 public boolean onMenuItemClick(MenuItem item) {
1901 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
1902 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
1903 downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1908 // Add a `Copy URL` entry.
1909 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1911 public boolean onMenuItemClick(MenuItem item) {
1912 // Save the image URL in a `ClipData`.
1913 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1915 // Set the `ClipData` as the clipboard's primary clip.
1916 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
1921 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1922 menu.add(R.string.cancel);
1928 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
1929 // Get shortcutNameEditText from the alert dialog.
1930 EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
1932 // Create the bookmark shortcut based on formattedUrlString.
1933 Intent bookmarkShortcut = new Intent();
1934 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
1935 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
1937 // Place the bookmark shortcut on the home screen.
1938 Intent placeBookmarkShortcut = new Intent();
1939 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
1940 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
1941 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIconBitmap);
1942 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
1943 sendBroadcast(placeBookmarkShortcut);
1947 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
1948 // Download the image if it has an HTTP or HTTPS URI.
1949 if (imageUrl.startsWith("http")) {
1950 // Get a handle for the system `DOWNLOAD_SERVICE`.
1951 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
1953 // Parse `imageUrl`.
1954 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
1956 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
1957 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
1958 if (firstPartyCookiesEnabled) {
1959 // Get the cookies for `imageUrl`.
1960 String cookies = cookieManager.getCookie(imageUrl);
1962 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
1963 downloadRequest.addRequestHeader("Cookie", cookies);
1966 // Get the file name from `dialogFragment`.
1967 EditText downloadImageNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_image_name);
1968 String imageName = downloadImageNameEditText.getText().toString();
1970 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
1971 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `imageName`.
1972 downloadRequest.setDestinationInExternalFilesDir(this, "/", imageName);
1973 } else { // Only set the title using `imageName`.
1974 downloadRequest.setTitle(imageName);
1977 // Allow `MediaScanner` to index the download if it is a media file.
1978 downloadRequest.allowScanningByMediaScanner();
1980 // Add the URL as the description for the download.
1981 downloadRequest.setDescription(imageUrl);
1983 // Show the download notification after the download is completed.
1984 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
1986 // Initiate the download.
1987 downloadManager.enqueue(downloadRequest);
1988 } else { // The image is not an HTTP or HTTPS URI.
1989 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
1994 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
1995 // Download the file if it has an HTTP or HTTPS URI.
1996 if (downloadUrl.startsWith("http")) {
1998 // Get a handle for the system `DOWNLOAD_SERVICE`.
1999 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2001 // Parse `downloadUrl`.
2002 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
2004 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
2005 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2006 if (firstPartyCookiesEnabled) {
2007 // Get the cookies for `downloadUrl`.
2008 String cookies = cookieManager.getCookie(downloadUrl);
2010 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2011 downloadRequest.addRequestHeader("Cookie", cookies);
2014 // Get the file name from `dialogFragment`.
2015 EditText downloadFileNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_file_name);
2016 String fileName = downloadFileNameEditText.getText().toString();
2018 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
2019 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download location to `/sdcard/Android/data/com.stoutner.privacybrowser.standard/files` named `fileName`.
2020 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
2021 } else { // Only set the title using `fileName`.
2022 downloadRequest.setTitle(fileName);
2025 // Allow `MediaScanner` to index the download if it is a media file.
2026 downloadRequest.allowScanningByMediaScanner();
2028 // Add the URL as the description for the download.
2029 downloadRequest.setDescription(downloadUrl);
2031 // Show the download notification after the download is completed.
2032 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2034 // Initiate the download.
2035 downloadManager.enqueue(downloadRequest);
2036 } else { // The download is not an HTTP or HTTPS URI.
2037 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
2041 public void viewSslCertificate(View view) {
2042 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
2043 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
2044 viewSslCertificateDialogFragment.show(getFragmentManager(), getResources().getString(R.string.view_ssl_certificate));
2048 public void onSslErrorCancel() {
2049 sslErrorHandler.cancel();
2053 public void onSslErrorProceed() {
2054 sslErrorHandler.proceed();
2058 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
2059 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2060 navigatingHistory = true;
2062 // Load the history entry.
2063 mainWebView.goBackOrForward(moveBackOrForwardSteps);
2067 public void onClearHistory() {
2068 // Clear the history.
2069 mainWebView.clearHistory();
2072 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
2074 public void onBackPressed() {
2075 // Close the navigation drawer if it is available. GravityCompat.START is the drawer on the left on Left-to-Right layout text.
2076 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
2077 drawerLayout.closeDrawer(GravityCompat.START);
2079 // Load the previous URL if available.
2080 if (mainWebView.canGoBack()) {
2081 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2082 navigatingHistory = true;
2085 mainWebView.goBack();
2087 // Pass `onBackPressed()` to the system.
2088 super.onBackPressed();
2093 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
2094 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
2095 String unformattedUrlString = urlTextBox.getText().toString().trim();
2097 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
2098 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
2099 // Add `http://` at the beginning if it is missing. Otherwise the app will segfault.
2100 if (!unformattedUrlString.startsWith("http")) {
2101 unformattedUrlString = "http://" + unformattedUrlString;
2104 // Initialize `unformattedUrl`.
2105 URL unformattedUrl = null;
2107 // 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.
2109 unformattedUrl = new URL(unformattedUrlString);
2110 } catch (MalformedURLException e) {
2111 e.printStackTrace();
2114 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2115 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2116 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2117 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2118 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2119 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2122 Uri.Builder formattedUri = new Uri.Builder();
2123 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2125 // Decode `formattedUri` as a `String` in `UTF-8`.
2126 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
2128 // Sanitize the search input and convert it to a search.
2129 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2131 // Add the base search URL.
2132 formattedUrlString = searchURL + encodedUrlString;
2135 loadUrl(formattedUrlString);
2137 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
2138 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2142 private void loadUrl(String url) {
2143 // Apply any custom domain settings.
2144 applyDomainSettings(url);
2147 mainWebView.loadUrl(url, customHeaders);
2150 public void findPreviousOnPage(View view) {
2151 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
2152 mainWebView.findNext(false);
2155 public void findNextOnPage(View view) {
2156 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2157 mainWebView.findNext(true);
2160 public void closeFindOnPage(View view) {
2161 // Delete the contents of `find_on_page_edittext`.
2162 findOnPageEditText.setText(null);
2164 // Clear the highlighted phrases.
2165 mainWebView.clearMatches();
2167 // Hide the Find on Page `RelativeLayout`.
2168 findOnPageLinearLayout.setVisibility(View.GONE);
2170 // Show the URL app bar.
2171 supportAppBar.setVisibility(View.VISIBLE);
2173 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
2174 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2177 private void applyAppSettings() {
2178 // Get a handle for `sharedPreferences`. `this` references the current context.
2179 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2181 // Store the values from `sharedPreferences` in variables.
2182 String homepageString = sharedPreferences.getString("homepage", "https://start.duckduckgo.com");
2183 String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
2184 String torSearchString = sharedPreferences.getString("tor_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
2185 String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
2186 String searchString = sharedPreferences.getString("search", "https://duckduckgo.com/html/?q=");
2187 String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
2188 adBlockerEnabled = sharedPreferences.getBoolean("block_ads", true);
2189 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
2190 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
2191 boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
2192 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
2193 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
2194 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
2195 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh", false);
2196 displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
2198 // Set the homepage, search, and proxy options.
2199 if (proxyThroughOrbot) { // Set the Tor options.
2200 // Set `torHomepageString` as `homepage`.
2201 homepage = torHomepageString;
2203 // If formattedUrlString is null assign the homepage to it.
2204 if (formattedUrlString == null) {
2205 formattedUrlString = homepage;
2208 // Set the search URL.
2209 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
2210 searchURL = torSearchCustomURLString;
2211 } else { // Use the string from the pre-built list.
2212 searchURL = torSearchString;
2215 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
2216 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
2218 // Display a message to the user if we are waiting on Orbot.
2219 if (!orbotStatus.equals("ON")) {
2220 // Set `waitingForOrbot`.
2221 waitingForOrbot = true;
2223 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
2224 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
2226 } else { // Set the non-Tor options.
2227 // Set `homepageString` as `homepage`.
2228 homepage = homepageString;
2230 // If formattedUrlString is null assign the homepage to it.
2231 if (formattedUrlString == null) {
2232 formattedUrlString = homepage;
2235 // Set the search URL.
2236 if (searchString.equals("Custom URL")) { // Get the custom URL string.
2237 searchURL = searchCustomURLString;
2238 } else { // Use the string from the pre-built list.
2239 searchURL = searchString;
2242 // Reset the proxy to default. The host is `""` and the port is `"0"`.
2243 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
2245 // Reset `waitingForOrbot.
2246 waitingForOrbot = false;
2249 // Set swipe to refresh.
2250 swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
2252 // Set Do Not Track status.
2253 if (doNotTrackEnabled) {
2254 customHeaders.put("DNT", "1");
2256 customHeaders.remove("DNT");
2259 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
2260 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
2261 if (hideSystemBarsOnFullscreen) { // Hide everything.
2262 // Remove the translucent navigation setting if it is currently flagged.
2263 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2265 // Remove the translucent status bar overlay.
2266 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2268 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
2269 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
2271 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
2272 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
2273 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
2275 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
2276 } else { // Hide everything except the status and navigation bars.
2277 // Add the translucent status flag if it is unset.
2278 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2280 if (translucentNavigationBarOnFullscreen) {
2281 // Set the navigation bar to be translucent.
2282 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2284 // Set the navigation bar to be black.
2285 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2288 } else { // Switch to normal viewing mode.
2289 // Reset `inFullScreenBrowsingMode` to `false`.
2290 inFullScreenBrowsingMode = false;
2292 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
2293 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
2297 // Show the `BannerAd` in the free flavor.
2298 if (BuildConfig.FLAVOR.contentEquals("free")) {
2299 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
2300 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2302 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2303 adView = findViewById(R.id.adview);
2306 // Remove the translucent navigation bar flag if it is set.
2307 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2309 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
2310 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2312 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
2313 rootCoordinatorLayout.setSystemUiVisibility(0);
2315 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
2316 rootCoordinatorLayout.setFitsSystemWindows(true);
2320 // We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2321 @SuppressWarnings("deprecation")
2322 private void applyDomainSettings(String url) {
2323 // Reset `navigatingHistory`.
2324 navigatingHistory = false;
2326 // Parse the URL into a URI.
2327 Uri uri = Uri.parse(url);
2329 // Extract the domain from `uri`.
2330 String hostName = uri.getHost();
2332 // Initialize `loadingNewDomainName`.
2333 boolean loadingNewDomainName;
2335 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
2336 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
2337 //noinspection SimplifiableIfStatement
2338 if ((hostName == null) || (currentDomainName == null)) {
2339 loadingNewDomainName = true;
2340 } else { // Determine if `hostName` equals `currentDomainName`.
2341 loadingNewDomainName = !hostName.equals(currentDomainName);
2344 // 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.
2345 if (loadingNewDomainName) {
2346 // Set the new `hostname` as the `currentDomainName`.
2347 currentDomainName = hostName;
2349 // Reset `favoriteIconBitmap` and display it in the `appbar`.
2350 favoriteIconBitmap = favoriteIconDefaultBitmap;
2351 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
2353 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
2354 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2355 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2357 // Get a full cursor from `domainsDatabaseHelper`.
2358 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
2360 // Initialize `domainSettingsSet`.
2361 Set<String> domainSettingsSet = new HashSet<>();
2363 // Get the domain name column index.
2364 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
2366 // Populate `domainSettingsSet`.
2367 for (int i = 0; i < domainNameCursor.getCount(); i++) {
2368 // Move `domainsCursor` to the current row.
2369 domainNameCursor.moveToPosition(i);
2371 // Store the domain name in `domainSettingsSet`.
2372 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
2375 // Close `domainNameCursor.
2376 domainNameCursor.close();
2378 // Initialize variables to track if domain settings will be applied and, if so, under which name.
2379 domainSettingsApplied = false;
2380 String domainNameInDatabase = null;
2382 // Check the hostname.
2383 if (domainSettingsSet.contains(hostName)) {
2384 domainSettingsApplied = true;
2385 domainNameInDatabase = hostName;
2388 // If `hostName` is not `null`, check all the subdomains of `hostName` against wildcard domains in `domainCursor`.
2389 if (hostName != null) {
2390 while (hostName.contains(".") && !domainSettingsApplied) { // Stop checking if we run out of `.` or if we already know that `domainSettingsApplied` is `true`.
2391 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
2392 domainSettingsApplied = true;
2393 domainNameInDatabase = "*." + hostName;
2396 // Strip out the lowest subdomain of `host`.
2397 hostName = hostName.substring(hostName.indexOf(".") + 1);
2401 // Get a handle for the shared preference. `this` references the current context.
2402 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2404 if (domainSettingsApplied) { // The url we are loading has custom domain settings.
2405 // Get a cursor for the current host and move it to the first position.
2406 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
2407 currentHostDomainSettingsCursor.moveToFirst();
2409 // Get the settings from the cursor.
2410 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
2411 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
2412 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
2413 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
2414 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
2415 String userAgentString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
2416 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
2417 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
2419 // Close `currentHostDomainSettingsCursor`.
2420 currentHostDomainSettingsCursor.close();
2422 // Apply the domain settings.
2423 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2424 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2425 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2426 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2427 mainWebView.getSettings().setTextZoom(fontSize);
2429 // Set third-party cookies status if API >= 21.
2430 if (Build.VERSION.SDK_INT >= 21) {
2431 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2434 // Set the user agent.
2435 if (userAgentString.equals("WebView default user agent")) {
2436 // Set the user agent to `""`, which uses the default value.
2437 mainWebView.getSettings().setUserAgentString("");
2439 // Use the selected user agent.
2440 mainWebView.getSettings().setUserAgentString(userAgentString);
2443 // 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.
2444 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_green));
2445 } else { // The URL we are loading does not have custom domain settings. Load the defaults.
2446 // Store the values from `sharedPreferences` in variables.
2447 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
2448 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
2449 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
2450 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
2451 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
2452 String userAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
2453 String customUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
2454 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
2456 // Apply the default settings.
2457 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2458 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2459 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2460 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2461 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
2463 // Set third-party cookies status if API >= 21.
2464 if (Build.VERSION.SDK_INT >= 21) {
2465 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2468 // Set the default user agent.
2469 switch (userAgentString) {
2470 case "WebView default user agent":
2471 // Set the user agent to `""`, which uses the default value.
2472 mainWebView.getSettings().setUserAgentString("");
2475 case "Custom user agent":
2476 // Set the custom user agent.
2477 mainWebView.getSettings().setUserAgentString(customUserAgentString);
2481 // Use the selected user agent.
2482 mainWebView.getSettings().setUserAgentString(userAgentString);
2486 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2487 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.url_bar_background_transparent));
2490 // Close `domainsDatabaseHelper`.
2491 domainsDatabaseHelper.close();
2493 // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode. `true` indicates that custom domain settings are applied.
2494 onTheFlyDisplayImagesSet = false;
2495 setDisplayWebpageImages();
2497 // Update the privacy icons, but only if `mainMenu` has already been populated.
2498 if (mainMenu != null) {
2499 updatePrivacyIcons(true);
2504 private void setDisplayWebpageImages() {
2505 if (!onTheFlyDisplayImagesSet) {
2506 if (domainSettingsApplied) { // Custom domain settings are applied.
2507 switch (displayWebpageImagesInt) {
2508 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
2509 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
2512 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
2513 mainWebView.getSettings().setLoadsImagesAutomatically(true);
2516 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
2517 mainWebView.getSettings().setLoadsImagesAutomatically(false);
2520 } else { // Default settings are applied.
2521 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
2526 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
2527 // Get handles for the icons.
2528 MenuItem privacyIconMenuItem = mainMenu.findItem(R.id.toggle_javascript);
2529 MenuItem firstPartyCookiesIconMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
2530 MenuItem domStorageIconMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
2531 MenuItem formDataIconMenuItem = mainMenu.findItem(R.id.toggle_save_form_data);
2533 // Update `privacyIcon`.
2534 if (javaScriptEnabled) { // JavaScript is enabled.
2535 privacyIconMenuItem.setIcon(R.drawable.javascript_enabled);
2536 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
2537 privacyIconMenuItem.setIcon(R.drawable.warning);
2538 } else { // All the dangerous features are disabled.
2539 privacyIconMenuItem.setIcon(R.drawable.privacy_mode);
2542 // Update `firstPartyCookiesIcon`.
2543 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
2544 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_enabled);
2545 } else { // First-party cookies are disabled.
2546 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled);
2549 // Update `domStorageIcon`.
2550 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
2551 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_enabled);
2552 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
2553 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled);
2554 } else { // JavaScript is disabled, so DOM storage is ghosted.
2555 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted);
2558 // Update `formDataIcon`.
2559 if (saveFormDataEnabled) { // Form data is enabled.
2560 formDataIconMenuItem.setIcon(R.drawable.form_data_enabled);
2561 } else { // Form data is disabled.
2562 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled);
2565 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`. `this` references the current activity.
2566 if (runInvalidateOptionsMenu) {
2567 ActivityCompat.invalidateOptionsMenu(this);
2571 private void highlightUrlText() {
2572 String urlString = urlTextBox.getText().toString();
2574 if (urlString.startsWith("http://")) { // Highlight connections that are not encrypted.
2575 urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
2576 urlTextBox.getText().setSpan(boldStyleSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
2577 } else if (urlString.startsWith("https://")) { // Highlight connections that are encrypted.
2578 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
2581 // Get the index of the `/` immediately after the domain name.
2582 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
2584 // De-emphasize the text after the domain name.
2585 if (endOfDomainName > 0) {
2586 urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);