2 * Copyright © 2015-2017 Soren Stoutner <soren@stoutner.com>.
4 * Download cookie code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
6 * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
8 * Privacy Browser is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
13 * Privacy Browser is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with Privacy Browser. If not, see <http://www.gnu.org/licenses/>.
22 package com.stoutner.privacybrowser.activities;
24 import android.annotation.SuppressLint;
25 import android.app.DialogFragment;
26 import android.app.DownloadManager;
27 import android.content.BroadcastReceiver;
28 import android.content.ClipData;
29 import android.content.ClipboardManager;
30 import android.content.Context;
31 import android.content.Intent;
32 import android.content.IntentFilter;
33 import android.content.SharedPreferences;
34 import android.content.res.Configuration;
35 import android.database.Cursor;
36 import android.graphics.Bitmap;
37 import android.graphics.Typeface;
38 import android.graphics.drawable.BitmapDrawable;
39 import android.graphics.drawable.Drawable;
40 import android.net.Uri;
41 import android.net.http.SslCertificate;
42 import android.net.http.SslError;
43 import android.os.Build;
44 import android.os.Bundle;
45 import android.preference.PreferenceManager;
46 import android.print.PrintDocumentAdapter;
47 import android.print.PrintManager;
48 import android.support.annotation.NonNull;
49 import android.support.design.widget.CoordinatorLayout;
50 import android.support.design.widget.NavigationView;
51 import android.support.design.widget.Snackbar;
52 import android.support.v4.app.ActivityCompat;
53 import android.support.v4.content.ContextCompat;
54 import android.support.v4.view.GravityCompat;
55 import android.support.v4.widget.DrawerLayout;
56 import android.support.v4.widget.SwipeRefreshLayout;
57 import android.support.v7.app.ActionBar;
58 import android.support.v7.app.ActionBarDrawerToggle;
59 import android.support.v7.app.AppCompatActivity;
60 import android.support.v7.app.AppCompatDialogFragment;
61 import android.support.v7.widget.Toolbar;
62 import android.text.Editable;
63 import android.text.Spanned;
64 import android.text.TextWatcher;
65 import android.text.style.ForegroundColorSpan;
66 import android.text.style.StyleSpan;
67 import android.util.Patterns;
68 import android.view.ContextMenu;
69 import android.view.GestureDetector;
70 import android.view.KeyEvent;
71 import android.view.Menu;
72 import android.view.MenuItem;
73 import android.view.MotionEvent;
74 import android.view.View;
75 import android.view.WindowManager;
76 import android.view.inputmethod.InputMethodManager;
77 import android.webkit.CookieManager;
78 import android.webkit.DownloadListener;
79 import android.webkit.SslErrorHandler;
80 import android.webkit.WebBackForwardList;
81 import android.webkit.WebChromeClient;
82 import android.webkit.WebResourceResponse;
83 import android.webkit.WebStorage;
84 import android.webkit.WebView;
85 import android.webkit.WebViewClient;
86 import android.webkit.WebViewDatabase;
87 import android.widget.EditText;
88 import android.widget.FrameLayout;
89 import android.widget.ImageView;
90 import android.widget.LinearLayout;
91 import android.widget.ProgressBar;
92 import android.widget.RelativeLayout;
93 import android.widget.TextView;
95 import com.stoutner.privacybrowser.BannerAd;
96 import com.stoutner.privacybrowser.BuildConfig;
97 import com.stoutner.privacybrowser.R;
98 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
99 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
100 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
101 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
102 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
103 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
104 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
105 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
107 import java.io.BufferedReader;
108 import java.io.ByteArrayInputStream;
109 import java.io.IOException;
110 import java.io.InputStreamReader;
111 import java.io.UnsupportedEncodingException;
112 import java.net.MalformedURLException;
114 import java.net.URLDecoder;
115 import java.net.URLEncoder;
116 import java.util.HashMap;
117 import java.util.HashSet;
118 import java.util.Map;
119 import java.util.Set;
121 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
122 public class MainWebViewActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, CreateHomeScreenShortcutDialog.CreateHomeScreenSchortcutListener,
123 SslCertificateErrorDialog.SslCertificateErrorListener, DownloadFileDialog.DownloadFileListener, DownloadImageDialog.DownloadImageListener, UrlHistoryDialog.UrlHistoryListener {
125 // `darkTheme` is public static so it can be accessed from `AboutActivity` and `GuideActivity`. It is also used in `onCreate()`, `applyAppSettings()`, and `applyDomainSettings()`.
126 public static boolean darkTheme;
128 // `favoriteIconBitmap` is public static so it can be accessed from `CreateHomeScreenShortcutDialog`, `BookmarksActivity`, `CreateBookmarkDialog`, `CreateBookmarkFolderDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`, `ViewSslCertificateDialog`.
129 // It is also used in `onCreate()`, `onCreateHomeScreenShortcutCreate()`, and `applyDomainSettings`.
130 public static Bitmap favoriteIconBitmap;
132 // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`, `CreateBookmarkDialog`, and `AddDomainDialog`.
133 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
134 public static String formattedUrlString;
136 // `sslCertificate` is public static so it can be accessed from `ViewSslCertificateDialog`. It is also used in `onCreate()`.
137 public static SslCertificate sslCertificate;
139 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`.
140 public static String orbotStatus;
142 // `webViewTitle` is public static so it can be accessed from `CreateBookmarkDialog` and `CreateHomeScreenShortcutDialog`. It is also used in `onCreate()`.
143 public static String webViewTitle;
145 // `displayWebpageImagesBoolean` is public static so it can be accessed from `DomainSettingsFragment`. It is also used in `applyAppSettings()` and `applyDomainSettings()`.
146 public static boolean displayWebpageImagesBoolean;
148 // `reloadOnRestartBoolean` is public static so it can be accessed from `SettingsFragment`. It is also used in `onRestart()`
149 public static boolean reloadOnRestartBoolean;
152 // `appBar` is used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applyAppSettings()`.
153 private ActionBar appBar;
155 // `navigatingHistory` is used in `onCreate()`, `onNavigationItemSelected()`, and `applyDomainSettings()`.
156 private boolean navigatingHistory;
158 // `favoriteIconDefaultBitmap` is used in `onCreate()` and `applyDomainSettings`.
159 private Bitmap favoriteIconDefaultBitmap;
161 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, and `onBackPressed()`.
162 private DrawerLayout drawerLayout;
164 // `rootCoordinatorLayout` is used in `onCreate()` and `applyAppSettings()`.
165 private CoordinatorLayout rootCoordinatorLayout;
167 // `mainWebView` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`, `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`
168 // and `setDisplayWebpageImages()`.
169 private WebView mainWebView;
171 // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
172 private FrameLayout fullScreenVideoFrameLayout;
174 // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu`, and `onRestart()`.
175 private SwipeRefreshLayout swipeRefreshLayout;
177 // `urlAppBarRelativeLayout` is used in `onCreate()` and `applyDomainSettings()`.
178 private RelativeLayout urlAppBarRelativeLayout;
180 // `favoriteIconImageView` is used in `onCreate()` and `applyDomainSettings()`
181 private ImageView favoriteIconImageView;
183 // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `loadUrlFromTextBox()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
184 private CookieManager cookieManager;
186 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
187 private final Map<String, String> customHeaders = new HashMap<>();
189 // `javaScriptEnabled` is also used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `applyAppSettings()`.
190 // It is `Boolean` instead of `boolean` because `applyAppSettings()` needs to know if it is `null`.
191 private Boolean javaScriptEnabled;
193 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applyAppSettings()`.
194 private boolean firstPartyCookiesEnabled;
196 // `thirdPartyCookiesEnabled` used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
197 private boolean thirdPartyCookiesEnabled;
199 // `domStorageEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
200 private boolean domStorageEnabled;
202 // `saveFormDataEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
203 private boolean saveFormDataEnabled;
205 // `swipeToRefreshEnabled` is used in `onPrepareOptionsMenu()` and `applyAppSettings()`.
206 private boolean swipeToRefreshEnabled;
208 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applyAppSettings()`.
209 private String homepage;
211 // `searchURL` is used in `loadURLFromTextBox()` and `applyAppSettings()`.
212 private String searchURL;
214 // `adBlockerEnabled` is used in `onCreate()` and `applyAppSettings()`.
215 private boolean adBlockerEnabled;
217 // `privacyBrowserRuntime` is used in `onCreate()` and `applyAppSettings()`.
218 private Runtime privacyBrowserRuntime;
220 // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
221 private boolean incognitoModeEnabled;
223 // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
224 private boolean fullScreenBrowsingModeEnabled;
226 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
227 private boolean inFullScreenBrowsingMode;
229 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
230 private boolean hideSystemBarsOnFullscreen;
232 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
233 private boolean translucentNavigationBarOnFullscreen;
235 // `currentDomainName` is used in `onCreate()`, `onNavigationItemSelected()`, and `applyDomainSettings()`.
236 private String currentDomainName;
238 // `waitingForOrbot` is used in `onCreate()` and `applyAppSettings()`.
239 private boolean waitingForOrbot;
241 // `domainSettingsApplied` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
242 private boolean domainSettingsApplied;
244 // `displayWebpageImagesInt` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
245 private int displayWebpageImagesInt;
247 // `onTheFlyDisplayImagesSet` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
248 private boolean onTheFlyDisplayImagesSet;
250 // `waitingForOrbotData` is used in `onCreate()` and `applyAppSettings()`.
251 private String waitingForOrbotHTMLString;
253 // `privateDataDirectoryString` is used in `onCreate()` and `onNavigationItemSelected()`.
254 private String privateDataDirectoryString;
256 // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
257 private LinearLayout findOnPageLinearLayout;
259 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
260 private EditText findOnPageEditText;
262 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
263 private Menu mainMenu;
265 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
266 private ActionBarDrawerToggle drawerToggle;
268 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
269 private Toolbar supportAppBar;
271 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, `loadUrl()`, and `highlightUrlText()`.
272 private EditText urlTextBox;
274 // `redColorSpan` is used in `onCreate()` and `highlightUrlText()`.
275 private ForegroundColorSpan redColorSpan;
277 // `initialGrayColorSpan` is sued in `onCreate()` and `highlightUrlText()`.
278 private ForegroundColorSpan initialGrayColorSpan;
280 // `finalGrayColorSpam` is used in `onCreate()` and `highlightUrlText()`.
281 private ForegroundColorSpan finalGrayColorSpan;
283 // `boldStyleSpan` is used in `onCreate()` and `highlightUrlText()`.
284 private StyleSpan boldStyleSpan;
286 // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
289 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
290 private SslErrorHandler sslErrorHandler;
292 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
293 private InputMethodManager inputMethodManager;
295 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
296 private RelativeLayout mainWebViewRelativeLayout;
299 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled. The whole premise of Privacy Browser is built around an understanding of these dangers.
300 @SuppressLint("SetJavaScriptEnabled")
301 // Remove Android Studio's warning about deprecations. We have to use the deprecated `getColor()` until API >= 23.
302 @SuppressWarnings("deprecation")
303 protected void onCreate(Bundle savedInstanceState) {
304 // Get a handle for `sharedPreferences`. `this` references the current context.
305 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
307 // Get the theme preference.
308 darkTheme = sharedPreferences.getBoolean("dark_theme", false);
310 // Set the activity theme.
312 setTheme(R.style.PrivacyBrowserDark);
314 setTheme(R.style.PrivacyBrowserLight);
317 // Run the default commands.
318 super.onCreate(savedInstanceState);
320 // Set the content view.
321 setContentView(R.layout.main_drawerlayout);
323 // Get a handle for `inputMethodManager`.
324 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
326 // We need to use the `SupportActionBar` from `android.support.v7.app.ActionBar` until the minimum API is >= 21.
327 supportAppBar = (Toolbar) findViewById(R.id.app_bar);
328 setSupportActionBar(supportAppBar);
329 appBar = getSupportActionBar();
331 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
332 assert appBar != null;
334 // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
335 appBar.setCustomView(R.layout.url_app_bar);
336 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
338 // Initialize the `ForegroundColorSpans` and `StyleSpan` for highlighting `urlTextBox`. We have to use the deprecated `getColor()` until API >= 23.
339 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
340 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
341 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
342 boldStyleSpan = new StyleSpan(Typeface.BOLD);
344 // Get a handle for `urlTextBox`.
345 urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.url_edittext);
347 // Remove the formatting from `urlTextBar` when the user is editing the text.
348 urlTextBox.setOnFocusChangeListener(new View.OnFocusChangeListener() {
350 public void onFocusChange(View v, boolean hasFocus) {
351 if (hasFocus) { // The user is editing `urlTextBox`.
352 // Remove the highlighting.
353 urlTextBox.getText().removeSpan(redColorSpan);
354 urlTextBox.getText().removeSpan(initialGrayColorSpan);
355 urlTextBox.getText().removeSpan(finalGrayColorSpan);
356 urlTextBox.getText().removeSpan(boldStyleSpan);
357 } else { // The user has stopped editing `urlTextBox`.
358 // Reapply the highlighting.
361 // Scroll to the beginning of the text.
362 urlTextBox.setScrollX(0);
367 // Set the `Go` button on the keyboard to load the URL in `urlTextBox`.
368 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
370 public boolean onKey(View v, int keyCode, KeyEvent event) {
371 // If the event is a key-down event on the `enter` button, load the URL.
372 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
373 // Load the URL into the mainWebView and consume the event.
375 loadUrlFromTextBox();
376 } catch (UnsupportedEncodingException e) {
379 // If the enter key was pressed, consume the event.
382 // If any other key was pressed, do not consume the event.
388 // Set `waitingForOrbotHTMLString`.
389 waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
391 // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
392 currentDomainName = "";
393 orbotStatus = "unknown";
394 waitingForOrbot = false;
396 // Create an Orbot status `BroadcastReceiver`.
397 BroadcastReceiver orbotStatusBroadcastReceiver = new BroadcastReceiver() {
399 public void onReceive(Context context, Intent intent) {
400 // Store the content of the status message in `orbotStatus`.
401 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
403 // If we are waiting on Orbot, load the website now that Orbot is connected.
404 if (orbotStatus.equals("ON") && waitingForOrbot) {
405 // Reset `waitingForOrbot`.
406 waitingForOrbot = false;
408 // Load `formattedUrlString
409 loadUrl(formattedUrlString);
414 // Register `orbotStatusBroadcastReceiver` on `this` context.
415 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
417 // Get handles for views that need to be accessed.
418 drawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout);
419 rootCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.root_coordinatorlayout);
420 mainWebViewRelativeLayout = (RelativeLayout) findViewById(R.id.main_webview_relativelayout);
421 mainWebView = (WebView) findViewById(R.id.main_webview);
422 findOnPageLinearLayout = (LinearLayout) findViewById(R.id.find_on_page_linearlayout);
423 findOnPageEditText = (EditText) findViewById(R.id.find_on_page_edittext);
424 fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.full_screen_video_framelayout);
425 urlAppBarRelativeLayout = (RelativeLayout) findViewById(R.id.url_app_bar_relativelayout);
426 favoriteIconImageView = (ImageView) findViewById(R.id.favorite_icon);
428 // Create a double-tap listener to toggle full-screen mode.
429 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
430 // Override `onDoubleTap()`. All other events are handled using the default settings.
432 public boolean onDoubleTap(MotionEvent event) {
433 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
434 // Toggle `inFullScreenBrowsingMode`.
435 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
437 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
438 // Hide the `appBar`.
441 // Hide the `BannerAd` in the free flavor.
442 if (BuildConfig.FLAVOR.contentEquals("free")) {
443 BannerAd.hideAd(adView);
446 // Modify the system bars.
447 if (hideSystemBarsOnFullscreen) { // Hide everything.
448 // Remove the translucent overlays.
449 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
451 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
452 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
454 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
455 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
456 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
458 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
460 // Set `rootCoordinatorLayout` to fill the whole screen.
461 rootCoordinatorLayout.setFitsSystemWindows(false);
462 } else { // Hide everything except the status and navigation bars.
463 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
464 rootCoordinatorLayout.setFitsSystemWindows(false);
466 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.
467 // Set the navigation bar to be translucent.
468 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
471 } else { // Switch to normal viewing mode.
472 // Show the `appBar`.
475 // Show the `BannerAd` in the free flavor.
476 if (BuildConfig.FLAVOR.contentEquals("free")) {
477 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
478 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
480 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
481 adView = findViewById(R.id.adview);
484 // Remove the translucent navigation bar flag if it is set.
485 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
487 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
488 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
490 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
491 rootCoordinatorLayout.setSystemUiVisibility(0);
493 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
494 rootCoordinatorLayout.setFitsSystemWindows(true);
497 // Consume the double-tap.
499 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
505 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
506 mainWebView.setOnTouchListener(new View.OnTouchListener() {
508 public boolean onTouch(View v, MotionEvent event) {
509 // Send the `event` to `gestureDetector`.
510 return gestureDetector.onTouchEvent(event);
514 // Update `findOnPageCountTextView`.
515 mainWebView.setFindListener(new WebView.FindListener() {
516 // Get a handle for `findOnPageCountTextView`.
517 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
520 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
521 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
522 // Set `findOnPageCountTextView` to `0/0`.
523 findOnPageCountTextView.setText(R.string.zero_of_zero);
524 } else if (isDoneCounting) { // There are matches.
525 // `activeMatchOrdinal` is zero-based.
526 int activeMatch = activeMatchOrdinal + 1;
528 // Set `findOnPageCountTextView`.
529 findOnPageCountTextView.setText(activeMatch + "/" + numberOfMatches);
534 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
535 findOnPageEditText.addTextChangedListener(new TextWatcher() {
537 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
542 public void onTextChanged(CharSequence s, int start, int before, int count) {
547 public void afterTextChanged(Editable s) {
548 // Search for the text in `mainWebView`.
549 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
553 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
554 findOnPageEditText.setOnKeyListener(new View.OnKeyListener() {
556 public boolean onKey(View v, int keyCode, KeyEvent event) {
557 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
558 // Hide the soft keyboard. `0` indicates no additional flags.
559 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
561 // Consume the event.
563 } else { // A different key was pressed.
564 // Do not consume the event.
570 // Implement swipe to refresh
571 swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refreshlayout);
572 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
573 swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
575 public void onRefresh() {
576 mainWebView.reload();
580 // `DrawerTitle` identifies the `DrawerLayout` in accessibility mode.
581 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
583 // Listen for touches on the navigation menu.
584 final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationview);
585 navigationView.setNavigationItemSelectedListener(this);
587 // 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.
588 final Menu navigationMenu = navigationView.getMenu();
589 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
590 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
591 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
593 // The `DrawerListener` allows us to update the Navigation Menu.
594 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
596 public void onDrawerSlide(View drawerView, float slideOffset) {
600 public void onDrawerOpened(View drawerView) {
604 public void onDrawerClosed(View drawerView) {
608 public void onDrawerStateChanged(int newState) {
609 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // The drawer is opening or closing.
610 // Update the `Back`, `Forward`, and `History` menu items.
611 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
612 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
613 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
615 // Hide the keyboard (if displayed) so we can see the navigation menu. `0` indicates no additional flags.
616 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
618 // Clear the focus from `urlTextBox` if it has it.
619 urlTextBox.clearFocus();
624 // drawerToggle creates the hamburger icon at the start of the AppBar.
625 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
627 // Initialize `adServerSet`.
628 final Set<String> adServersSet = new HashSet<>();
630 // Load the list of ad servers into memory.
632 // Load `pgl.yoyo.org_adservers.txt` into a `BufferedReader`.
633 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(getAssets().open("pgl.yoyo.org_adservers.txt")));
635 // Create a string for storing each ad server.
638 // Populate `adServersSet`.
639 while ((adServer = bufferedReader.readLine()) != null) {
640 adServersSet.add(adServer);
643 // Close `bufferedReader`.
644 bufferedReader.close();
645 } catch (IOException ioException) {
646 // We're pretty sure the asset exists, so we don't need to worry about the `IOException` ever being thrown.
649 mainWebView.setWebViewClient(new WebViewClient() {
650 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
651 // We have to use the deprecated `shouldOverrideUrlLoading` until API >= 24.
652 @SuppressWarnings("deprecation")
654 public boolean shouldOverrideUrlLoading(WebView view, String url) {
655 if (url.startsWith("mailto:")) { // Load the URL in an external email program because it begins with `mailto:`.
656 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
657 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
659 // Parse the url and set it as the data for the `Intent`.
660 emailIntent.setData(Uri.parse(url));
662 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
663 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
666 startActivity(emailIntent);
668 // Returning `true` indicates the application is handling the URL.
670 } else { // Load the URL in Privacy Browser.
671 // Apply the domain settings for the new URL.
672 applyDomainSettings(url);
674 // Returning `false` causes the current `WebView` to handle the URL and prevents it from adding redirects to the history list.
679 // Block ads. We have to use the deprecated `shouldInterceptRequest` until minimum API >= 21.
680 @SuppressWarnings("deprecation")
682 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
683 if (adBlockerEnabled) { // Block ads.
684 // Extract the host from `url`.
685 Uri requestUri = Uri.parse(url);
686 String requestHost = requestUri.getHost();
688 // Initialize a variable to track if this is an ad server.
689 boolean requestHostIsAdServer = false;
691 // Check all the subdomains of `requestHost` if it is not `null` against the ad server database.
692 if (requestHost != null) {
693 while (requestHost.contains(".") && !requestHostIsAdServer) { // Stop checking if we run out of `.` or if we already know that `requestHostIsAdServer` is `true`.
694 if (adServersSet.contains(requestHost)) {
695 requestHostIsAdServer = true;
698 // Strip out the lowest subdomain of `requestHost`.
699 requestHost = requestHost.substring(requestHost.indexOf(".") + 1);
703 if (requestHostIsAdServer) { // It is an ad server.
704 // Return an empty `WebResourceResponse`.
705 return new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
706 } else { // It is not an ad server.
707 // `return null` loads the requested resource.
710 } else { // Ad blocking is disabled.
711 // `return null` loads the requested resource.
716 // Update the URL in urlTextBox when the page starts to load.
718 public void onPageStarted(WebView view, String url, Bitmap favicon) {
719 // Reset `webViewTitle`
720 webViewTitle = getString(R.string.no_title);
722 // Check to see if we are waiting on Orbot.
723 if (!waitingForOrbot) { // We are not waiting on Orbot, so we need to process the URL.
724 // 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.
725 formattedUrlString = url;
727 // Display the formatted URL text.
728 urlTextBox.setText(formattedUrlString);
730 // Apply text highlighting to `urlTextBox`.
733 // Apply any custom domain settings if the URL was loaded by navigating history.
734 if (navigatingHistory) {
735 applyDomainSettings(url);
740 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
742 public void onPageFinished(WebView view, String url) {
743 // Clear the cache and history if Incognito Mode is enabled.
744 if (incognitoModeEnabled) {
745 // Clear the cache. `true` includes disk files.
746 mainWebView.clearCache(true);
748 // Clear the back/forward history.
749 mainWebView.clearHistory();
751 // Manually delete cache folders.
753 // Delete the main `cache` folder.
754 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
756 // 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`.
757 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
758 } catch (IOException e) {
759 // Do nothing if an error is thrown.
763 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
764 if (!waitingForOrbot) {
765 // Check to see if `WebView` has set `url` to be `about:blank`.
766 if (url.equals("about:blank")) { // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
767 // Set `formattedUrlString` to `""`.
768 formattedUrlString = "";
770 urlTextBox.setText(formattedUrlString);
772 // Request focus for `urlTextBox`.
773 urlTextBox.requestFocus();
775 // Display the keyboard.
776 inputMethodManager.showSoftInput(urlTextBox, 0);
778 // Apply the domain settings. This clears any settings from the previous domain.
779 applyDomainSettings(formattedUrlString);
780 } else { // `WebView` has loaded a webpage.
781 // Set `formattedUrlString`.
782 formattedUrlString = url;
784 // Only update `urlTextBox` if the user is not typing in it.
785 if (!urlTextBox.hasFocus()) {
786 // Display the formatted URL text.
787 urlTextBox.setText(formattedUrlString);
789 // Apply text highlighting to `urlTextBox`.
794 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog`.
795 sslCertificate = mainWebView.getCertificate();
799 // Handle SSL Certificate errors.
801 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
802 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
803 sslErrorHandler = handler;
805 // Display the SSL error `AlertDialog`.
806 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
807 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.ssl_certificate_error));
811 // Get a handle for the progress bar.
812 final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress_bar);
814 mainWebView.setWebChromeClient(new WebChromeClient() {
815 // Update the progress bar when a page is loading.
817 public void onProgressChanged(WebView view, int progress) {
818 progressBar.setProgress(progress);
819 if (progress < 100) {
820 progressBar.setVisibility(View.VISIBLE);
822 progressBar.setVisibility(View.GONE);
824 //Stop the `SwipeToRefresh` indicator if it is running
825 swipeRefreshLayout.setRefreshing(false);
829 // Set the favorite icon when it changes.
831 public void onReceivedIcon(WebView view, Bitmap icon) {
832 // Only update the favorite icon if the website has finished loading.
833 if (progressBar.getVisibility() == View.GONE) {
834 // Save a copy of the favorite icon.
835 favoriteIconBitmap = icon;
837 // Place the favorite icon in the appBar.
838 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
842 // Save a copy of the title when it changes.
844 public void onReceivedTitle(WebView view, String title) {
845 // Save a copy of the title.
846 webViewTitle = title;
849 // Enter full screen video
851 public void onShowCustomView(View view, CustomViewCallback callback) {
852 // Pause the ad if this is the free flavor.
853 if (BuildConfig.FLAVOR.contentEquals("free")) {
854 BannerAd.pauseAd(adView);
857 // Remove the translucent overlays.
858 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
860 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
861 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
863 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
864 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
865 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
867 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
869 // Set `rootCoordinatorLayout` to fill the entire screen.
870 rootCoordinatorLayout.setFitsSystemWindows(false);
872 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
873 fullScreenVideoFrameLayout.addView(view);
874 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
877 // Exit full screen video
878 public void onHideCustomView() {
879 // Hide `fullScreenVideoFrameLayout`.
880 fullScreenVideoFrameLayout.removeAllViews();
881 fullScreenVideoFrameLayout.setVisibility(View.GONE);
883 // Add the translucent status flag. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
884 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
886 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars. This also clears the `SYSTEM_UI` flags.
887 rootCoordinatorLayout.setFitsSystemWindows(true);
889 // Show the ad if this is the free flavor.
890 if (BuildConfig.FLAVOR.contentEquals("free")) {
891 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
892 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
894 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
895 adView = findViewById(R.id.adview);
900 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
901 registerForContextMenu(mainWebView);
903 // Allow the downloading of files.
904 mainWebView.setDownloadListener(new DownloadListener() {
906 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
907 // Show the `DownloadFileDialog` `AlertDialog` and name this instance `@string/download`.
908 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
909 downloadFileDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
913 // Allow pinch to zoom.
914 mainWebView.getSettings().setBuiltInZoomControls(true);
916 // Hide zoom controls.
917 mainWebView.getSettings().setDisplayZoomControls(false);
919 // Set `mainWebView` to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
920 mainWebView.getSettings().setUseWideViewPort(true);
922 // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
923 mainWebView.getSettings().setLoadWithOverviewMode(true);
925 // Initialize cookieManager.
926 cookieManager = CookieManager.getInstance();
928 // 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).
929 customHeaders.put("X-Requested-With", "");
931 // 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.
932 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
934 // Get the intent that started the app.
935 final Intent launchingIntent = getIntent();
937 // Extract the launching intent data as `launchingIntentUriData`.
938 final Uri launchingIntentUriData = launchingIntent.getData();
940 // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
941 if (launchingIntentUriData != null) {
942 formattedUrlString = launchingIntentUriData.toString();
945 // Get a handle for the `Runtime`.
946 privacyBrowserRuntime = Runtime.getRuntime();
948 // Store the application's private data directory.
949 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`.
951 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
952 inFullScreenBrowsingMode = false;
954 // Initialize AdView for the free flavor.
955 adView = findViewById(R.id.adview);
957 // Initialize the privacy settings variables.
958 javaScriptEnabled = false;
959 firstPartyCookiesEnabled = false;
960 thirdPartyCookiesEnabled = false;
961 domStorageEnabled = false;
962 saveFormDataEnabled = false;
964 // Initialize `webViewTitle`.
965 webViewTitle = getString(R.string.no_title);
967 // Initialize `favoriteIconBitmap`. We have to use `ContextCompat` until API >= 21.
968 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
969 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
970 favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
972 // If the favorite icon is null, load the default.
973 if (favoriteIconBitmap == null) {
974 favoriteIconBitmap = favoriteIconDefaultBitmap;
977 // Apply the app settings from the shared preferences.
980 // Load `formattedUrlString` if we are not waiting for Orbot to connect.
981 if (!waitingForOrbot) {
982 loadUrl(formattedUrlString);
987 protected void onNewIntent(Intent intent) {
988 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
991 if (intent.getData() != null) {
992 // Get the intent data and convert it to a string.
993 final Uri intentUriData = intent.getData();
994 formattedUrlString = intentUriData.toString();
997 // Close the navigation drawer if it is open.
998 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
999 drawerLayout.closeDrawer(GravityCompat.START);
1002 // Load the website.
1003 loadUrl(formattedUrlString);
1005 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1006 mainWebView.requestFocus();
1010 public void onRestart() {
1013 // Apply the app settings, which may have been changed in `SettingsActivity`.
1016 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1017 updatePrivacyIcons(true);
1019 // Set the display webpage images mode.
1020 setDisplayWebpageImages();
1022 // Reload the webpage if displaying of images has been disabled in `SettingsFragment`.
1023 if (reloadOnRestartBoolean) {
1024 // Reload `mainWebView`.
1025 mainWebView.reload();
1027 // Reset `reloadOnRestartBoolean`.
1028 reloadOnRestartBoolean = false;
1032 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1034 public void onResume() {
1037 // Resume JavaScript (if enabled).
1038 mainWebView.resumeTimers();
1040 // Resume `mainWebView`.
1041 mainWebView.onResume();
1043 // Resume the adView for the free flavor.
1044 if (BuildConfig.FLAVOR.contentEquals("free")) {
1045 BannerAd.resumeAd(adView);
1050 public void onPause() {
1051 // Pause `mainWebView`.
1052 mainWebView.onPause();
1054 // Stop all JavaScript.
1055 mainWebView.pauseTimers();
1057 // Pause the adView or it will continue to consume resources in the background on the free flavor.
1058 if (BuildConfig.FLAVOR.contentEquals("free")) {
1059 BannerAd.pauseAd(adView);
1066 public boolean onCreateOptionsMenu(Menu menu) {
1067 // Inflate the menu; this adds items to the action bar if it is present.
1068 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1070 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1073 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1074 updatePrivacyIcons(false);
1076 // Get handles for the menu items.
1077 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1078 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1079 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1080 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1082 // Only display third-party cookies if SDK >= 21
1083 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1085 // Get the shared preference values. `this` references the current context.
1086 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1088 // Set the status of the additional app bar icons. The default is `false`.
1089 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
1090 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1091 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1092 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1093 } else { //Do not display the additional icons.
1094 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1095 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1096 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1103 public boolean onPrepareOptionsMenu(Menu menu) {
1104 // Get handles for the menu items.
1105 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1106 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1107 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1108 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1109 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1110 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);
1111 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1112 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1113 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1115 // Set the status of the menu item checkboxes.
1116 toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1117 toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1118 toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1119 toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);
1120 displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1122 // Enable third-party cookies if first-party cookies are enabled.
1123 toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1125 // Enable DOM Storage if JavaScript is enabled.
1126 toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
1128 // Enable Clear Cookies if there are any.
1129 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1131 // Enable Clear Form Data is there is any.
1132 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1133 clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
1135 // Initialize font size variables.
1136 int fontSize = mainWebView.getSettings().getTextZoom();
1137 String fontSizeTitle;
1138 MenuItem selectedFontSizeMenuItem;
1140 // Prepare the font size title and current size menu item.
1143 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.twenty_five_percent);
1144 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1148 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.fifty_percent);
1149 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1153 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.seventy_five_percent);
1154 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1158 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
1159 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1163 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_twenty_five_percent);
1164 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1168 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_fifty_percent);
1169 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1173 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_seventy_five_percent);
1174 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1178 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.two_hundred_percent);
1179 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1183 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
1184 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1188 // Set the font size title and select the current size menu item.
1189 fontSizeMenuItem.setTitle(fontSizeTitle);
1190 selectedFontSizeMenuItem.setChecked(true);
1192 // Only show `Refresh` if `swipeToRefresh` is disabled.
1193 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
1195 // Run all the other default commands.
1196 super.onPrepareOptionsMenu(menu);
1198 // `return true` displays the menu.
1203 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1204 @SuppressLint("SetJavaScriptEnabled")
1205 // removeAllCookies is deprecated, but it is required for API < 21.
1206 @SuppressWarnings("deprecation")
1207 public boolean onOptionsItemSelected(MenuItem menuItem) {
1208 int menuItemId = menuItem.getItemId();
1210 // Set the commands that relate to the menu entries.
1211 switch (menuItemId) {
1212 case R.id.toggle_javascript:
1213 // Switch the status of javaScriptEnabled.
1214 javaScriptEnabled = !javaScriptEnabled;
1216 // Apply the new JavaScript status.
1217 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1219 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1220 updatePrivacyIcons(true);
1222 // Display a `Snackbar`.
1223 if (javaScriptEnabled) { // JavaScrip is enabled.
1224 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1225 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
1226 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1227 } else { // Privacy mode.
1228 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1231 // Reload the WebView.
1232 mainWebView.reload();
1235 case R.id.toggle_first_party_cookies:
1236 // Switch the status of firstPartyCookiesEnabled.
1237 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1239 // Update the menu checkbox.
1240 menuItem.setChecked(firstPartyCookiesEnabled);
1242 // Apply the new cookie status.
1243 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1245 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1246 updatePrivacyIcons(true);
1248 // Display a `Snackbar`.
1249 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1250 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1251 } else if (javaScriptEnabled){ // JavaScript is still enabled.
1252 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1253 } else { // Privacy mode.
1254 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1257 // Reload the WebView.
1258 mainWebView.reload();
1261 case R.id.toggle_third_party_cookies:
1262 if (Build.VERSION.SDK_INT >= 21) {
1263 // Switch the status of thirdPartyCookiesEnabled.
1264 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1266 // Update the menu checkbox.
1267 menuItem.setChecked(thirdPartyCookiesEnabled);
1269 // Apply the new cookie status.
1270 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1272 // Display a `Snackbar`.
1273 if (thirdPartyCookiesEnabled) {
1274 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1276 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1279 // Reload the WebView.
1280 mainWebView.reload();
1281 } // Else do nothing because SDK < 21.
1284 case R.id.toggle_dom_storage:
1285 // Switch the status of domStorageEnabled.
1286 domStorageEnabled = !domStorageEnabled;
1288 // Update the menu checkbox.
1289 menuItem.setChecked(domStorageEnabled);
1291 // Apply the new DOM Storage status.
1292 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1294 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1295 updatePrivacyIcons(true);
1297 // Display a `Snackbar`.
1298 if (domStorageEnabled) {
1299 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1301 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1304 // Reload the WebView.
1305 mainWebView.reload();
1308 case R.id.toggle_save_form_data:
1309 // Switch the status of saveFormDataEnabled.
1310 saveFormDataEnabled = !saveFormDataEnabled;
1312 // Update the menu checkbox.
1313 menuItem.setChecked(saveFormDataEnabled);
1315 // Apply the new form data status.
1316 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1318 // Display a `Snackbar`.
1319 if (saveFormDataEnabled) {
1320 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1322 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1325 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1326 updatePrivacyIcons(true);
1328 // Reload the WebView.
1329 mainWebView.reload();
1332 case R.id.clear_cookies:
1333 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1334 .setAction(R.string.undo, new View.OnClickListener() {
1336 public void onClick(View v) {
1337 // Do nothing because everything will be handled by `onDismissed()` below.
1340 .addCallback(new Snackbar.Callback() {
1342 public void onDismissed(Snackbar snackbar, int event) {
1344 // The user pushed the `Undo` button.
1345 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1349 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1351 // `cookieManager.removeAllCookie()` varies by SDK.
1352 if (Build.VERSION.SDK_INT < 21) {
1353 cookieManager.removeAllCookie();
1355 // `null` indicates no callback.
1356 cookieManager.removeAllCookies(null);
1364 case R.id.clear_dom_storage:
1365 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1366 .setAction(R.string.undo, new View.OnClickListener() {
1368 public void onClick(View v) {
1369 // Do nothing because everything will be handled by `onDismissed()` below.
1372 .addCallback(new Snackbar.Callback() {
1374 public void onDismissed(Snackbar snackbar, int event) {
1376 // The user pushed the `Undo` button.
1377 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1381 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1383 // Delete the DOM Storage.
1384 WebStorage webStorage = WebStorage.getInstance();
1385 webStorage.deleteAllData();
1392 case R.id.clear_form_data:
1393 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1394 .setAction(R.string.undo, new View.OnClickListener() {
1396 public void onClick(View v) {
1397 // Do nothing because everything will be handled by `onDismissed()` below.
1400 .addCallback(new Snackbar.Callback() {
1402 public void onDismissed(Snackbar snackbar, int event) {
1404 // The user pushed the `Undo` button.
1405 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1409 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1411 // Delete the form data.
1412 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1413 mainWebViewDatabase.clearFormData();
1420 case R.id.font_size_twenty_five_percent:
1421 mainWebView.getSettings().setTextZoom(25);
1424 case R.id.font_size_fifty_percent:
1425 mainWebView.getSettings().setTextZoom(50);
1428 case R.id.font_size_seventy_five_percent:
1429 mainWebView.getSettings().setTextZoom(75);
1432 case R.id.font_size_one_hundred_percent:
1433 mainWebView.getSettings().setTextZoom(100);
1436 case R.id.font_size_one_hundred_twenty_five_percent:
1437 mainWebView.getSettings().setTextZoom(125);
1440 case R.id.font_size_one_hundred_fifty_percent:
1441 mainWebView.getSettings().setTextZoom(150);
1444 case R.id.font_size_one_hundred_seventy_five_percent:
1445 mainWebView.getSettings().setTextZoom(175);
1448 case R.id.font_size_two_hundred_percent:
1449 mainWebView.getSettings().setTextZoom(200);
1452 case R.id.display_images:
1453 if (mainWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1454 mainWebView.getSettings().setLoadsImagesAutomatically(false);
1455 mainWebView.reload();
1456 } else { // Images are not currently loaded automatically.
1457 mainWebView.getSettings().setLoadsImagesAutomatically(true);
1460 // Set `onTheFlyDisplayImagesSet`.
1461 onTheFlyDisplayImagesSet = true;
1465 // Setup the share string.
1467 if (webViewTitle != null) {
1468 shareString = webViewTitle + " – " + urlTextBox.getText().toString();
1470 shareString = urlTextBox.getText().toString();
1473 // Create the share intent.
1474 Intent shareIntent = new Intent();
1475 shareIntent.setAction(Intent.ACTION_SEND);
1476 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1477 shareIntent.setType("text/plain");
1480 startActivity(Intent.createChooser(shareIntent, "Share URL"));
1483 case R.id.find_on_page:
1484 // Hide the URL app bar.
1485 supportAppBar.setVisibility(View.GONE);
1487 // Show the Find on Page `RelativeLayout`.
1488 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1490 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android.
1491 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1492 findOnPageEditText.postDelayed(new Runnable()
1497 // Set the focus on `findOnPageEditText`.
1498 findOnPageEditText.requestFocus();
1500 // Display the keyboard.
1501 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1507 // Get a `PrintManager` instance.
1508 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1510 // Convert `mainWebView` to `printDocumentAdapter`.
1511 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
1513 // Print the document. The print attributes are `null`.
1514 printManager.print(getResources().getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1517 case R.id.add_to_homescreen:
1518 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
1519 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
1520 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.create_shortcut));
1522 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
1526 mainWebView.reload();
1530 // Don't consume the event.
1531 return super.onOptionsItemSelected(menuItem);
1535 // removeAllCookies is deprecated, but it is required for API < 21.
1536 @SuppressWarnings("deprecation")
1538 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1539 int menuItemId = menuItem.getItemId();
1541 switch (menuItemId) {
1547 if (mainWebView.canGoBack()) {
1548 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1549 navigatingHistory = true;
1551 // Load the previous website in the history.
1552 mainWebView.goBack();
1557 if (mainWebView.canGoForward()) {
1558 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1559 navigatingHistory = true;
1561 // Load the next website in the history.
1562 mainWebView.goForward();
1567 // Get the `WebBackForwardList`.
1568 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
1570 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
1571 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
1572 urlHistoryDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.history));
1575 case R.id.bookmarks:
1576 // Launch BookmarksActivity.
1577 Intent bookmarksIntent = new Intent(this, BookmarksActivity.class);
1578 startActivity(bookmarksIntent);
1581 case R.id.downloads:
1582 // Launch the system Download Manager.
1583 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1585 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1586 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1588 startActivity(downloadManagerIntent);
1592 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1593 currentDomainName = "";
1595 // Launch `SettingsActivity`.
1596 Intent settingsIntent = new Intent(this, SettingsActivity.class);
1597 startActivity(settingsIntent);
1601 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1602 currentDomainName = "";
1604 // Launch `DomainsActivity`.
1605 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1606 startActivity(domainsIntent);
1610 // Launch `GuideActivity`.
1611 Intent guideIntent = new Intent(this, GuideActivity.class);
1612 startActivity(guideIntent);
1616 // Launch `AboutActivity`.
1617 Intent aboutIntent = new Intent(this, AboutActivity.class);
1618 startActivity(aboutIntent);
1621 case R.id.clearAndExit:
1622 // Get a handle for `sharedPreferences`. `this` references the current context.
1623 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1625 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
1628 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
1629 // The command to remove cookies changed slightly in API 21.
1630 if (Build.VERSION.SDK_INT >= 21) {
1631 cookieManager.removeAllCookies(null);
1633 cookieManager.removeAllCookie();
1636 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1638 // We have to use two commands because `Runtime.exec()` does not like `*`.
1639 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
1640 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
1641 } catch (IOException e) {
1642 // Do nothing if an error is thrown.
1646 // Clear DOM storage.
1647 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
1648 // Ask `WebStorage` to clear the DOM storage.
1649 WebStorage webStorage = WebStorage.getInstance();
1650 webStorage.deleteAllData();
1652 // Manually delete the DOM storage directory, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1654 // We have to use a `String[]` because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1655 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1656 } catch (IOException e) {
1657 // Do nothing if an error is thrown.
1662 if (clearEverything || sharedPreferences.getBoolean("clear_form_data", true)) {
1663 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1664 webViewDatabase.clearFormData();
1666 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1668 // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1669 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
1670 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
1671 } catch (IOException e) {
1672 // Do nothing if an error is thrown.
1677 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
1678 // `true` includes disk files.
1679 mainWebView.clearCache(true);
1681 // Manually delete the cache directories.
1683 // Delete the main cache directory.
1684 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1686 // 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.
1687 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1688 } catch (IOException e) {
1689 // Do nothing if an error is thrown.
1693 // Clear SSL certificate preferences.
1694 mainWebView.clearSslPreferences();
1696 // Clear the back/forward history.
1697 mainWebView.clearHistory();
1699 // Clear `formattedUrlString`.
1700 formattedUrlString = null;
1702 // Clear `customHeaders`.
1703 customHeaders.clear();
1705 // Detach all views from `mainWebViewRelativeLayout`.
1706 mainWebViewRelativeLayout.removeAllViews();
1708 // Destroy the internal state of `mainWebView`.
1709 mainWebView.destroy();
1711 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
1712 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
1713 if (clearEverything) {
1715 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
1716 } catch (IOException e) {
1717 // Do nothing if an error is thrown.
1721 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
1722 if (Build.VERSION.SDK_INT >= 21) {
1723 finishAndRemoveTask();
1728 // Remove the terminated program from RAM. The status code is `0`.
1733 // Close the navigation drawer.
1734 drawerLayout.closeDrawer(GravityCompat.START);
1739 public void onPostCreate(Bundle savedInstanceState) {
1740 super.onPostCreate(savedInstanceState);
1742 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
1743 drawerToggle.syncState();
1747 public void onConfigurationChanged(Configuration newConfig) {
1748 super.onConfigurationChanged(newConfig);
1750 // Reload the ad for the free flavor if we are not in full screen mode.
1751 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
1753 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1755 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1756 adView = findViewById(R.id.adview);
1759 // `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
1760 // ActivityCompat.invalidateOptionsMenu(this);
1764 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
1765 // Store the `HitTestResult`.
1766 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
1769 final String imageUrl;
1770 final String linkUrl;
1772 // Get a handle for the `ClipboardManager`.
1773 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
1775 switch (hitTestResult.getType()) {
1776 // `SRC_ANCHOR_TYPE` is a link.
1777 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1778 // Get the target URL.
1779 linkUrl = hitTestResult.getExtra();
1781 // Set the target URL as the title of the `ContextMenu`.
1782 menu.setHeaderTitle(linkUrl);
1784 // Add a `Load URL` entry.
1785 menu.add(R.string.load_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1787 public boolean onMenuItemClick(MenuItem item) {
1793 // Add a `Copy URL` entry.
1794 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1796 public boolean onMenuItemClick(MenuItem item) {
1797 // Save the link URL in a `ClipData`.
1798 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), linkUrl);
1800 // Set the `ClipData` as the clipboard's primary clip.
1801 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
1806 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1807 menu.add(R.string.cancel);
1810 case WebView.HitTestResult.EMAIL_TYPE:
1811 // Get the target URL.
1812 linkUrl = hitTestResult.getExtra();
1814 // Set the target URL as the title of the `ContextMenu`.
1815 menu.setHeaderTitle(linkUrl);
1817 // Add a `Write Email` entry.
1818 menu.add(R.string.write_email).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1820 public boolean onMenuItemClick(MenuItem item) {
1821 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1822 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1824 // Parse the url and set it as the data for the `Intent`.
1825 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
1827 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
1828 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1831 startActivity(emailIntent);
1836 // Add a `Copy Email Address` entry.
1837 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1839 public boolean onMenuItemClick(MenuItem item) {
1840 // Save the email address in a `ClipData`.
1841 ClipData srcEmailTypeClipData = ClipData.newPlainText(getResources().getString(R.string.email_address), linkUrl);
1843 // Set the `ClipData` as the clipboard's primary clip.
1844 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
1849 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1850 menu.add(R.string.cancel);
1853 // `IMAGE_TYPE` is an image.
1854 case WebView.HitTestResult.IMAGE_TYPE:
1855 // Get the image URL.
1856 imageUrl = hitTestResult.getExtra();
1858 // Set the image URL as the title of the `ContextMenu`.
1859 menu.setHeaderTitle(imageUrl);
1861 // Add a `View Image` entry.
1862 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1864 public boolean onMenuItemClick(MenuItem item) {
1870 // Add a `Download Image` entry.
1871 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1873 public boolean onMenuItemClick(MenuItem item) {
1874 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
1875 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
1876 downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1881 // Add a `Copy URL` entry.
1882 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1884 public boolean onMenuItemClick(MenuItem item) {
1885 // Save the image URL in a `ClipData`.
1886 ClipData srcImageTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1888 // Set the `ClipData` as the clipboard's primary clip.
1889 clipboardManager.setPrimaryClip(srcImageTypeClipData);
1894 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1895 menu.add(R.string.cancel);
1899 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
1900 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1901 // Get the image URL.
1902 imageUrl = hitTestResult.getExtra();
1904 // Set the image URL as the title of the `ContextMenu`.
1905 menu.setHeaderTitle(imageUrl);
1907 // Add a `View Image` entry.
1908 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1910 public boolean onMenuItemClick(MenuItem item) {
1916 // Add a `Download Image` entry.
1917 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1919 public boolean onMenuItemClick(MenuItem item) {
1920 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
1921 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
1922 downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1927 // Add a `Copy URL` entry.
1928 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1930 public boolean onMenuItemClick(MenuItem item) {
1931 // Save the image URL in a `ClipData`.
1932 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1934 // Set the `ClipData` as the clipboard's primary clip.
1935 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
1940 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1941 menu.add(R.string.cancel);
1947 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
1948 // Get shortcutNameEditText from the alert dialog.
1949 EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
1951 // Create the bookmark shortcut based on formattedUrlString.
1952 Intent bookmarkShortcut = new Intent();
1953 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
1954 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
1956 // Place the bookmark shortcut on the home screen.
1957 Intent placeBookmarkShortcut = new Intent();
1958 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
1959 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
1960 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIconBitmap);
1961 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
1962 sendBroadcast(placeBookmarkShortcut);
1966 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
1967 // Download the image if it has an HTTP or HTTPS URI.
1968 if (imageUrl.startsWith("http")) {
1969 // Get a handle for the system `DOWNLOAD_SERVICE`.
1970 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
1972 // Parse `imageUrl`.
1973 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
1975 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
1976 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
1977 if (firstPartyCookiesEnabled) {
1978 // Get the cookies for `imageUrl`.
1979 String cookies = cookieManager.getCookie(imageUrl);
1981 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
1982 downloadRequest.addRequestHeader("Cookie", cookies);
1985 // Get the file name from `dialogFragment`.
1986 EditText downloadImageNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_image_name);
1987 String imageName = downloadImageNameEditText.getText().toString();
1989 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
1990 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `imageName`.
1991 downloadRequest.setDestinationInExternalFilesDir(this, "/", imageName);
1992 } else { // Only set the title using `imageName`.
1993 downloadRequest.setTitle(imageName);
1996 // Allow `MediaScanner` to index the download if it is a media file.
1997 downloadRequest.allowScanningByMediaScanner();
1999 // Add the URL as the description for the download.
2000 downloadRequest.setDescription(imageUrl);
2002 // Show the download notification after the download is completed.
2003 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2005 // Initiate the download.
2006 downloadManager.enqueue(downloadRequest);
2007 } else { // The image is not an HTTP or HTTPS URI.
2008 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
2013 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
2014 // Download the file if it has an HTTP or HTTPS URI.
2015 if (downloadUrl.startsWith("http")) {
2017 // Get a handle for the system `DOWNLOAD_SERVICE`.
2018 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2020 // Parse `downloadUrl`.
2021 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
2023 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
2024 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2025 if (firstPartyCookiesEnabled) {
2026 // Get the cookies for `downloadUrl`.
2027 String cookies = cookieManager.getCookie(downloadUrl);
2029 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2030 downloadRequest.addRequestHeader("Cookie", cookies);
2033 // Get the file name from `dialogFragment`.
2034 EditText downloadFileNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_file_name);
2035 String fileName = downloadFileNameEditText.getText().toString();
2037 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
2038 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download location to `/sdcard/Android/data/com.stoutner.privacybrowser.standard/files` named `fileName`.
2039 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
2040 } else { // Only set the title using `fileName`.
2041 downloadRequest.setTitle(fileName);
2044 // Allow `MediaScanner` to index the download if it is a media file.
2045 downloadRequest.allowScanningByMediaScanner();
2047 // Add the URL as the description for the download.
2048 downloadRequest.setDescription(downloadUrl);
2050 // Show the download notification after the download is completed.
2051 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2053 // Initiate the download.
2054 downloadManager.enqueue(downloadRequest);
2055 } else { // The download is not an HTTP or HTTPS URI.
2056 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
2060 public void viewSslCertificate(View view) {
2061 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
2062 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
2063 viewSslCertificateDialogFragment.show(getFragmentManager(), getResources().getString(R.string.view_ssl_certificate));
2067 public void onSslErrorCancel() {
2068 sslErrorHandler.cancel();
2072 public void onSslErrorProceed() {
2073 sslErrorHandler.proceed();
2077 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
2078 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2079 navigatingHistory = true;
2081 // Load the history entry.
2082 mainWebView.goBackOrForward(moveBackOrForwardSteps);
2086 public void onClearHistory() {
2087 // Clear the history.
2088 mainWebView.clearHistory();
2091 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
2093 public void onBackPressed() {
2094 // Close the navigation drawer if it is available. GravityCompat.START is the drawer on the left on Left-to-Right layout text.
2095 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
2096 drawerLayout.closeDrawer(GravityCompat.START);
2098 // Load the previous URL if available.
2099 if (mainWebView.canGoBack()) {
2100 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2101 navigatingHistory = true;
2104 mainWebView.goBack();
2106 // Pass `onBackPressed()` to the system.
2107 super.onBackPressed();
2112 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
2113 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
2114 String unformattedUrlString = urlTextBox.getText().toString().trim();
2116 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
2117 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
2118 // Add `http://` at the beginning if it is missing. Otherwise the app will segfault.
2119 if (!unformattedUrlString.startsWith("http")) {
2120 unformattedUrlString = "http://" + unformattedUrlString;
2123 // Initialize `unformattedUrl`.
2124 URL unformattedUrl = null;
2126 // 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.
2128 unformattedUrl = new URL(unformattedUrlString);
2129 } catch (MalformedURLException e) {
2130 e.printStackTrace();
2133 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2134 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2135 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2136 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2137 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2138 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2141 Uri.Builder formattedUri = new Uri.Builder();
2142 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2144 // Decode `formattedUri` as a `String` in `UTF-8`.
2145 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
2147 // Sanitize the search input and convert it to a search.
2148 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2150 // Add the base search URL.
2151 formattedUrlString = searchURL + encodedUrlString;
2154 loadUrl(formattedUrlString);
2156 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
2157 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2161 private void loadUrl(String url) {
2162 // Apply any custom domain settings.
2163 applyDomainSettings(url);
2166 mainWebView.loadUrl(url, customHeaders);
2169 public void findPreviousOnPage(View view) {
2170 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
2171 mainWebView.findNext(false);
2174 public void findNextOnPage(View view) {
2175 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2176 mainWebView.findNext(true);
2179 public void closeFindOnPage(View view) {
2180 // Delete the contents of `find_on_page_edittext`.
2181 findOnPageEditText.setText(null);
2183 // Clear the highlighted phrases.
2184 mainWebView.clearMatches();
2186 // Hide the Find on Page `RelativeLayout`.
2187 findOnPageLinearLayout.setVisibility(View.GONE);
2189 // Show the URL app bar.
2190 supportAppBar.setVisibility(View.VISIBLE);
2192 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
2193 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2196 private void applyAppSettings() {
2197 // Get a handle for `sharedPreferences`. `this` references the current context.
2198 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2200 // Store the values from `sharedPreferences` in variables.
2201 String homepageString = sharedPreferences.getString("homepage", "https://start.duckduckgo.com");
2202 String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
2203 String torSearchString = sharedPreferences.getString("tor_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
2204 String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
2205 String searchString = sharedPreferences.getString("search", "https://duckduckgo.com/html/?q=");
2206 String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
2207 adBlockerEnabled = sharedPreferences.getBoolean("block_ads", true);
2208 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
2209 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
2210 boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
2211 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
2212 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
2213 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
2214 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh", false);
2215 displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
2217 // Set the homepage, search, and proxy options.
2218 if (proxyThroughOrbot) { // Set the Tor options.
2219 // Set `torHomepageString` as `homepage`.
2220 homepage = torHomepageString;
2222 // If formattedUrlString is null assign the homepage to it.
2223 if (formattedUrlString == null) {
2224 formattedUrlString = homepage;
2227 // Set the search URL.
2228 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
2229 searchURL = torSearchCustomURLString;
2230 } else { // Use the string from the pre-built list.
2231 searchURL = torSearchString;
2234 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
2235 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
2237 // Set the `appBar` background to indicate proxying through Orbot is enabled. `this` refers to the context.
2239 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
2241 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
2244 // Display a message to the user if we are waiting on Orbot.
2245 if (!orbotStatus.equals("ON")) {
2246 // Set `waitingForOrbot`.
2247 waitingForOrbot = true;
2249 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
2250 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
2252 } else { // Set the non-Tor options.
2253 // Set `homepageString` as `homepage`.
2254 homepage = homepageString;
2256 // If formattedUrlString is null assign the homepage to it.
2257 if (formattedUrlString == null) {
2258 formattedUrlString = homepage;
2261 // Set the search URL.
2262 if (searchString.equals("Custom URL")) { // Get the custom URL string.
2263 searchURL = searchCustomURLString;
2264 } else { // Use the string from the pre-built list.
2265 searchURL = searchString;
2268 // Reset the proxy to default. The host is `""` and the port is `"0"`.
2269 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
2271 // Set the default `appBar` background. `this` refers to the context.
2273 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
2275 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
2278 // Reset `waitingForOrbot.
2279 waitingForOrbot = false;
2282 // Set swipe to refresh.
2283 swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
2285 // Set Do Not Track status.
2286 if (doNotTrackEnabled) {
2287 customHeaders.put("DNT", "1");
2289 customHeaders.remove("DNT");
2292 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
2293 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
2294 if (hideSystemBarsOnFullscreen) { // Hide everything.
2295 // Remove the translucent navigation setting if it is currently flagged.
2296 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2298 // Remove the translucent status bar overlay.
2299 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2301 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
2302 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
2304 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
2305 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
2306 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
2308 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
2309 } else { // Hide everything except the status and navigation bars.
2310 // Add the translucent status flag if it is unset.
2311 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2313 if (translucentNavigationBarOnFullscreen) {
2314 // Set the navigation bar to be translucent.
2315 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2317 // Set the navigation bar to be black.
2318 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2321 } else { // Switch to normal viewing mode.
2322 // Reset `inFullScreenBrowsingMode` to `false`.
2323 inFullScreenBrowsingMode = false;
2325 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
2326 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
2330 // Show the `BannerAd` in the free flavor.
2331 if (BuildConfig.FLAVOR.contentEquals("free")) {
2332 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
2333 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2335 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2336 adView = findViewById(R.id.adview);
2339 // Remove the translucent navigation bar flag if it is set.
2340 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2342 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
2343 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2345 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
2346 rootCoordinatorLayout.setSystemUiVisibility(0);
2348 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
2349 rootCoordinatorLayout.setFitsSystemWindows(true);
2353 // We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2354 @SuppressWarnings("deprecation")
2355 private void applyDomainSettings(String url) {
2356 // Reset `navigatingHistory`.
2357 navigatingHistory = false;
2359 // Parse the URL into a URI.
2360 Uri uri = Uri.parse(url);
2362 // Extract the domain from `uri`.
2363 String hostName = uri.getHost();
2365 // Initialize `loadingNewDomainName`.
2366 boolean loadingNewDomainName;
2368 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
2369 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
2370 //noinspection SimplifiableIfStatement
2371 if ((hostName == null) || (currentDomainName == null)) {
2372 loadingNewDomainName = true;
2373 } else { // Determine if `hostName` equals `currentDomainName`.
2374 loadingNewDomainName = !hostName.equals(currentDomainName);
2377 // 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.
2378 if (loadingNewDomainName) {
2379 // Set the new `hostname` as the `currentDomainName`.
2380 currentDomainName = hostName;
2382 // Reset `favoriteIconBitmap` and display it in the `appbar`.
2383 favoriteIconBitmap = favoriteIconDefaultBitmap;
2384 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
2386 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
2387 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2388 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2390 // Get a full cursor from `domainsDatabaseHelper`.
2391 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
2393 // Initialize `domainSettingsSet`.
2394 Set<String> domainSettingsSet = new HashSet<>();
2396 // Get the domain name column index.
2397 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
2399 // Populate `domainSettingsSet`.
2400 for (int i = 0; i < domainNameCursor.getCount(); i++) {
2401 // Move `domainsCursor` to the current row.
2402 domainNameCursor.moveToPosition(i);
2404 // Store the domain name in `domainSettingsSet`.
2405 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
2408 // Close `domainNameCursor.
2409 domainNameCursor.close();
2411 // Initialize variables to track if domain settings will be applied and, if so, under which name.
2412 domainSettingsApplied = false;
2413 String domainNameInDatabase = null;
2415 // Check the hostname.
2416 if (domainSettingsSet.contains(hostName)) {
2417 domainSettingsApplied = true;
2418 domainNameInDatabase = hostName;
2421 // If `hostName` is not `null`, check all the subdomains of `hostName` against wildcard domains in `domainCursor`.
2422 if (hostName != null) {
2423 while (hostName.contains(".") && !domainSettingsApplied) { // Stop checking if we run out of `.` or if we already know that `domainSettingsApplied` is `true`.
2424 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
2425 domainSettingsApplied = true;
2426 domainNameInDatabase = "*." + hostName;
2429 // Strip out the lowest subdomain of `host`.
2430 hostName = hostName.substring(hostName.indexOf(".") + 1);
2434 // Get a handle for the shared preference. `this` references the current context.
2435 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2437 if (domainSettingsApplied) { // The url we are loading has custom domain settings.
2438 // Get a cursor for the current host and move it to the first position.
2439 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
2440 currentHostDomainSettingsCursor.moveToFirst();
2442 // Get the settings from the cursor.
2443 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
2444 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
2445 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
2446 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
2447 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
2448 String userAgentString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
2449 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
2450 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
2452 // Close `currentHostDomainSettingsCursor`.
2453 currentHostDomainSettingsCursor.close();
2455 // Apply the domain settings.
2456 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2457 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2458 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2459 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2460 mainWebView.getSettings().setTextZoom(fontSize);
2462 // Set third-party cookies status if API >= 21.
2463 if (Build.VERSION.SDK_INT >= 21) {
2464 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2467 // Set the user agent.
2468 if (userAgentString.equals("WebView default user agent")) {
2469 // Set the user agent to `""`, which uses the default value.
2470 mainWebView.getSettings().setUserAgentString("");
2472 // Use the selected user agent.
2473 mainWebView.getSettings().setUserAgentString(userAgentString);
2476 // 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.
2478 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
2480 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
2482 } else { // The URL we are loading does not have custom domain settings. Load the defaults.
2483 // Store the values from `sharedPreferences` in variables.
2484 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
2485 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
2486 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
2487 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
2488 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
2489 String userAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
2490 String customUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
2491 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
2493 // Apply the default settings.
2494 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2495 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2496 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2497 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2498 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
2500 // Set third-party cookies status if API >= 21.
2501 if (Build.VERSION.SDK_INT >= 21) {
2502 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2505 // Set the default user agent.
2506 switch (userAgentString) {
2507 case "WebView default user agent":
2508 // Set the user agent to `""`, which uses the default value.
2509 mainWebView.getSettings().setUserAgentString("");
2512 case "Custom user agent":
2513 // Set the custom user agent.
2514 mainWebView.getSettings().setUserAgentString(customUserAgentString);
2518 // Use the selected user agent.
2519 mainWebView.getSettings().setUserAgentString(userAgentString);
2523 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2524 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
2527 // Close `domainsDatabaseHelper`.
2528 domainsDatabaseHelper.close();
2530 // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode. `true` indicates that custom domain settings are applied.
2531 onTheFlyDisplayImagesSet = false;
2532 setDisplayWebpageImages();
2534 // Update the privacy icons, but only if `mainMenu` has already been populated.
2535 if (mainMenu != null) {
2536 updatePrivacyIcons(true);
2541 private void setDisplayWebpageImages() {
2542 if (!onTheFlyDisplayImagesSet) {
2543 if (domainSettingsApplied) { // Custom domain settings are applied.
2544 switch (displayWebpageImagesInt) {
2545 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
2546 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
2549 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
2550 mainWebView.getSettings().setLoadsImagesAutomatically(true);
2553 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
2554 mainWebView.getSettings().setLoadsImagesAutomatically(false);
2557 } else { // Default settings are applied.
2558 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
2563 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
2564 // Get handles for the icons.
2565 MenuItem privacyIconMenuItem = mainMenu.findItem(R.id.toggle_javascript);
2566 MenuItem firstPartyCookiesIconMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
2567 MenuItem domStorageIconMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
2568 MenuItem formDataIconMenuItem = mainMenu.findItem(R.id.toggle_save_form_data);
2570 // Update `privacyIcon`.
2571 if (javaScriptEnabled) { // JavaScript is enabled.
2572 privacyIconMenuItem.setIcon(R.drawable.javascript_enabled);
2573 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
2574 privacyIconMenuItem.setIcon(R.drawable.warning);
2575 } else { // All the dangerous features are disabled.
2576 privacyIconMenuItem.setIcon(R.drawable.privacy_mode);
2579 // Update `firstPartyCookiesIcon`.
2580 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
2581 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_enabled);
2582 } else { // First-party cookies are disabled.
2583 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled);
2586 // Update `domStorageIcon`.
2587 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
2588 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_enabled);
2589 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
2590 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled);
2591 } else { // JavaScript is disabled, so DOM storage is ghosted.
2592 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted);
2595 // Update `formDataIcon`.
2596 if (saveFormDataEnabled) { // Form data is enabled.
2597 formDataIconMenuItem.setIcon(R.drawable.form_data_enabled);
2598 } else { // Form data is disabled.
2599 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled);
2602 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`. `this` references the current activity.
2603 if (runInvalidateOptionsMenu) {
2604 ActivityCompat.invalidateOptionsMenu(this);
2608 private void highlightUrlText() {
2609 String urlString = urlTextBox.getText().toString();
2611 if (urlString.startsWith("http://")) { // Highlight connections that are not encrypted.
2612 urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
2613 urlTextBox.getText().setSpan(boldStyleSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
2614 } else if (urlString.startsWith("https://")) { // Highlight connections that are encrypted.
2615 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
2618 // Get the index of the `/` immediately after the domain name.
2619 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
2621 // De-emphasize the text after the domain name.
2622 if (endOfDomainName > 0) {
2623 urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);