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.SpannableStringBuilder;
64 import android.text.Spanned;
65 import android.text.TextWatcher;
66 import android.text.style.ForegroundColorSpan;
67 import android.text.style.StyleSpan;
68 import android.util.Patterns;
69 import android.view.ContextMenu;
70 import android.view.GestureDetector;
71 import android.view.KeyEvent;
72 import android.view.Menu;
73 import android.view.MenuItem;
74 import android.view.MotionEvent;
75 import android.view.View;
76 import android.view.WindowManager;
77 import android.view.inputmethod.InputMethodManager;
78 import android.webkit.CookieManager;
79 import android.webkit.DownloadListener;
80 import android.webkit.SslErrorHandler;
81 import android.webkit.WebBackForwardList;
82 import android.webkit.WebChromeClient;
83 import android.webkit.WebResourceResponse;
84 import android.webkit.WebStorage;
85 import android.webkit.WebView;
86 import android.webkit.WebViewClient;
87 import android.webkit.WebViewDatabase;
88 import android.widget.EditText;
89 import android.widget.FrameLayout;
90 import android.widget.ImageView;
91 import android.widget.LinearLayout;
92 import android.widget.ProgressBar;
93 import android.widget.RelativeLayout;
94 import android.widget.TextView;
96 import com.stoutner.privacybrowser.BannerAd;
97 import com.stoutner.privacybrowser.BuildConfig;
98 import com.stoutner.privacybrowser.R;
99 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
100 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
101 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
102 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
103 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
104 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
105 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
106 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
108 import java.io.BufferedReader;
109 import java.io.ByteArrayInputStream;
110 import java.io.IOException;
111 import java.io.InputStreamReader;
112 import java.io.UnsupportedEncodingException;
113 import java.net.MalformedURLException;
115 import java.net.URLDecoder;
116 import java.net.URLEncoder;
117 import java.util.HashMap;
118 import java.util.HashSet;
119 import java.util.Map;
120 import java.util.Set;
122 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
123 public class MainWebViewActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, CreateHomeScreenShortcutDialog.CreateHomeScreenSchortcutListener,
124 SslCertificateErrorDialog.SslCertificateErrorListener, DownloadFileDialog.DownloadFileListener, DownloadImageDialog.DownloadImageListener, UrlHistoryDialog.UrlHistoryListener {
126 // `appBar` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applyAppSettings()`.
127 public static ActionBar appBar;
129 // `favoriteIconBitmap` is public static so it can be accessed from `CreateHomeScreenShortcutDialog`, `BookmarksActivity`, `CreateBookmarkDialog`, `CreateBookmarkFolderDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`, `ViewSslCertificateDialog`.
130 // It is also used in `onCreate()`, `onCreateHomeScreenShortcutCreate()`, and `applyDomainSettings`.
131 public static Bitmap favoriteIconBitmap;
133 // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`, `CreateBookmarkDialog`, and `AddDomainDialog`.
134 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
135 public static String formattedUrlString;
137 // `sslCertificate` is public static so it can be accessed from `ViewSslCertificateDialog`. It is also used in `onCreate()`.
138 public static SslCertificate sslCertificate;
140 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`.
141 public static String orbotStatus;
143 // `webViewTitle` is public static so it can be accessed from `CreateBookmarkDialog` and `CreateHomeScreenShortcutDialog`. It is also used in `onCreate()`.
144 public static String webViewTitle;
146 // `displayWebpageImagesBoolean` is public static so it can be accessed from `DomainSettingsFragment`. It is also used in `applyAppSettings()` and `applyDomainSettings()`.
147 public static boolean displayWebpageImagesBoolean;
149 // `reloadOnRestartBoolean` is public static so it can be accessed from `SettingsFragment`. It is also used in `onRestart()`
150 public static boolean reloadOnRestartBoolean;
153 // `navigatingHistory` is used in `onCreate()`, `onNavigationItemSelected()`, and `applyDomainSettings()`.
154 private boolean navigatingHistory;
156 // `favoriteIconDefaultBitmap` is used in `onCreate()` and `applyDomainSettings`.
157 private Bitmap favoriteIconDefaultBitmap;
159 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, and `onBackPressed()`.
160 private DrawerLayout drawerLayout;
162 // `rootCoordinatorLayout` is used in `onCreate()` and `applyAppSettings()`.
163 private CoordinatorLayout rootCoordinatorLayout;
165 // `mainWebView` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`, `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`
166 // and `setDisplayWebpageImages()`.
167 private WebView mainWebView;
169 // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
170 private FrameLayout fullScreenVideoFrameLayout;
172 // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu`, and `onRestart()`.
173 private SwipeRefreshLayout swipeRefreshLayout;
175 // `urlAppBarRelativeLayout` is used in `onCreate()` and `applyDomainSettings()`.
176 private RelativeLayout urlAppBarRelativeLayout;
178 // `favoriteIconImageView` is used in `onCreate()` and `applyDomainSettings()`
179 private ImageView favoriteIconImageView;
181 // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `loadUrlFromTextBox()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
182 private CookieManager cookieManager;
184 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
185 private final Map<String, String> customHeaders = new HashMap<>();
187 // `javaScriptEnabled` is also used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `applyAppSettings()`.
188 // It is `Boolean` instead of `boolean` because `applyAppSettings()` needs to know if it is `null`.
189 private Boolean javaScriptEnabled;
191 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applyAppSettings()`.
192 private boolean firstPartyCookiesEnabled;
194 // `thirdPartyCookiesEnabled` used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
195 private boolean thirdPartyCookiesEnabled;
197 // `domStorageEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
198 private boolean domStorageEnabled;
200 // `saveFormDataEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
201 private boolean saveFormDataEnabled;
203 // `swipeToRefreshEnabled` is used in `onPrepareOptionsMenu()` and `applyAppSettings()`.
204 private boolean swipeToRefreshEnabled;
206 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applyAppSettings()`.
207 private String homepage;
209 // `searchURL` is used in `loadURLFromTextBox()` and `applyAppSettings()`.
210 private String searchURL;
212 // `adBlockerEnabled` is used in `onCreate()` and `applyAppSettings()`.
213 private boolean adBlockerEnabled;
215 // `privacyBrowserRuntime` is used in `onCreate()` and `applyAppSettings()`.
216 private Runtime privacyBrowserRuntime;
218 // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
219 private boolean incognitoModeEnabled;
221 // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
222 private boolean fullScreenBrowsingModeEnabled;
224 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
225 private boolean inFullScreenBrowsingMode;
227 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
228 private boolean hideSystemBarsOnFullscreen;
230 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
231 private boolean translucentNavigationBarOnFullscreen;
233 // `currentDomainName` is used in `onCreate()`, `onNavigationItemSelected()`, and `applyDomainSettings()`.
234 private String currentDomainName;
236 // `waitingForOrbot` is used in `onCreate()` and `applyAppSettings()`.
237 private boolean waitingForOrbot;
239 // `domainSettingsApplied` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
240 private boolean domainSettingsApplied;
242 // `displayWebpageImagesInt` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
243 private int displayWebpageImagesInt;
245 // `onTheFlyDisplayImagesSet` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
246 private boolean onTheFlyDisplayImagesSet;
248 // `waitingForOrbotData` is used in `onCreate()` and `applyAppSettings()`.
249 private String waitingForOrbotHTMLString;
251 // `privateDataDirectoryString` is used in `onCreate()` and `onNavigationItemSelected()`.
252 private String privateDataDirectoryString;
254 // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
255 private LinearLayout findOnPageLinearLayout;
257 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
258 private EditText findOnPageEditText;
260 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
261 private Menu mainMenu;
263 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
264 private ActionBarDrawerToggle drawerToggle;
266 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
267 private Toolbar supportAppBar;
269 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `loadUrl()`.
270 private EditText urlTextBox;
272 // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
275 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
276 private SslErrorHandler sslErrorHandler;
278 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
279 private InputMethodManager inputMethodManager;
281 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
282 private RelativeLayout mainWebViewRelativeLayout;
285 // 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.
286 @SuppressLint("SetJavaScriptEnabled")
287 protected void onCreate(Bundle savedInstanceState) {
288 super.onCreate(savedInstanceState);
289 setContentView(R.layout.main_drawerlayout);
291 // Get a handle for `inputMethodManager`.
292 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
294 // We need to use the `SupportActionBar` from `android.support.v7.app.ActionBar` until the minimum API is >= 21.
295 supportAppBar = (Toolbar) findViewById(R.id.app_bar);
296 setSupportActionBar(supportAppBar);
297 appBar = getSupportActionBar();
299 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
300 assert appBar != null;
302 // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
303 appBar.setCustomView(R.layout.url_app_bar);
304 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
306 // Create a `ForegroundColorSpan` and `StyleSpan` for formatting of `urlTextBox`. We have to use the deprecated `getColor()` until API >= 23.
307 @SuppressWarnings("deprecation") final ForegroundColorSpan redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
308 final StyleSpan boldStyleSpan = new StyleSpan(Typeface.BOLD);
310 // Get a handle for `urlTextBox`.
311 urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.url_edittext);
313 // Remove the formatting from `urlTextBar` when the user is editing the text.
314 urlTextBox.setOnFocusChangeListener(new View.OnFocusChangeListener() {
316 public void onFocusChange(View v, boolean hasFocus) {
317 if (hasFocus) { // The user is editing `urlTextBox`.
318 // Remove the formatting.
319 urlTextBox.getText().removeSpan(redColorSpan);
320 urlTextBox.getText().removeSpan(boldStyleSpan);
321 } else { // The user has stopped editing `urlTextBox`.
322 // Highlight connections that are not encrypted.
323 if (urlTextBox.getText().toString().startsWith("http://")) {
324 urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
325 urlTextBox.getText().setSpan(boldStyleSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
331 // Set the `Go` button on the keyboard to load the URL in `urlTextBox`.
332 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
334 public boolean onKey(View v, int keyCode, KeyEvent event) {
335 // If the event is a key-down event on the `enter` button, load the URL.
336 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
337 // Load the URL into the mainWebView and consume the event.
339 loadUrlFromTextBox();
340 } catch (UnsupportedEncodingException e) {
343 // If the enter key was pressed, consume the event.
346 // If any other key was pressed, do not consume the event.
352 // Set `waitingForOrbotHTMLString`.
353 waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
355 // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
356 currentDomainName = "";
357 orbotStatus = "unknown";
358 waitingForOrbot = false;
360 // Create an Orbot status `BroadcastReceiver`.
361 BroadcastReceiver orbotStatusBroadcastReceiver = new BroadcastReceiver() {
363 public void onReceive(Context context, Intent intent) {
364 // Store the content of the status message in `orbotStatus`.
365 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
367 // If we are waiting on Orbot, load the website now that Orbot is connected.
368 if (orbotStatus.equals("ON") && waitingForOrbot) {
369 // Reset `waitingForOrbot`.
370 waitingForOrbot = false;
372 // Load `formattedUrlString
373 loadUrl(formattedUrlString);
378 // Register `orbotStatusBroadcastReceiver` on `this` context.
379 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
381 // Get handles for views that need to be accessed.
382 drawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout);
383 rootCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.root_coordinatorlayout);
384 mainWebViewRelativeLayout = (RelativeLayout) findViewById(R.id.main_webview_relativelayout);
385 mainWebView = (WebView) findViewById(R.id.main_webview);
386 findOnPageLinearLayout = (LinearLayout) findViewById(R.id.find_on_page_linearlayout);
387 findOnPageEditText = (EditText) findViewById(R.id.find_on_page_edittext);
388 fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.full_screen_video_framelayout);
389 urlAppBarRelativeLayout = (RelativeLayout) findViewById(R.id.url_app_bar_relativelayout);
390 favoriteIconImageView = (ImageView) findViewById(R.id.favorite_icon);
392 // Create a double-tap listener to toggle full-screen mode.
393 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
394 // Override `onDoubleTap()`. All other events are handled using the default settings.
396 public boolean onDoubleTap(MotionEvent event) {
397 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
398 // Toggle `inFullScreenBrowsingMode`.
399 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
401 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
402 // Hide the `appBar`.
405 // Hide the `BannerAd` in the free flavor.
406 if (BuildConfig.FLAVOR.contentEquals("free")) {
407 BannerAd.hideAd(adView);
410 // Modify the system bars.
411 if (hideSystemBarsOnFullscreen) { // Hide everything.
412 // Remove the translucent overlays.
413 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
415 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
416 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
418 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
419 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
420 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
422 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
424 // Set `rootCoordinatorLayout` to fill the whole screen.
425 rootCoordinatorLayout.setFitsSystemWindows(false);
426 } else { // Hide everything except the status and navigation bars.
427 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
428 rootCoordinatorLayout.setFitsSystemWindows(false);
430 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.
431 // Set the navigation bar to be translucent.
432 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
435 } else { // Switch to normal viewing mode.
436 // Show the `appBar`.
439 // Show the `BannerAd` in the free flavor.
440 if (BuildConfig.FLAVOR.contentEquals("free")) {
441 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
442 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
444 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
445 adView = findViewById(R.id.adview);
448 // Remove the translucent navigation bar flag if it is set.
449 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
451 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
452 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
454 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
455 rootCoordinatorLayout.setSystemUiVisibility(0);
457 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
458 rootCoordinatorLayout.setFitsSystemWindows(true);
461 // Consume the double-tap.
463 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
469 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
470 mainWebView.setOnTouchListener(new View.OnTouchListener() {
472 public boolean onTouch(View v, MotionEvent event) {
473 // Send the `event` to `gestureDetector`.
474 return gestureDetector.onTouchEvent(event);
478 // Update `findOnPageCountTextView`.
479 mainWebView.setFindListener(new WebView.FindListener() {
480 // Get a handle for `findOnPageCountTextView`.
481 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
484 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
485 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
486 // Set `findOnPageCountTextView` to `0/0`.
487 findOnPageCountTextView.setText(R.string.zero_of_zero);
488 } else if (isDoneCounting) { // There are matches.
489 // `activeMatchOrdinal` is zero-based.
490 int activeMatch = activeMatchOrdinal + 1;
492 // Set `findOnPageCountTextView`.
493 findOnPageCountTextView.setText(activeMatch + "/" + numberOfMatches);
498 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
499 findOnPageEditText.addTextChangedListener(new TextWatcher() {
501 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
506 public void onTextChanged(CharSequence s, int start, int before, int count) {
511 public void afterTextChanged(Editable s) {
512 // Search for the text in `mainWebView`.
513 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
517 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
518 findOnPageEditText.setOnKeyListener(new View.OnKeyListener() {
520 public boolean onKey(View v, int keyCode, KeyEvent event) {
521 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
522 // Hide the soft keyboard. `0` indicates no additional flags.
523 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
525 // Consume the event.
527 } else { // A different key was pressed.
528 // Do not consume the event.
534 // Implement swipe to refresh
535 swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refreshlayout);
536 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
537 swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
539 public void onRefresh() {
540 mainWebView.reload();
544 // `DrawerTitle` identifies the `DrawerLayout` in accessibility mode.
545 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
547 // Listen for touches on the navigation menu.
548 final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationview);
549 navigationView.setNavigationItemSelectedListener(this);
551 // 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.
552 final Menu navigationMenu = navigationView.getMenu();
553 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
554 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
555 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
557 // The `DrawerListener` allows us to update the Navigation Menu.
558 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
560 public void onDrawerSlide(View drawerView, float slideOffset) {
564 public void onDrawerOpened(View drawerView) {
568 public void onDrawerClosed(View drawerView) {
572 public void onDrawerStateChanged(int newState) {
573 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // The drawer is opening or closing.
574 // Update the `Back`, `Forward`, and `History` menu items.
575 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
576 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
577 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
579 // Hide the keyboard so we can see the navigation menu. `0` indicates no additional flags.
580 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
582 // Clear the focus from `urlTextBox` if it has it.
583 urlTextBox.clearFocus();
588 // drawerToggle creates the hamburger icon at the start of the AppBar.
589 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
591 // Initialize `adServerSet`.
592 final Set<String> adServersSet = new HashSet<>();
594 // Load the list of ad servers into memory.
596 // Load `pgl.yoyo.org_adservers.txt` into a `BufferedReader`.
597 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(getAssets().open("pgl.yoyo.org_adservers.txt")));
599 // Create a string for storing each ad server.
602 // Populate `adServersSet`.
603 while ((adServer = bufferedReader.readLine()) != null) {
604 adServersSet.add(adServer);
607 // Close `bufferedReader`.
608 bufferedReader.close();
609 } catch (IOException ioException) {
610 // We're pretty sure the asset exists, so we don't need to worry about the `IOException` ever being thrown.
613 mainWebView.setWebViewClient(new WebViewClient() {
614 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
615 // We have to use the deprecated `shouldOverrideUrlLoading` until API >= 24.
616 @SuppressWarnings("deprecation")
618 public boolean shouldOverrideUrlLoading(WebView view, String url) {
619 if (url.startsWith("mailto:")) { // Load the URL in an external email program because it begins with `mailto:`.
620 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
621 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
623 // Parse the url and set it as the data for the `Intent`.
624 emailIntent.setData(Uri.parse(url));
626 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
627 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
630 startActivity(emailIntent);
632 // Returning `true` indicates the application is handling the URL.
634 } else { // Load the URL in Privacy Browser.
635 // Apply the domain settings for the new URL.
636 applyDomainSettings(url);
638 // Returning `false` causes the current `WebView` to handle the URL and prevents it from adding redirects to the history list.
643 // Block ads. We have to use the deprecated `shouldInterceptRequest` until minimum API >= 21.
644 @SuppressWarnings("deprecation")
646 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
647 if (adBlockerEnabled) { // Block ads.
648 // Extract the host from `url`.
649 Uri requestUri = Uri.parse(url);
650 String requestHost = requestUri.getHost();
652 // Initialize a variable to track if this is an ad server.
653 boolean requestHostIsAdServer = false;
655 // Check all the subdomains of `requestHost` if it is not `null` against the ad server database.
656 if (requestHost != null) {
657 while (requestHost.contains(".") && !requestHostIsAdServer) { // Stop checking if we run out of `.` or if we already know that `requestHostIsAdServer` is `true`.
658 if (adServersSet.contains(requestHost)) {
659 requestHostIsAdServer = true;
662 // Strip out the lowest subdomain of `requestHost`.
663 requestHost = requestHost.substring(requestHost.indexOf(".") + 1);
667 if (requestHostIsAdServer) { // It is an ad server.
668 // Return an empty `WebResourceResponse`.
669 return new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
670 } else { // It is not an ad server.
671 // `return null` loads the requested resource.
674 } else { // Ad blocking is disabled.
675 // `return null` loads the requested resource.
680 // Update the URL in urlTextBox when the page starts to load.
682 public void onPageStarted(WebView view, String url, Bitmap favicon) {
683 // Reset `webViewTitle`
684 webViewTitle = getString(R.string.no_title);
686 // Check to see if we are waiting on Orbot.
687 if (!waitingForOrbot) { // We are not waiting on Orbot, so we need to process the URL.
688 // 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.
689 formattedUrlString = url;
691 // Setup a `formattedUrlStringBuilder` to format the text in `urlTextBox`.
692 SpannableStringBuilder formattedUrlStringBuilder = new SpannableStringBuilder(formattedUrlString);
694 // Highlight connections that are not encrypted.
695 if (formattedUrlString.startsWith("http://")) {
696 formattedUrlStringBuilder.setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
697 formattedUrlStringBuilder.setSpan(boldStyleSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
700 // Display the formatted URL text.
701 urlTextBox.setText(formattedUrlStringBuilder);
703 // Apply any custom domain settings if the URL was loaded by navigating history.
704 if (navigatingHistory) {
705 applyDomainSettings(url);
710 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
712 public void onPageFinished(WebView view, String url) {
713 // Clear the cache and history if Incognito Mode is enabled.
714 if (incognitoModeEnabled) {
715 // Clear the cache. `true` includes disk files.
716 mainWebView.clearCache(true);
718 // Clear the back/forward history.
719 mainWebView.clearHistory();
721 // Manually delete cache folders.
723 // Delete the main `cache` folder.
724 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
726 // 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`.
727 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
728 } catch (IOException e) {
729 // Do nothing if an error is thrown.
733 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
734 if (!waitingForOrbot) {
735 // Check to see if `WebView` has set `url` to be `about:blank`.
736 if (url.equals("about:blank")) { // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
737 // Set `formattedUrlString` to `""`.
738 formattedUrlString = "";
740 urlTextBox.setText(formattedUrlString);
742 // Request focus for `urlTextBox`.
743 urlTextBox.requestFocus();
745 // Display the keyboard.
746 inputMethodManager.showSoftInput(urlTextBox, 0);
748 // Apply the domain settings. This clears any settings from the previous domain.
749 applyDomainSettings(formattedUrlString);
750 } else { // `WebView` has loaded a webpage.
751 // Set `formattedUrlString`.
752 formattedUrlString = url;
754 // Only update `urlTextBox` if the user is not typing in it.
755 if (!urlTextBox.hasFocus()) {
756 // Setup a `formattedUrlStringBuilder` to format the text in `urlTextBox`.
757 SpannableStringBuilder formattedUrlStringBuilder = new SpannableStringBuilder(formattedUrlString);
759 // Highlight connections that are not encrypted.
760 if (formattedUrlString.startsWith("http://")) {
761 formattedUrlStringBuilder.setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
762 formattedUrlStringBuilder.setSpan(boldStyleSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
765 // Display the formatted URL text.
766 urlTextBox.setText(formattedUrlStringBuilder);
770 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog`.
771 sslCertificate = mainWebView.getCertificate();
775 // Handle SSL Certificate errors.
777 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
778 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
779 sslErrorHandler = handler;
781 // Display the SSL error `AlertDialog`.
782 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
783 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.ssl_certificate_error));
787 // Get a handle for the progress bar.
788 final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress_bar);
790 mainWebView.setWebChromeClient(new WebChromeClient() {
791 // Update the progress bar when a page is loading.
793 public void onProgressChanged(WebView view, int progress) {
794 progressBar.setProgress(progress);
795 if (progress < 100) {
796 progressBar.setVisibility(View.VISIBLE);
798 progressBar.setVisibility(View.GONE);
800 //Stop the `SwipeToRefresh` indicator if it is running
801 swipeRefreshLayout.setRefreshing(false);
805 // Set the favorite icon when it changes.
807 public void onReceivedIcon(WebView view, Bitmap icon) {
808 // Only update the favorite icon if the website has finished loading.
809 if (progressBar.getVisibility() == View.GONE) {
810 // Save a copy of the favorite icon.
811 favoriteIconBitmap = icon;
813 // Place the favorite icon in the appBar.
814 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
818 // Save a copy of the title when it changes.
820 public void onReceivedTitle(WebView view, String title) {
821 // Save a copy of the title.
822 webViewTitle = title;
825 // Enter full screen video
827 public void onShowCustomView(View view, CustomViewCallback callback) {
828 // Pause the ad if this is the free flavor.
829 if (BuildConfig.FLAVOR.contentEquals("free")) {
830 BannerAd.pauseAd(adView);
833 // Remove the translucent overlays.
834 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
836 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
837 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
839 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
840 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
841 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
843 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
845 // Set `rootCoordinatorLayout` to fill the entire screen.
846 rootCoordinatorLayout.setFitsSystemWindows(false);
848 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
849 fullScreenVideoFrameLayout.addView(view);
850 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
853 // Exit full screen video
854 public void onHideCustomView() {
855 // Hide `fullScreenVideoFrameLayout`.
856 fullScreenVideoFrameLayout.removeAllViews();
857 fullScreenVideoFrameLayout.setVisibility(View.GONE);
859 // Add the translucent status flag. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
860 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
862 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars. This also clears the `SYSTEM_UI` flags.
863 rootCoordinatorLayout.setFitsSystemWindows(true);
865 // Show the ad if this is the free flavor.
866 if (BuildConfig.FLAVOR.contentEquals("free")) {
867 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
868 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
870 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
871 adView = findViewById(R.id.adview);
876 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
877 registerForContextMenu(mainWebView);
879 // Allow the downloading of files.
880 mainWebView.setDownloadListener(new DownloadListener() {
882 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
883 // Show the `DownloadFileDialog` `AlertDialog` and name this instance `@string/download`.
884 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
885 downloadFileDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
889 // Allow pinch to zoom.
890 mainWebView.getSettings().setBuiltInZoomControls(true);
892 // Hide zoom controls.
893 mainWebView.getSettings().setDisplayZoomControls(false);
895 // Set `mainWebView` to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
896 mainWebView.getSettings().setUseWideViewPort(true);
898 // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
899 mainWebView.getSettings().setLoadWithOverviewMode(true);
901 // Initialize cookieManager.
902 cookieManager = CookieManager.getInstance();
904 // 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).
905 customHeaders.put("X-Requested-With", "");
907 // 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.
908 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
910 // Get the intent that started the app.
911 final Intent launchingIntent = getIntent();
913 // Extract the launching intent data as `launchingIntentUriData`.
914 final Uri launchingIntentUriData = launchingIntent.getData();
916 // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
917 if (launchingIntentUriData != null) {
918 formattedUrlString = launchingIntentUriData.toString();
921 // Get a handle for the `Runtime`.
922 privacyBrowserRuntime = Runtime.getRuntime();
924 // Store the application's private data directory.
925 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`.
927 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
928 inFullScreenBrowsingMode = false;
930 // Initialize AdView for the free flavor.
931 adView = findViewById(R.id.adview);
933 // Initialize the privacy settings variables.
934 javaScriptEnabled = false;
935 firstPartyCookiesEnabled = false;
936 thirdPartyCookiesEnabled = false;
937 domStorageEnabled = false;
938 saveFormDataEnabled = false;
940 // Initialize `webViewTitle`.
941 webViewTitle = getString(R.string.no_title);
943 // Initialize `favoriteIconBitmap`. We have to use `ContextCompat` until API >= 21.
944 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
945 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
946 favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
948 // If the favorite icon is null, load the default.
949 if (favoriteIconBitmap == null) {
950 favoriteIconBitmap = favoriteIconDefaultBitmap;
953 // Apply the app settings from the shared preferences.
956 // Load `formattedUrlString` if we are not waiting for Orbot to connect.
957 if (!waitingForOrbot) {
958 loadUrl(formattedUrlString);
963 protected void onNewIntent(Intent intent) {
964 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
967 if (intent.getData() != null) {
968 // Get the intent data and convert it to a string.
969 final Uri intentUriData = intent.getData();
970 formattedUrlString = intentUriData.toString();
973 // Close the navigation drawer if it is open.
974 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
975 drawerLayout.closeDrawer(GravityCompat.START);
979 loadUrl(formattedUrlString);
981 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
982 mainWebView.requestFocus();
986 public void onRestart() {
989 // Apply the app settings, which may have been changed in `SettingsActivity`.
992 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
993 updatePrivacyIcons(true);
995 // Set the display webpage images mode.
996 setDisplayWebpageImages();
998 // Reload the webpage if displaying of images has been disabled in `SettingsFragment`.
999 if (reloadOnRestartBoolean) {
1000 // Reload `mainWebView`.
1001 mainWebView.reload();
1003 // Reset `reloadOnRestartBoolean`.
1004 reloadOnRestartBoolean = false;
1008 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1010 public void onResume() {
1013 // Resume JavaScript (if enabled).
1014 mainWebView.resumeTimers();
1016 // Resume `mainWebView`.
1017 mainWebView.onResume();
1019 // Resume the adView for the free flavor.
1020 if (BuildConfig.FLAVOR.contentEquals("free")) {
1021 BannerAd.resumeAd(adView);
1026 public void onPause() {
1027 // Pause `mainWebView`.
1028 mainWebView.onPause();
1030 // Stop all JavaScript.
1031 mainWebView.pauseTimers();
1033 // Pause the adView or it will continue to consume resources in the background on the free flavor.
1034 if (BuildConfig.FLAVOR.contentEquals("free")) {
1035 BannerAd.pauseAd(adView);
1042 public boolean onCreateOptionsMenu(Menu menu) {
1043 // Inflate the menu; this adds items to the action bar if it is present.
1044 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1046 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1049 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1050 updatePrivacyIcons(false);
1052 // Get handles for the menu items.
1053 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1054 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1055 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1056 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1058 // Only display third-party cookies if SDK >= 21
1059 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1061 // Get the shared preference values. `this` references the current context.
1062 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1064 // Set the status of the additional app bar icons. The default is `false`.
1065 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
1066 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1067 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1068 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1069 } else { //Do not display the additional icons.
1070 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1071 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1072 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1079 public boolean onPrepareOptionsMenu(Menu menu) {
1080 // Get handles for the menu items.
1081 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1082 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1083 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1084 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1085 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1086 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);
1087 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1088 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1089 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1091 // Set the status of the menu item checkboxes.
1092 toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1093 toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1094 toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1095 toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);
1096 displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1098 // Enable third-party cookies if first-party cookies are enabled.
1099 toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1101 // Enable DOM Storage if JavaScript is enabled.
1102 toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
1104 // Enable Clear Cookies if there are any.
1105 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1107 // Enable Clear Form Data is there is any.
1108 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1109 clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
1111 // Initialize font size variables.
1112 int fontSize = mainWebView.getSettings().getTextZoom();
1113 String fontSizeTitle;
1114 MenuItem selectedFontSizeMenuItem;
1116 // Prepare the font size title and current size menu item.
1119 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.twenty_five_percent);
1120 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1124 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.fifty_percent);
1125 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1129 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.seventy_five_percent);
1130 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1134 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
1135 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1139 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_twenty_five_percent);
1140 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1144 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_fifty_percent);
1145 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1149 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_seventy_five_percent);
1150 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1154 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.two_hundred_percent);
1155 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1159 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
1160 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1164 // Set the font size title and select the current size menu item.
1165 fontSizeMenuItem.setTitle(fontSizeTitle);
1166 selectedFontSizeMenuItem.setChecked(true);
1168 // Only show `Refresh` if `swipeToRefresh` is disabled.
1169 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
1171 // Run all the other default commands.
1172 super.onPrepareOptionsMenu(menu);
1174 // `return true` displays the menu.
1179 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1180 @SuppressLint("SetJavaScriptEnabled")
1181 // removeAllCookies is deprecated, but it is required for API < 21.
1182 @SuppressWarnings("deprecation")
1183 public boolean onOptionsItemSelected(MenuItem menuItem) {
1184 int menuItemId = menuItem.getItemId();
1186 // Set the commands that relate to the menu entries.
1187 switch (menuItemId) {
1188 case R.id.toggle_javascript:
1189 // Switch the status of javaScriptEnabled.
1190 javaScriptEnabled = !javaScriptEnabled;
1192 // Apply the new JavaScript status.
1193 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1195 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1196 updatePrivacyIcons(true);
1198 // Display a `Snackbar`.
1199 if (javaScriptEnabled) { // JavaScrip is enabled.
1200 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1201 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
1202 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1203 } else { // Privacy mode.
1204 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1207 // Reload the WebView.
1208 mainWebView.reload();
1211 case R.id.toggle_first_party_cookies:
1212 // Switch the status of firstPartyCookiesEnabled.
1213 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1215 // Update the menu checkbox.
1216 menuItem.setChecked(firstPartyCookiesEnabled);
1218 // Apply the new cookie status.
1219 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1221 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1222 updatePrivacyIcons(true);
1224 // Display a `Snackbar`.
1225 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1226 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1227 } else if (javaScriptEnabled){ // JavaScript is still enabled.
1228 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1229 } else { // Privacy mode.
1230 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1233 // Reload the WebView.
1234 mainWebView.reload();
1237 case R.id.toggle_third_party_cookies:
1238 if (Build.VERSION.SDK_INT >= 21) {
1239 // Switch the status of thirdPartyCookiesEnabled.
1240 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1242 // Update the menu checkbox.
1243 menuItem.setChecked(thirdPartyCookiesEnabled);
1245 // Apply the new cookie status.
1246 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1248 // Display a `Snackbar`.
1249 if (thirdPartyCookiesEnabled) {
1250 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1252 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1255 // Reload the WebView.
1256 mainWebView.reload();
1257 } // Else do nothing because SDK < 21.
1260 case R.id.toggle_dom_storage:
1261 // Switch the status of domStorageEnabled.
1262 domStorageEnabled = !domStorageEnabled;
1264 // Update the menu checkbox.
1265 menuItem.setChecked(domStorageEnabled);
1267 // Apply the new DOM Storage status.
1268 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1270 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1271 updatePrivacyIcons(true);
1273 // Display a `Snackbar`.
1274 if (domStorageEnabled) {
1275 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1277 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1280 // Reload the WebView.
1281 mainWebView.reload();
1284 case R.id.toggle_save_form_data:
1285 // Switch the status of saveFormDataEnabled.
1286 saveFormDataEnabled = !saveFormDataEnabled;
1288 // Update the menu checkbox.
1289 menuItem.setChecked(saveFormDataEnabled);
1291 // Apply the new form data status.
1292 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1294 // Display a `Snackbar`.
1295 if (saveFormDataEnabled) {
1296 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1298 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1301 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1302 updatePrivacyIcons(true);
1304 // Reload the WebView.
1305 mainWebView.reload();
1308 case R.id.clear_cookies:
1309 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1310 .setAction(R.string.undo, new View.OnClickListener() {
1312 public void onClick(View v) {
1313 // Do nothing because everything will be handled by `onDismissed()` below.
1316 .addCallback(new Snackbar.Callback() {
1318 public void onDismissed(Snackbar snackbar, int event) {
1320 // The user pushed the `Undo` button.
1321 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1325 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1327 // `cookieManager.removeAllCookie()` varies by SDK.
1328 if (Build.VERSION.SDK_INT < 21) {
1329 cookieManager.removeAllCookie();
1331 // `null` indicates no callback.
1332 cookieManager.removeAllCookies(null);
1340 case R.id.clear_dom_storage:
1341 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1342 .setAction(R.string.undo, new View.OnClickListener() {
1344 public void onClick(View v) {
1345 // Do nothing because everything will be handled by `onDismissed()` below.
1348 .addCallback(new Snackbar.Callback() {
1350 public void onDismissed(Snackbar snackbar, int event) {
1352 // The user pushed the `Undo` button.
1353 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1357 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1359 // Delete the DOM Storage.
1360 WebStorage webStorage = WebStorage.getInstance();
1361 webStorage.deleteAllData();
1368 case R.id.clear_form_data:
1369 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1370 .setAction(R.string.undo, new View.OnClickListener() {
1372 public void onClick(View v) {
1373 // Do nothing because everything will be handled by `onDismissed()` below.
1376 .addCallback(new Snackbar.Callback() {
1378 public void onDismissed(Snackbar snackbar, int event) {
1380 // The user pushed the `Undo` button.
1381 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1385 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1387 // Delete the form data.
1388 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1389 mainWebViewDatabase.clearFormData();
1396 case R.id.font_size_twenty_five_percent:
1397 mainWebView.getSettings().setTextZoom(25);
1400 case R.id.font_size_fifty_percent:
1401 mainWebView.getSettings().setTextZoom(50);
1404 case R.id.font_size_seventy_five_percent:
1405 mainWebView.getSettings().setTextZoom(75);
1408 case R.id.font_size_one_hundred_percent:
1409 mainWebView.getSettings().setTextZoom(100);
1412 case R.id.font_size_one_hundred_twenty_five_percent:
1413 mainWebView.getSettings().setTextZoom(125);
1416 case R.id.font_size_one_hundred_fifty_percent:
1417 mainWebView.getSettings().setTextZoom(150);
1420 case R.id.font_size_one_hundred_seventy_five_percent:
1421 mainWebView.getSettings().setTextZoom(175);
1424 case R.id.font_size_two_hundred_percent:
1425 mainWebView.getSettings().setTextZoom(200);
1428 case R.id.display_images:
1429 if (mainWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1430 mainWebView.getSettings().setLoadsImagesAutomatically(false);
1431 mainWebView.reload();
1432 } else { // Images are not currently loaded automatically.
1433 mainWebView.getSettings().setLoadsImagesAutomatically(true);
1436 // Set `onTheFlyDisplayImagesSet`.
1437 onTheFlyDisplayImagesSet = true;
1441 // Setup the share string.
1443 if (webViewTitle != null) {
1444 shareString = webViewTitle + " – " + urlTextBox.getText().toString();
1446 shareString = urlTextBox.getText().toString();
1449 // Create the share intent.
1450 Intent shareIntent = new Intent();
1451 shareIntent.setAction(Intent.ACTION_SEND);
1452 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1453 shareIntent.setType("text/plain");
1456 startActivity(Intent.createChooser(shareIntent, "Share URL"));
1459 case R.id.find_on_page:
1460 // Hide the URL app bar.
1461 supportAppBar.setVisibility(View.GONE);
1463 // Show the Find on Page `RelativeLayout`.
1464 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1466 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android.
1467 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1468 findOnPageEditText.postDelayed(new Runnable()
1473 // Set the focus on `findOnPageEditText`.
1474 findOnPageEditText.requestFocus();
1476 // Display the keyboard.
1477 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1483 // Get a `PrintManager` instance.
1484 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1486 // Convert `mainWebView` to `printDocumentAdapter`.
1487 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
1489 // Print the document. The print attributes are `null`.
1490 printManager.print(getResources().getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1493 case R.id.add_to_homescreen:
1494 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
1495 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
1496 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.create_shortcut));
1498 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
1502 mainWebView.reload();
1506 // Don't consume the event.
1507 return super.onOptionsItemSelected(menuItem);
1511 // removeAllCookies is deprecated, but it is required for API < 21.
1512 @SuppressWarnings("deprecation")
1514 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1515 int menuItemId = menuItem.getItemId();
1517 switch (menuItemId) {
1523 if (mainWebView.canGoBack()) {
1524 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1525 navigatingHistory = true;
1527 // Load the previous website in the history.
1528 mainWebView.goBack();
1533 if (mainWebView.canGoForward()) {
1534 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1535 navigatingHistory = true;
1537 // Load the next website in the history.
1538 mainWebView.goForward();
1543 // Get the `WebBackForwardList`.
1544 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
1546 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
1547 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
1548 urlHistoryDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.history));
1551 case R.id.bookmarks:
1552 // Launch BookmarksActivity.
1553 Intent bookmarksIntent = new Intent(this, BookmarksActivity.class);
1554 startActivity(bookmarksIntent);
1557 case R.id.downloads:
1558 // Launch the system Download Manager.
1559 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1561 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1562 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1564 startActivity(downloadManagerIntent);
1568 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1569 currentDomainName = "";
1571 // Launch `SettingsActivity`.
1572 Intent settingsIntent = new Intent(this, SettingsActivity.class);
1573 startActivity(settingsIntent);
1577 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1578 currentDomainName = "";
1580 // Launch `DomainsActivity`.
1581 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1582 startActivity(domainsIntent);
1586 // Launch `GuideActivity`.
1587 Intent guideIntent = new Intent(this, GuideActivity.class);
1588 startActivity(guideIntent);
1592 // Launch `AboutActivity`.
1593 Intent aboutIntent = new Intent(this, AboutActivity.class);
1594 startActivity(aboutIntent);
1597 case R.id.clearAndExit:
1598 // Get a handle for `sharedPreferences`. `this` references the current context.
1599 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1601 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
1604 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
1605 // The command to remove cookies changed slightly in API 21.
1606 if (Build.VERSION.SDK_INT >= 21) {
1607 cookieManager.removeAllCookies(null);
1609 cookieManager.removeAllCookie();
1612 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1614 // We have to use two commands because `Runtime.exec()` does not like `*`.
1615 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
1616 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
1617 } catch (IOException e) {
1618 // Do nothing if an error is thrown.
1622 // Clear DOM storage.
1623 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
1624 // Ask `WebStorage` to clear the DOM storage.
1625 WebStorage webStorage = WebStorage.getInstance();
1626 webStorage.deleteAllData();
1628 // Manually delete the DOM storage directory, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1630 // We have to use a `String[]` because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1631 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1632 } catch (IOException e) {
1633 // Do nothing if an error is thrown.
1638 if (clearEverything || sharedPreferences.getBoolean("clear_form_data", true)) {
1639 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1640 webViewDatabase.clearFormData();
1642 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1644 // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1645 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
1646 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
1647 } catch (IOException e) {
1648 // Do nothing if an error is thrown.
1653 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
1654 // `true` includes disk files.
1655 mainWebView.clearCache(true);
1657 // Manually delete the cache directories.
1659 // Delete the main cache directory.
1660 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1662 // 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.
1663 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1664 } catch (IOException e) {
1665 // Do nothing if an error is thrown.
1669 // Clear SSL certificate preferences.
1670 mainWebView.clearSslPreferences();
1672 // Clear the back/forward history.
1673 mainWebView.clearHistory();
1675 // Clear `formattedUrlString`.
1676 formattedUrlString = null;
1678 // Clear `customHeaders`.
1679 customHeaders.clear();
1681 // Detach all views from `mainWebViewRelativeLayout`.
1682 mainWebViewRelativeLayout.removeAllViews();
1684 // Destroy the internal state of `mainWebView`.
1685 mainWebView.destroy();
1687 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
1688 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
1689 if (clearEverything) {
1691 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
1692 } catch (IOException e) {
1693 // Do nothing if an error is thrown.
1697 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
1698 if (Build.VERSION.SDK_INT >= 21) {
1699 finishAndRemoveTask();
1704 // Remove the terminated program from RAM. The status code is `0`.
1709 // Close the navigation drawer.
1710 drawerLayout.closeDrawer(GravityCompat.START);
1715 public void onPostCreate(Bundle savedInstanceState) {
1716 super.onPostCreate(savedInstanceState);
1718 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
1719 drawerToggle.syncState();
1723 public void onConfigurationChanged(Configuration newConfig) {
1724 super.onConfigurationChanged(newConfig);
1726 // Reload the ad for the free flavor if we are not in full screen mode.
1727 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
1729 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1731 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1732 adView = findViewById(R.id.adview);
1735 // `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
1736 // ActivityCompat.invalidateOptionsMenu(this);
1740 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
1741 // Store the `HitTestResult`.
1742 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
1745 final String imageUrl;
1746 final String linkUrl;
1748 // Get a handle for the `ClipboardManager`.
1749 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
1751 switch (hitTestResult.getType()) {
1752 // `SRC_ANCHOR_TYPE` is a link.
1753 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1754 // Get the target URL.
1755 linkUrl = hitTestResult.getExtra();
1757 // Set the target URL as the title of the `ContextMenu`.
1758 menu.setHeaderTitle(linkUrl);
1760 // Add a `Load URL` entry.
1761 menu.add(R.string.load_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1763 public boolean onMenuItemClick(MenuItem item) {
1769 // Add a `Copy URL` entry.
1770 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1772 public boolean onMenuItemClick(MenuItem item) {
1773 // Save the link URL in a `ClipData`.
1774 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), linkUrl);
1776 // Set the `ClipData` as the clipboard's primary clip.
1777 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
1782 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1783 menu.add(R.string.cancel);
1786 case WebView.HitTestResult.EMAIL_TYPE:
1787 // Get the target URL.
1788 linkUrl = hitTestResult.getExtra();
1790 // Set the target URL as the title of the `ContextMenu`.
1791 menu.setHeaderTitle(linkUrl);
1793 // Add a `Write Email` entry.
1794 menu.add(R.string.write_email).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1796 public boolean onMenuItemClick(MenuItem item) {
1797 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1798 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1800 // Parse the url and set it as the data for the `Intent`.
1801 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
1803 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
1804 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1807 startActivity(emailIntent);
1812 // Add a `Copy Email Address` entry.
1813 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1815 public boolean onMenuItemClick(MenuItem item) {
1816 // Save the email address in a `ClipData`.
1817 ClipData srcEmailTypeClipData = ClipData.newPlainText(getResources().getString(R.string.email_address), linkUrl);
1819 // Set the `ClipData` as the clipboard's primary clip.
1820 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
1825 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1826 menu.add(R.string.cancel);
1829 // `IMAGE_TYPE` is an image.
1830 case WebView.HitTestResult.IMAGE_TYPE:
1831 // Get the image URL.
1832 imageUrl = hitTestResult.getExtra();
1834 // Set the image URL as the title of the `ContextMenu`.
1835 menu.setHeaderTitle(imageUrl);
1837 // Add a `View Image` entry.
1838 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1840 public boolean onMenuItemClick(MenuItem item) {
1846 // Add a `Download Image` entry.
1847 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1849 public boolean onMenuItemClick(MenuItem item) {
1850 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
1851 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
1852 downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1857 // Add a `Copy URL` entry.
1858 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1860 public boolean onMenuItemClick(MenuItem item) {
1861 // Save the image URL in a `ClipData`.
1862 ClipData srcImageTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1864 // Set the `ClipData` as the clipboard's primary clip.
1865 clipboardManager.setPrimaryClip(srcImageTypeClipData);
1870 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1871 menu.add(R.string.cancel);
1875 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
1876 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1877 // Get the image URL.
1878 imageUrl = hitTestResult.getExtra();
1880 // Set the image URL as the title of the `ContextMenu`.
1881 menu.setHeaderTitle(imageUrl);
1883 // Add a `View Image` entry.
1884 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1886 public boolean onMenuItemClick(MenuItem item) {
1892 // Add a `Download Image` entry.
1893 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1895 public boolean onMenuItemClick(MenuItem item) {
1896 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
1897 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
1898 downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1903 // Add a `Copy URL` entry.
1904 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1906 public boolean onMenuItemClick(MenuItem item) {
1907 // Save the image URL in a `ClipData`.
1908 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1910 // Set the `ClipData` as the clipboard's primary clip.
1911 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
1916 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1917 menu.add(R.string.cancel);
1923 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
1924 // Get shortcutNameEditText from the alert dialog.
1925 EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
1927 // Create the bookmark shortcut based on formattedUrlString.
1928 Intent bookmarkShortcut = new Intent();
1929 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
1930 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
1932 // Place the bookmark shortcut on the home screen.
1933 Intent placeBookmarkShortcut = new Intent();
1934 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
1935 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
1936 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIconBitmap);
1937 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
1938 sendBroadcast(placeBookmarkShortcut);
1942 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
1943 // Download the image if it has an HTTP or HTTPS URI.
1944 if (imageUrl.startsWith("http")) {
1945 // Get a handle for the system `DOWNLOAD_SERVICE`.
1946 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
1948 // Parse `imageUrl`.
1949 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
1951 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
1952 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
1953 if (firstPartyCookiesEnabled) {
1954 // Get the cookies for `imageUrl`.
1955 String cookies = cookieManager.getCookie(imageUrl);
1957 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
1958 downloadRequest.addRequestHeader("Cookie", cookies);
1961 // Get the file name from `dialogFragment`.
1962 EditText downloadImageNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_image_name);
1963 String imageName = downloadImageNameEditText.getText().toString();
1965 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
1966 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `imageName`.
1967 downloadRequest.setDestinationInExternalFilesDir(this, "/", imageName);
1968 } else { // Only set the title using `imageName`.
1969 downloadRequest.setTitle(imageName);
1972 // Allow `MediaScanner` to index the download if it is a media file.
1973 downloadRequest.allowScanningByMediaScanner();
1975 // Add the URL as the description for the download.
1976 downloadRequest.setDescription(imageUrl);
1978 // Show the download notification after the download is completed.
1979 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
1981 // Initiate the download.
1982 downloadManager.enqueue(downloadRequest);
1983 } else { // The image is not an HTTP or HTTPS URI.
1984 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
1989 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
1990 // Download the file if it has an HTTP or HTTPS URI.
1991 if (downloadUrl.startsWith("http")) {
1993 // Get a handle for the system `DOWNLOAD_SERVICE`.
1994 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
1996 // Parse `downloadUrl`.
1997 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
1999 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
2000 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2001 if (firstPartyCookiesEnabled) {
2002 // Get the cookies for `downloadUrl`.
2003 String cookies = cookieManager.getCookie(downloadUrl);
2005 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2006 downloadRequest.addRequestHeader("Cookie", cookies);
2009 // Get the file name from `dialogFragment`.
2010 EditText downloadFileNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_file_name);
2011 String fileName = downloadFileNameEditText.getText().toString();
2013 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
2014 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download location to `/sdcard/Android/data/com.stoutner.privacybrowser.standard/files` named `fileName`.
2015 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
2016 } else { // Only set the title using `fileName`.
2017 downloadRequest.setTitle(fileName);
2020 // Allow `MediaScanner` to index the download if it is a media file.
2021 downloadRequest.allowScanningByMediaScanner();
2023 // Add the URL as the description for the download.
2024 downloadRequest.setDescription(downloadUrl);
2026 // Show the download notification after the download is completed.
2027 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2029 // Initiate the download.
2030 downloadManager.enqueue(downloadRequest);
2031 } else { // The download is not an HTTP or HTTPS URI.
2032 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
2036 public void viewSslCertificate(View view) {
2037 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
2038 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
2039 viewSslCertificateDialogFragment.show(getFragmentManager(), getResources().getString(R.string.view_ssl_certificate));
2043 public void onSslErrorCancel() {
2044 sslErrorHandler.cancel();
2048 public void onSslErrorProceed() {
2049 sslErrorHandler.proceed();
2053 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
2054 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2055 navigatingHistory = true;
2057 // Load the history entry.
2058 mainWebView.goBackOrForward(moveBackOrForwardSteps);
2062 public void onClearHistory() {
2063 // Clear the history.
2064 mainWebView.clearHistory();
2067 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
2069 public void onBackPressed() {
2070 // Close the navigation drawer if it is available. GravityCompat.START is the drawer on the left on Left-to-Right layout text.
2071 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
2072 drawerLayout.closeDrawer(GravityCompat.START);
2074 // Load the previous URL if available.
2075 if (mainWebView.canGoBack()) {
2076 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2077 navigatingHistory = true;
2080 mainWebView.goBack();
2082 // Pass `onBackPressed()` to the system.
2083 super.onBackPressed();
2088 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
2089 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
2090 String unformattedUrlString = urlTextBox.getText().toString().trim();
2092 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
2093 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
2094 // Add `http://` at the beginning if it is missing. Otherwise the app will segfault.
2095 if (!unformattedUrlString.startsWith("http")) {
2096 unformattedUrlString = "http://" + unformattedUrlString;
2099 // Initialize `unformattedUrl`.
2100 URL unformattedUrl = null;
2102 // 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.
2104 unformattedUrl = new URL(unformattedUrlString);
2105 } catch (MalformedURLException e) {
2106 e.printStackTrace();
2109 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2110 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2111 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2112 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2113 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2114 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2117 Uri.Builder formattedUri = new Uri.Builder();
2118 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2120 // Decode `formattedUri` as a `String` in `UTF-8`.
2121 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
2123 // Sanitize the search input and convert it to a search.
2124 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2126 // Add the base search URL.
2127 formattedUrlString = searchURL + encodedUrlString;
2130 loadUrl(formattedUrlString);
2132 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
2133 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2137 private void loadUrl(String url) {
2138 // Apply any custom domain settings.
2139 applyDomainSettings(url);
2142 mainWebView.loadUrl(url, customHeaders);
2145 public void findPreviousOnPage(View view) {
2146 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
2147 mainWebView.findNext(false);
2150 public void findNextOnPage(View view) {
2151 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2152 mainWebView.findNext(true);
2155 public void closeFindOnPage(View view) {
2156 // Delete the contents of `find_on_page_edittext`.
2157 findOnPageEditText.setText(null);
2159 // Clear the highlighted phrases.
2160 mainWebView.clearMatches();
2162 // Hide the Find on Page `RelativeLayout`.
2163 findOnPageLinearLayout.setVisibility(View.GONE);
2165 // Show the URL app bar.
2166 supportAppBar.setVisibility(View.VISIBLE);
2168 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
2169 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2172 private void applyAppSettings() {
2173 // Get a handle for `sharedPreferences`. `this` references the current context.
2174 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2176 // Store the values from `sharedPreferences` in variables.
2177 String homepageString = sharedPreferences.getString("homepage", "https://start.duckduckgo.com");
2178 String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
2179 String torSearchString = sharedPreferences.getString("tor_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
2180 String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
2181 String searchString = sharedPreferences.getString("search", "https://duckduckgo.com/html/?q=");
2182 String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
2183 adBlockerEnabled = sharedPreferences.getBoolean("block_ads", true);
2184 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
2185 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
2186 boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
2187 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
2188 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
2189 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
2190 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh", false);
2191 displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
2193 // Set the homepage, search, and proxy options.
2194 if (proxyThroughOrbot) { // Set the Tor options.
2195 // Set `torHomepageString` as `homepage`.
2196 homepage = torHomepageString;
2198 // If formattedUrlString is null assign the homepage to it.
2199 if (formattedUrlString == null) {
2200 formattedUrlString = homepage;
2203 // Set the search URL.
2204 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
2205 searchURL = torSearchCustomURLString;
2206 } else { // Use the string from the pre-built list.
2207 searchURL = torSearchString;
2210 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
2211 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
2213 // Display a message to the user if we are waiting on Orbot.
2214 if (!orbotStatus.equals("ON")) {
2215 // Set `waitingForOrbot`.
2216 waitingForOrbot = true;
2218 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
2219 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
2221 } else { // Set the non-Tor options.
2222 // Set `homepageString` as `homepage`.
2223 homepage = homepageString;
2225 // If formattedUrlString is null assign the homepage to it.
2226 if (formattedUrlString == null) {
2227 formattedUrlString = homepage;
2230 // Set the search URL.
2231 if (searchString.equals("Custom URL")) { // Get the custom URL string.
2232 searchURL = searchCustomURLString;
2233 } else { // Use the string from the pre-built list.
2234 searchURL = searchString;
2237 // Reset the proxy to default. The host is `""` and the port is `"0"`.
2238 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
2240 // Reset `waitingForOrbot.
2241 waitingForOrbot = false;
2244 // Set swipe to refresh.
2245 swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
2247 // Set Do Not Track status.
2248 if (doNotTrackEnabled) {
2249 customHeaders.put("DNT", "1");
2251 customHeaders.remove("DNT");
2254 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
2255 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
2256 if (hideSystemBarsOnFullscreen) { // Hide everything.
2257 // Remove the translucent navigation setting if it is currently flagged.
2258 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2260 // Remove the translucent status bar overlay.
2261 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2263 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
2264 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
2266 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
2267 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
2268 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
2270 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
2271 } else { // Hide everything except the status and navigation bars.
2272 // Add the translucent status flag if it is unset.
2273 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2275 if (translucentNavigationBarOnFullscreen) {
2276 // Set the navigation bar to be translucent.
2277 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2279 // Set the navigation bar to be black.
2280 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2283 } else { // Switch to normal viewing mode.
2284 // Reset `inFullScreenBrowsingMode` to `false`.
2285 inFullScreenBrowsingMode = false;
2287 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
2288 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
2292 // Show the `BannerAd` in the free flavor.
2293 if (BuildConfig.FLAVOR.contentEquals("free")) {
2294 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
2295 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2297 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2298 adView = findViewById(R.id.adview);
2301 // Remove the translucent navigation bar flag if it is set.
2302 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2304 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
2305 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2307 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
2308 rootCoordinatorLayout.setSystemUiVisibility(0);
2310 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
2311 rootCoordinatorLayout.setFitsSystemWindows(true);
2315 // We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2316 @SuppressWarnings("deprecation")
2317 private void applyDomainSettings(String url) {
2318 // Reset `navigatingHistory`.
2319 navigatingHistory = false;
2321 // Parse the URL into a URI.
2322 Uri uri = Uri.parse(url);
2324 // Extract the domain from `uri`.
2325 String hostName = uri.getHost();
2327 // Initialize `loadingNewDomainName`.
2328 boolean loadingNewDomainName;
2330 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
2331 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
2332 //noinspection SimplifiableIfStatement
2333 if ((hostName == null) || (currentDomainName == null)) {
2334 loadingNewDomainName = true;
2335 } else { // Determine if `hostName` equals `currentDomainName`.
2336 loadingNewDomainName = !hostName.equals(currentDomainName);
2339 // 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.
2340 if (loadingNewDomainName) {
2341 // Set the new `hostname` as the `currentDomainName`.
2342 currentDomainName = hostName;
2344 // Reset `favoriteIconBitmap` and display it in the `appbar`.
2345 favoriteIconBitmap = favoriteIconDefaultBitmap;
2346 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
2348 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
2349 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2350 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2352 // Get a full cursor from `domainsDatabaseHelper`.
2353 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
2355 // Initialize `domainSettingsSet`.
2356 Set<String> domainSettingsSet = new HashSet<>();
2358 // Get the domain name column index.
2359 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
2361 // Populate `domainSettingsSet`.
2362 for (int i = 0; i < domainNameCursor.getCount(); i++) {
2363 // Move `domainsCursor` to the current row.
2364 domainNameCursor.moveToPosition(i);
2366 // Store the domain name in `domainSettingsSet`.
2367 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
2370 // Close `domainNameCursor.
2371 domainNameCursor.close();
2373 // Initialize variables to track if domain settings will be applied and, if so, under which name.
2374 domainSettingsApplied = false;
2375 String domainNameInDatabase = null;
2377 // Check the hostname.
2378 if (domainSettingsSet.contains(hostName)) {
2379 domainSettingsApplied = true;
2380 domainNameInDatabase = hostName;
2383 // If `hostName` is not `null`, check all the subdomains of `hostName` against wildcard domains in `domainCursor`.
2384 if (hostName != null) {
2385 while (hostName.contains(".") && !domainSettingsApplied) { // Stop checking if we run out of `.` or if we already know that `domainSettingsApplied` is `true`.
2386 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
2387 domainSettingsApplied = true;
2388 domainNameInDatabase = "*." + hostName;
2391 // Strip out the lowest subdomain of `host`.
2392 hostName = hostName.substring(hostName.indexOf(".") + 1);
2396 // Get a handle for the shared preference. `this` references the current context.
2397 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2399 if (domainSettingsApplied) { // The url we are loading has custom domain settings.
2400 // Get a cursor for the current host and move it to the first position.
2401 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
2402 currentHostDomainSettingsCursor.moveToFirst();
2404 // Get the settings from the cursor.
2405 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
2406 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
2407 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
2408 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
2409 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
2410 String userAgentString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
2411 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
2412 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
2414 // Close `currentHostDomainSettingsCursor`.
2415 currentHostDomainSettingsCursor.close();
2417 // Apply the domain settings.
2418 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2419 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2420 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2421 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2422 mainWebView.getSettings().setTextZoom(fontSize);
2424 // Set third-party cookies status if API >= 21.
2425 if (Build.VERSION.SDK_INT >= 21) {
2426 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2429 // Set the user agent.
2430 if (userAgentString.equals("WebView default user agent")) {
2431 // Set the user agent to `""`, which uses the default value.
2432 mainWebView.getSettings().setUserAgentString("");
2434 // Use the selected user agent.
2435 mainWebView.getSettings().setUserAgentString(userAgentString);
2438 // 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.
2439 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_green));
2440 } else { // The URL we are loading does not have custom domain settings. Load the defaults.
2441 // Store the values from `sharedPreferences` in variables.
2442 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
2443 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
2444 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
2445 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
2446 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
2447 String userAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
2448 String customUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
2449 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
2451 // Apply the default settings.
2452 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2453 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2454 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2455 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2456 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
2458 // Set third-party cookies status if API >= 21.
2459 if (Build.VERSION.SDK_INT >= 21) {
2460 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2463 // Set the default user agent.
2464 switch (userAgentString) {
2465 case "WebView default user agent":
2466 // Set the user agent to `""`, which uses the default value.
2467 mainWebView.getSettings().setUserAgentString("");
2470 case "Custom user agent":
2471 // Set the custom user agent.
2472 mainWebView.getSettings().setUserAgentString(customUserAgentString);
2476 // Use the selected user agent.
2477 mainWebView.getSettings().setUserAgentString(userAgentString);
2481 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2482 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.url_bar_background_transparent));
2485 // Close `domainsDatabaseHelper`.
2486 domainsDatabaseHelper.close();
2488 // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode. `true` indicates that custom domain settings are applied.
2489 onTheFlyDisplayImagesSet = false;
2490 setDisplayWebpageImages();
2492 // Update the privacy icons, but only if `mainMenu` has already been populated.
2493 if (mainMenu != null) {
2494 updatePrivacyIcons(true);
2499 private void setDisplayWebpageImages() {
2500 if (!onTheFlyDisplayImagesSet) {
2501 if (domainSettingsApplied) { // Custom domain settings are applied.
2502 switch (displayWebpageImagesInt) {
2503 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
2504 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
2507 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
2508 mainWebView.getSettings().setLoadsImagesAutomatically(true);
2511 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
2512 mainWebView.getSettings().setLoadsImagesAutomatically(false);
2515 } else { // Default settings are applied.
2516 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
2521 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
2522 // Get handles for the icons.
2523 MenuItem privacyIconMenuItem = mainMenu.findItem(R.id.toggle_javascript);
2524 MenuItem firstPartyCookiesIconMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
2525 MenuItem domStorageIconMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
2526 MenuItem formDataIconMenuItem = mainMenu.findItem(R.id.toggle_save_form_data);
2528 // Update `privacyIcon`.
2529 if (javaScriptEnabled) { // JavaScript is enabled.
2530 privacyIconMenuItem.setIcon(R.drawable.javascript_enabled);
2531 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
2532 privacyIconMenuItem.setIcon(R.drawable.warning);
2533 } else { // All the dangerous features are disabled.
2534 privacyIconMenuItem.setIcon(R.drawable.privacy_mode);
2537 // Update `firstPartyCookiesIcon`.
2538 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
2539 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_enabled);
2540 } else { // First-party cookies are disabled.
2541 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled);
2544 // Update `domStorageIcon`.
2545 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
2546 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_enabled);
2547 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
2548 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled);
2549 } else { // JavaScript is disabled, so DOM storage is ghosted.
2550 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted);
2553 // Update `formDataIcon`.
2554 if (saveFormDataEnabled) { // Form data is enabled.
2555 formDataIconMenuItem.setIcon(R.drawable.form_data_enabled);
2556 } else { // Form data is disabled.
2557 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled);
2560 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`. `this` references the current activity.
2561 if (runInvalidateOptionsMenu) {
2562 ActivityCompat.invalidateOptionsMenu(this);