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.drawable.BitmapDrawable;
38 import android.graphics.drawable.Drawable;
39 import android.net.Uri;
40 import android.net.http.SslCertificate;
41 import android.net.http.SslError;
42 import android.os.Build;
43 import android.os.Bundle;
44 import android.os.Handler;
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.util.Patterns;
67 import android.view.ContextMenu;
68 import android.view.GestureDetector;
69 import android.view.KeyEvent;
70 import android.view.Menu;
71 import android.view.MenuItem;
72 import android.view.MotionEvent;
73 import android.view.View;
74 import android.view.WindowManager;
75 import android.view.inputmethod.InputMethodManager;
76 import android.webkit.CookieManager;
77 import android.webkit.DownloadListener;
78 import android.webkit.HttpAuthHandler;
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.HttpAuthenticationDialog;
101 import com.stoutner.privacybrowser.dialogs.PinnedSslCertificateMismatchDialog;
102 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
103 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
104 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
105 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
106 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
107 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
109 import java.io.BufferedReader;
110 import java.io.ByteArrayInputStream;
112 import java.io.IOException;
113 import java.io.InputStreamReader;
114 import java.io.UnsupportedEncodingException;
115 import java.net.MalformedURLException;
117 import java.net.URLDecoder;
118 import java.net.URLEncoder;
119 import java.util.Date;
120 import java.util.HashMap;
121 import java.util.HashSet;
122 import java.util.Map;
123 import java.util.Set;
125 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
126 public class MainWebViewActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, CreateHomeScreenShortcutDialog.CreateHomeScreenSchortcutListener,
127 HttpAuthenticationDialog.HttpAuthenticationListener, PinnedSslCertificateMismatchDialog.PinnedSslCertificateMismatchListener, SslCertificateErrorDialog.SslCertificateErrorListener, DownloadFileDialog.DownloadFileListener,
128 DownloadImageDialog.DownloadImageListener, UrlHistoryDialog.UrlHistoryListener {
130 // `darkTheme` is public static so it can be accessed from `AboutActivity`, `GuideActivity`, `AddDomainDialog`, `SettingsActivity`, `DomainsActivity`, `DomainsListFragment`, `BookmarksActivity`, `BookmarksDatabaseViewActivity`,
131 // `CreateBookmarkDialog`, `CreateBookmarkFolderDialog`, `DownloadFileDialog`, `DownloadImageDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`, `HttpAuthenticationDialog`, `MoveToFolderDialog`, `SslCertificateErrorDialog`, `UrlHistoryDialog`,
132 // `ViewSslCertificateDialog`, `CreateHomeScreenShortcutDialog`, and `OrbotProxyHelper`. It is also used in `onCreate()`, `applyAppSettings()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
133 public static boolean darkTheme;
135 // `favoriteIconBitmap` is public static so it can be accessed from `CreateHomeScreenShortcutDialog`, `BookmarksActivity`, `CreateBookmarkDialog`, `CreateBookmarkFolderDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`,
136 // and `ViewSslCertificateDialog`. It is also used in `onCreate()`, `onCreateHomeScreenShortcutCreate()`, and `applyDomainSettings`.
137 public static Bitmap favoriteIconBitmap;
139 // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`, `CreateBookmarkDialog`, and `AddDomainDialog`.
140 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
141 public static String formattedUrlString;
143 // `sslCertificate` is public static so it can be accessed from `DomainsActivity`, `DomainsListFragment`, `DomainSettingsFragment`, `PinnedSslCertificateMismatchDialog`, and `ViewSslCertificateDialog`. It is also used in `onCreate()`.
144 public static SslCertificate sslCertificate;
146 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`.
147 public static String orbotStatus;
149 // `webViewTitle` is public static so it can be accessed from `CreateBookmarkDialog` and `CreateHomeScreenShortcutDialog`. It is also used in `onCreate()`.
150 public static String webViewTitle;
152 // `displayWebpageImagesBoolean` is public static so it can be accessed from `DomainSettingsFragment`. It is also used in `applyAppSettings()` and `applyDomainSettings()`.
153 public static boolean displayWebpageImagesBoolean;
155 // `reloadOnRestart` is public static so it can be accessed from `SettingsFragment`. It is also used in `onRestart()`
156 public static boolean reloadOnRestart;
158 // `reloadUrlOnRestart` is public static so it can be accessed from `SettingsFragment`. It is also used in `onRestart()`.
159 public static boolean loadUrlOnRestart;
161 // The pinned domain SSL Certificate variables are public static so they can be accessed from `PinnedSslCertificateMismatchDialog`. They are also used in `onCreate()` and `applyDomainSettings()`.
162 public static int domainSettingsDatabaseId;
163 public static String pinnedDomainSslIssuedToCNameString;
164 public static String pinnedDomainSslIssuedToONameString;
165 public static String pinnedDomainSslIssuedToUNameString;
166 public static String pinnedDomainSslIssuedByCNameString;
167 public static String pinnedDomainSslIssuedByONameString;
168 public static String pinnedDomainSslIssuedByUNameString;
169 public static Date pinnedDomainSslStartDate;
170 public static Date pinnedDomainSslEndDate;
173 // `appBar` is used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applyAppSettings()`.
174 private ActionBar appBar;
176 // `navigatingHistory` is used in `onCreate()`, `onNavigationItemSelected()`, `onSslMismatchBack()`, and `applyDomainSettings()`.
177 private boolean navigatingHistory;
179 // `favoriteIconDefaultBitmap` is used in `onCreate()` and `applyDomainSettings`.
180 private Bitmap favoriteIconDefaultBitmap;
182 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, and `onBackPressed()`.
183 private DrawerLayout drawerLayout;
185 // `rootCoordinatorLayout` is used in `onCreate()` and `applyAppSettings()`.
186 private CoordinatorLayout rootCoordinatorLayout;
188 // `mainWebView` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`, `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`
189 // `onSslMismatchBack()`, and `setDisplayWebpageImages()`.
190 private WebView mainWebView;
192 // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
193 private FrameLayout fullScreenVideoFrameLayout;
195 // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu`, and `onRestart()`.
196 private SwipeRefreshLayout swipeRefreshLayout;
198 // `urlAppBarRelativeLayout` is used in `onCreate()` and `applyDomainSettings()`.
199 private RelativeLayout urlAppBarRelativeLayout;
201 // `favoriteIconImageView` is used in `onCreate()` and `applyDomainSettings()`
202 private ImageView favoriteIconImageView;
204 // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `loadUrlFromTextBox()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
205 private CookieManager cookieManager;
207 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
208 private final Map<String, String> customHeaders = new HashMap<>();
210 // `javaScriptEnabled` is also used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
211 private boolean javaScriptEnabled;
213 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applyDomainSettings()`.
214 private boolean firstPartyCookiesEnabled;
216 // `thirdPartyCookiesEnabled` used in `onCreate()`, `onPrepareOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
217 private boolean thirdPartyCookiesEnabled;
219 // `domStorageEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
220 private boolean domStorageEnabled;
222 // `saveFormDataEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
223 private boolean saveFormDataEnabled;
225 // `nightMode` is used in `onCreate()` and `applyDomainSettings()`.
226 private boolean nightMode;
228 // `swipeToRefreshEnabled` is used in `onPrepareOptionsMenu()` and `applyAppSettings()`.
229 private boolean swipeToRefreshEnabled;
231 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applyAppSettings()`.
232 private String homepage;
234 // `searchURL` is used in `loadURLFromTextBox()` and `applyAppSettings()`.
235 private String searchURL;
237 // `adBlockerEnabled` is used in `onCreate()` and `applyAppSettings()`.
238 private boolean adBlockerEnabled;
240 // `privacyBrowserRuntime` is used in `onCreate()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
241 private Runtime privacyBrowserRuntime;
243 // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
244 private boolean incognitoModeEnabled;
246 // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
247 private boolean fullScreenBrowsingModeEnabled;
249 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
250 private boolean inFullScreenBrowsingMode;
252 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
253 private boolean hideSystemBarsOnFullscreen;
255 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
256 private boolean translucentNavigationBarOnFullscreen;
258 // `currentDomainName` is used in `onCreate()`, `onNavigationItemSelected()`, `onSslMismatchProceed()`, and `applyDomainSettings()`.
259 private String currentDomainName;
261 // `ignorePinnedSslCertificateForDomain` is used in `onCreate()`, `onSslMismatchProceed()`, and `applyDomainSettings()`.
262 private boolean ignorePinnedSslCertificate;
264 // `waitingForOrbot` is used in `onCreate()` and `applyAppSettings()`.
265 private boolean waitingForOrbot;
267 // `domainSettingsApplied` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
268 private boolean domainSettingsApplied;
270 // `displayWebpageImagesInt` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
271 private int displayWebpageImagesInt;
273 // `onTheFlyDisplayImagesSet` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
274 private boolean onTheFlyDisplayImagesSet;
276 // `waitingForOrbotData` is used in `onCreate()` and `applyAppSettings()`.
277 private String waitingForOrbotHTMLString;
279 // `privateDataDirectoryString` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
280 private String privateDataDirectoryString;
282 // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
283 private LinearLayout findOnPageLinearLayout;
285 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
286 private EditText findOnPageEditText;
288 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
289 private Menu mainMenu;
291 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
292 private ActionBarDrawerToggle drawerToggle;
294 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
295 private Toolbar supportAppBar;
297 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, `loadUrl()`, and `highlightUrlText()`.
298 private EditText urlTextBox;
300 // `redColorSpan` is used in `onCreate()` and `highlightUrlText()`.
301 private ForegroundColorSpan redColorSpan;
303 // `initialGrayColorSpan` is sued in `onCreate()` and `highlightUrlText()`.
304 private ForegroundColorSpan initialGrayColorSpan;
306 // `finalGrayColorSpam` is used in `onCreate()` and `highlightUrlText()`.
307 private ForegroundColorSpan finalGrayColorSpan;
309 // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
312 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
313 private SslErrorHandler sslErrorHandler;
315 // `httpAuthHandler` is used in `onCreate()`, `onHttpAuthenticationCancel()`, and `onHttpAuthenticationProceed()`.
316 private static HttpAuthHandler httpAuthHandler;
318 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
319 private InputMethodManager inputMethodManager;
321 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
322 private RelativeLayout mainWebViewRelativeLayout;
324 // `urlIsLoading` is used in `onCreate()`, `loadUrl()`, and `applyDomainSettings()`.
325 private boolean urlIsLoading;
327 // `pinnedDomainSslCertificate` is used in `onCreate()` and `applyDomainSettings()`.
328 private boolean pinnedDomainSslCertificate;
332 // 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.
333 @SuppressLint("SetJavaScriptEnabled")
334 // Remove Android Studio's warning about deprecations. We have to use the deprecated `getColor()` until API >= 23.
335 @SuppressWarnings("deprecation")
336 protected void onCreate(Bundle savedInstanceState) {
337 // Get a handle for `sharedPreferences`. `this` references the current context.
338 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
340 // Get the theme preference.
341 darkTheme = sharedPreferences.getBoolean("dark_theme", false);
343 // Set the activity theme.
345 setTheme(R.style.PrivacyBrowserDark);
347 setTheme(R.style.PrivacyBrowserLight);
350 // Run the default commands.
351 super.onCreate(savedInstanceState);
353 // Set the content view.
354 setContentView(R.layout.main_drawerlayout);
356 // Get a handle for `inputMethodManager`.
357 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
359 // We need to use the `SupportActionBar` from `android.support.v7.app.ActionBar` until the minimum API is >= 21.
360 supportAppBar = (Toolbar) findViewById(R.id.app_bar);
361 setSupportActionBar(supportAppBar);
362 appBar = getSupportActionBar();
364 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
365 assert appBar != null;
367 // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
368 appBar.setCustomView(R.layout.url_app_bar);
369 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
371 // Initialize the `ForegroundColorSpans` and `StyleSpan` for highlighting `urlTextBox`. We have to use the deprecated `getColor()` until API >= 23.
372 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
373 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
374 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
376 // Get a handle for `urlTextBox`.
377 urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.url_edittext);
379 // Remove the formatting from `urlTextBar` when the user is editing the text.
380 urlTextBox.setOnFocusChangeListener(new View.OnFocusChangeListener() {
382 public void onFocusChange(View v, boolean hasFocus) {
383 if (hasFocus) { // The user is editing `urlTextBox`.
384 // Remove the highlighting.
385 urlTextBox.getText().removeSpan(redColorSpan);
386 urlTextBox.getText().removeSpan(initialGrayColorSpan);
387 urlTextBox.getText().removeSpan(finalGrayColorSpan);
388 } else { // The user has stopped editing `urlTextBox`.
389 // Reapply the highlighting.
395 // Set the `Go` button on the keyboard to load the URL in `urlTextBox`.
396 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
398 public boolean onKey(View v, int keyCode, KeyEvent event) {
399 // If the event is a key-down event on the `enter` button, load the URL.
400 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
401 // Load the URL into the mainWebView and consume the event.
403 loadUrlFromTextBox();
404 } catch (UnsupportedEncodingException e) {
407 // If the enter key was pressed, consume the event.
410 // If any other key was pressed, do not consume the event.
416 // Set `waitingForOrbotHTMLString`.
417 waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
419 // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
420 currentDomainName = "";
421 orbotStatus = "unknown";
422 waitingForOrbot = false;
424 // Create an Orbot status `BroadcastReceiver`.
425 BroadcastReceiver orbotStatusBroadcastReceiver = new BroadcastReceiver() {
427 public void onReceive(Context context, Intent intent) {
428 // Store the content of the status message in `orbotStatus`.
429 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
431 // If we are waiting on Orbot, load the website now that Orbot is connected.
432 if (orbotStatus.equals("ON") && waitingForOrbot) {
433 // Reset `waitingForOrbot`.
434 waitingForOrbot = false;
436 // Load `formattedUrlString
437 loadUrl(formattedUrlString);
442 // Register `orbotStatusBroadcastReceiver` on `this` context.
443 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
445 // Get handles for views that need to be accessed.
446 drawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout);
447 rootCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.root_coordinatorlayout);
448 mainWebViewRelativeLayout = (RelativeLayout) findViewById(R.id.main_webview_relativelayout);
449 mainWebView = (WebView) findViewById(R.id.main_webview);
450 findOnPageLinearLayout = (LinearLayout) findViewById(R.id.find_on_page_linearlayout);
451 findOnPageEditText = (EditText) findViewById(R.id.find_on_page_edittext);
452 fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.full_screen_video_framelayout);
453 urlAppBarRelativeLayout = (RelativeLayout) findViewById(R.id.url_app_bar_relativelayout);
454 favoriteIconImageView = (ImageView) findViewById(R.id.favorite_icon);
456 // Create a double-tap listener to toggle full-screen mode.
457 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
458 // Override `onDoubleTap()`. All other events are handled using the default settings.
460 public boolean onDoubleTap(MotionEvent event) {
461 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
462 // Toggle `inFullScreenBrowsingMode`.
463 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
465 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
466 // Hide the `appBar`.
469 // Hide the `BannerAd` in the free flavor.
470 if (BuildConfig.FLAVOR.contentEquals("free")) {
471 BannerAd.hideAd(adView);
474 // Modify the system bars.
475 if (hideSystemBarsOnFullscreen) { // Hide everything.
476 // Remove the translucent overlays.
477 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
479 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
480 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
482 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
483 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
484 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
486 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
488 // Set `rootCoordinatorLayout` to fill the whole screen.
489 rootCoordinatorLayout.setFitsSystemWindows(false);
490 } else { // Hide everything except the status and navigation bars.
491 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
492 rootCoordinatorLayout.setFitsSystemWindows(false);
494 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.
495 // Set the navigation bar to be translucent.
496 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
499 } else { // Switch to normal viewing mode.
500 // Show the `appBar`.
503 // Show the `BannerAd` in the free flavor.
504 if (BuildConfig.FLAVOR.contentEquals("free")) {
505 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
506 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
508 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
509 adView = findViewById(R.id.adview);
512 // Remove the translucent navigation bar flag if it is set.
513 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
515 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
516 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
518 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
519 rootCoordinatorLayout.setSystemUiVisibility(0);
521 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
522 rootCoordinatorLayout.setFitsSystemWindows(true);
525 // Consume the double-tap.
527 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
533 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
534 mainWebView.setOnTouchListener(new View.OnTouchListener() {
536 public boolean onTouch(View v, MotionEvent event) {
537 // Send the `event` to `gestureDetector`.
538 return gestureDetector.onTouchEvent(event);
542 // Update `findOnPageCountTextView`.
543 mainWebView.setFindListener(new WebView.FindListener() {
544 // Get a handle for `findOnPageCountTextView`.
545 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
548 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
549 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
550 // Set `findOnPageCountTextView` to `0/0`.
551 findOnPageCountTextView.setText(R.string.zero_of_zero);
552 } else if (isDoneCounting) { // There are matches.
553 // `activeMatchOrdinal` is zero-based.
554 int activeMatch = activeMatchOrdinal + 1;
556 // Set `findOnPageCountTextView`.
557 findOnPageCountTextView.setText(activeMatch + "/" + numberOfMatches);
562 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
563 findOnPageEditText.addTextChangedListener(new TextWatcher() {
565 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
570 public void onTextChanged(CharSequence s, int start, int before, int count) {
575 public void afterTextChanged(Editable s) {
576 // Search for the text in `mainWebView`.
577 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
581 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
582 findOnPageEditText.setOnKeyListener(new View.OnKeyListener() {
584 public boolean onKey(View v, int keyCode, KeyEvent event) {
585 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
586 // Hide the soft keyboard. `0` indicates no additional flags.
587 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
589 // Consume the event.
591 } else { // A different key was pressed.
592 // Do not consume the event.
598 // Implement swipe to refresh
599 swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refreshlayout);
600 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
601 swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
603 public void onRefresh() {
604 mainWebView.reload();
608 // `DrawerTitle` identifies the `DrawerLayout` in accessibility mode.
609 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
611 // Listen for touches on the navigation menu.
612 final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationview);
613 navigationView.setNavigationItemSelectedListener(this);
615 // 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.
616 final Menu navigationMenu = navigationView.getMenu();
617 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
618 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
619 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
621 // The `DrawerListener` allows us to update the Navigation Menu.
622 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
624 public void onDrawerSlide(View drawerView, float slideOffset) {
628 public void onDrawerOpened(View drawerView) {
632 public void onDrawerClosed(View drawerView) {
636 public void onDrawerStateChanged(int newState) {
637 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // The drawer is opening or closing.
638 // Update the `Back`, `Forward`, and `History` menu items.
639 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
640 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
641 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
643 // Hide the keyboard (if displayed) so we can see the navigation menu. `0` indicates no additional flags.
644 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
646 // Clear the focus from `urlTextBox` if it has it.
647 urlTextBox.clearFocus();
652 // drawerToggle creates the hamburger icon at the start of the AppBar.
653 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
655 // Initialize `adServerSet`.
656 final Set<String> adServersSet = new HashSet<>();
658 // Load the list of ad servers into memory.
660 // Load `pgl.yoyo.org_adservers.txt` into a `BufferedReader`.
661 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(getAssets().open("pgl.yoyo.org_adservers.txt")));
663 // Create a string for storing each ad server.
666 // Populate `adServersSet`.
667 while ((adServer = bufferedReader.readLine()) != null) {
668 adServersSet.add(adServer);
671 // Close `bufferedReader`.
672 bufferedReader.close();
673 } catch (IOException ioException) {
674 // We're pretty sure the asset exists, so we don't need to worry about the `IOException` ever being thrown.
677 mainWebView.setWebViewClient(new WebViewClient() {
678 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
679 // We have to use the deprecated `shouldOverrideUrlLoading` until API >= 24.
680 @SuppressWarnings("deprecation")
682 public boolean shouldOverrideUrlLoading(WebView view, String url) {
683 if (url.startsWith("mailto:")) { // Load the URL in an external email program because it begins with `mailto:`.
684 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
685 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
687 // Parse the url and set it as the data for the `Intent`.
688 emailIntent.setData(Uri.parse(url));
690 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
691 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
694 startActivity(emailIntent);
696 // Returning `true` indicates the application is handling the URL.
698 } else { // Load the URL in Privacy Browser.
699 // Apply the domain settings for the new URL.
700 applyDomainSettings(url);
702 // Returning `false` causes the current `WebView` to handle the URL and prevents it from adding redirects to the history list.
707 // Block ads. We have to use the deprecated `shouldInterceptRequest` until minimum API >= 21.
708 @SuppressWarnings("deprecation")
710 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
711 if (adBlockerEnabled) { // Block ads.
712 // Extract the host from `url`.
713 Uri requestUri = Uri.parse(url);
714 String requestHost = requestUri.getHost();
716 // Initialize a variable to track if this is an ad server.
717 boolean requestHostIsAdServer = false;
719 // Check all the subdomains of `requestHost` if it is not `null` against the ad server database.
720 if (requestHost != null) {
721 while (requestHost.contains(".") && !requestHostIsAdServer) { // Stop checking if we run out of `.` or if we already know that `requestHostIsAdServer` is `true`.
722 if (adServersSet.contains(requestHost)) {
723 requestHostIsAdServer = true;
726 // Strip out the lowest subdomain of `requestHost`.
727 requestHost = requestHost.substring(requestHost.indexOf(".") + 1);
731 if (requestHostIsAdServer) { // It is an ad server.
732 // Return an empty `WebResourceResponse`.
733 return new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
734 } else { // It is not an ad server.
735 // `return null` loads the requested resource.
738 } else { // Ad blocking is disabled.
739 // `return null` loads the requested resource.
744 // Handle HTTP authentication requests.
746 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
747 // Store `handler` so it can be accessed from `onHttpAuthenticationCancel()` and `onHttpAuthenticationProceed()`.
748 httpAuthHandler = handler;
750 // Display the HTTP authentication dialog.
751 AppCompatDialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm);
752 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
755 // Update the URL in urlTextBox when the page starts to load.
757 public void onPageStarted(WebView view, String url, Bitmap favicon) {
758 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
760 mainWebView.setVisibility(View.INVISIBLE);
763 // Check to see if we are waiting on Orbot.
764 if (!waitingForOrbot) { // We are not waiting on Orbot, so we need to process the URL.
765 // 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.
766 formattedUrlString = url;
768 // Display the formatted URL text.
769 urlTextBox.setText(formattedUrlString);
771 // Apply text highlighting to `urlTextBox`.
774 // Apply any custom domain settings if the URL was loaded by navigating history.
775 if (navigatingHistory) {
776 applyDomainSettings(url);
779 // Set `urlIsLoading` to `true`, so that redirects while loading do not trigger changes in the user agent, which forces another reload of the existing page.
784 // It is necessary to update `formattedUrlString` and `urlTextBox` after the page finishes loading because the final URL can change during load.
786 public void onPageFinished(WebView view, String url) {
787 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
788 urlIsLoading = false;
790 // Clear the cache and history if Incognito Mode is enabled.
791 if (incognitoModeEnabled) {
792 // Clear the cache. `true` includes disk files.
793 mainWebView.clearCache(true);
795 // Clear the back/forward history.
796 mainWebView.clearHistory();
798 // Manually delete cache folders.
800 // Delete the main `cache` folder.
801 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
803 // 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`.
804 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
805 } catch (IOException e) {
806 // Do nothing if an error is thrown.
810 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
811 if (!waitingForOrbot) {
812 // Check to see if `WebView` has set `url` to be `about:blank`.
813 if (url.equals("about:blank")) { // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
814 // Set `formattedUrlString` to `""`.
815 formattedUrlString = "";
817 urlTextBox.setText(formattedUrlString);
819 // Request focus for `urlTextBox`.
820 urlTextBox.requestFocus();
822 // Display the keyboard.
823 inputMethodManager.showSoftInput(urlTextBox, 0);
825 // Apply the domain settings. This clears any settings from the previous domain.
826 applyDomainSettings(formattedUrlString);
827 } else { // `WebView` has loaded a webpage.
828 // Set `formattedUrlString`.
829 formattedUrlString = url;
831 // Only update `urlTextBox` if the user is not typing in it.
832 if (!urlTextBox.hasFocus()) {
833 // Display the formatted URL text.
834 urlTextBox.setText(formattedUrlString);
836 // Apply text highlighting to `urlTextBox`.
841 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
842 sslCertificate = mainWebView.getCertificate();
844 // Check the current website SSL certificate against the pinned SSL certificate if there is a pinned SSL certificate the user has not chosen to ignore it for this session.
845 if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate) {
846 // Initialize the current SSL certificate variables.
847 String currentWebsiteIssuedToCName = "";
848 String currentWebsiteIssuedToOName = "";
849 String currentWebsiteIssuedToUName = "";
850 String currentWebsiteIssuedByCName = "";
851 String currentWebsiteIssuedByOName = "";
852 String currentWebsiteIssuedByUName = "";
853 Date currentWebsiteSslStartDate = null;
854 Date currentWebsiteSslEndDate = null;
857 // Extract the individual pieces of information from the current website SSL certificate if it is not null.
858 if (sslCertificate != null) {
859 currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
860 currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
861 currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
862 currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
863 currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
864 currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
865 currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
866 currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
869 // Initialize `String` variables to store the SSL certificate dates. `Strings` are needed to compare the values below, which doesn't work with `Dates` if they are `null`.
870 String currentWebsiteSslStartDateString = "";
871 String currentWebsiteSslEndDateString = "";
872 String pinnedDomainSslStartDateString = "";
873 String pinnedDomainSslEndDateString = "";
875 // Convert the `Dates` to `Strings` if they are not `null`.
876 if (currentWebsiteSslStartDate != null) {
877 currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
880 if (currentWebsiteSslEndDate != null) {
881 currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
884 if (pinnedDomainSslStartDate != null) {
885 pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
888 if (pinnedDomainSslEndDate != null) {
889 pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
892 // Check to see if the pinned SSL certificate matches the current website certificate.
893 if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) || !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) ||
894 !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) || !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
895 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) { // The pinned SSL certificate doesn't match the current domain certificate.
896 //Display the pinned SSL certificate mismatch `AlertDialog`.
897 AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
898 pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
904 // Handle SSL Certificate errors.
906 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
907 // Get the current website SSL certificate.
908 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
910 // Extract the individual pieces of information from the current website SSL certificate.
911 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
912 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
913 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
914 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
915 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
916 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
917 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
918 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
920 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
921 if (pinnedDomainSslCertificate &&
922 currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) && currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) &&
923 currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) && currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
924 currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) { // An SSL certificate is pinned and matches the current domain certificate.
925 // Proceed to the website without displaying an error.
927 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
928 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
929 sslErrorHandler = handler;
931 // Display the SSL error `AlertDialog`.
932 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
933 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
938 // Get a handle for the progress bar.
939 final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress_bar);
941 mainWebView.setWebChromeClient(new WebChromeClient() {
942 // Update the progress bar when a page is loading.
944 public void onProgressChanged(WebView view, int progress) {
945 progressBar.setProgress(progress);
946 if (progress < 100) {
947 // Show the progress bar.
948 progressBar.setVisibility(View.VISIBLE);
950 // Hide the progress bar.
951 progressBar.setVisibility(View.GONE);
953 // Inject the night mode CSS if night mode is enabled.
955 // `background-color: #212121` sets the background to be dark gray. `color: #BDBDBD` sets the text color to be light gray. `box-shadow: none` removes a lower underline on links used by WordPress.
956 // `text-decoration: none` removes all text underlines. `text-shadow: none` removes text shadows, which usually have a hard coded color. `border: none` removes all borders, which can also be used to underline text.
957 // `a {color: #1565C0}` sets links to be a dark blue. `!important` takes precedent over any existing sub-settings.
958 mainWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; style.innerHTML = '" +
959 "* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important; text-shadow: none !important; border: none !important;}" +
960 "a {color: #1565C0 !important;}" +
961 "'; parent.appendChild(style)})()", null);
964 // Initialize a `Handler` to display `mainWebView`, which may have been hid by a night mode domain setting even if night mode is not currently enabled.
965 Handler displayWebViewHandler = new Handler();
967 // Setup a `Runnable` to display `mainWebView` after a delay to allow the CSS to be applied.
968 Runnable displayWebViewRunnable = new Runnable() {
970 mainWebView.setVisibility(View.VISIBLE);
974 // Use `displayWebViewHandler` to delay the displaying of `mainWebView` for 1000 milliseconds.
975 displayWebViewHandler.postDelayed(displayWebViewRunnable, 1000);
977 //Stop the `SwipeToRefresh` indicator if it is running
978 swipeRefreshLayout.setRefreshing(false);
982 // Set the favorite icon when it changes.
984 public void onReceivedIcon(WebView view, Bitmap icon) {
985 // Only update the favorite icon if the website has finished loading.
986 if (progressBar.getVisibility() == View.GONE) {
987 // Save a copy of the favorite icon.
988 favoriteIconBitmap = icon;
990 // Place the favorite icon in the appBar.
991 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
995 // Save a copy of the title when it changes.
997 public void onReceivedTitle(WebView view, String title) {
998 // Save a copy of the title.
999 webViewTitle = title;
1002 // Enter full screen video
1004 public void onShowCustomView(View view, CustomViewCallback callback) {
1005 // Pause the ad if this is the free flavor.
1006 if (BuildConfig.FLAVOR.contentEquals("free")) {
1007 BannerAd.pauseAd(adView);
1010 // Remove the translucent overlays.
1011 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1013 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1014 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1016 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1017 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1018 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
1020 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1022 // Set `rootCoordinatorLayout` to fill the entire screen.
1023 rootCoordinatorLayout.setFitsSystemWindows(false);
1025 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
1026 fullScreenVideoFrameLayout.addView(view);
1027 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
1030 // Exit full screen video
1031 public void onHideCustomView() {
1032 // Hide `fullScreenVideoFrameLayout`.
1033 fullScreenVideoFrameLayout.removeAllViews();
1034 fullScreenVideoFrameLayout.setVisibility(View.GONE);
1036 // Add the translucent status flag. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1037 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1039 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars. This also clears the `SYSTEM_UI` flags.
1040 rootCoordinatorLayout.setFitsSystemWindows(true);
1042 // Show the ad if this is the free flavor.
1043 if (BuildConfig.FLAVOR.contentEquals("free")) {
1044 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
1045 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1047 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1048 adView = findViewById(R.id.adview);
1053 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
1054 registerForContextMenu(mainWebView);
1056 // Allow the downloading of files.
1057 mainWebView.setDownloadListener(new DownloadListener() {
1059 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
1060 // Show the `DownloadFileDialog` `AlertDialog` and name this instance `@string/download`.
1061 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
1062 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
1066 // Allow pinch to zoom.
1067 mainWebView.getSettings().setBuiltInZoomControls(true);
1069 // Hide zoom controls.
1070 mainWebView.getSettings().setDisplayZoomControls(false);
1072 // Set `mainWebView` to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
1073 mainWebView.getSettings().setUseWideViewPort(true);
1075 // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
1076 mainWebView.getSettings().setLoadWithOverviewMode(true);
1078 // Explicitly disable geolocation.
1079 mainWebView.getSettings().setGeolocationEnabled(false);
1081 // Initialize cookieManager.
1082 cookieManager = CookieManager.getInstance();
1084 // 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).
1085 customHeaders.put("X-Requested-With", "");
1087 // 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.
1088 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
1090 // Get the intent that started the app.
1091 final Intent launchingIntent = getIntent();
1093 // Extract the launching intent data as `launchingIntentUriData`.
1094 final Uri launchingIntentUriData = launchingIntent.getData();
1096 // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
1097 if (launchingIntentUriData != null) {
1098 formattedUrlString = launchingIntentUriData.toString();
1101 // Get a handle for the `Runtime`.
1102 privacyBrowserRuntime = Runtime.getRuntime();
1104 // Store the application's private data directory.
1105 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`.
1107 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
1108 inFullScreenBrowsingMode = false;
1110 // Initialize AdView for the free flavor.
1111 adView = findViewById(R.id.adview);
1113 // Initialize the privacy settings variables.
1114 javaScriptEnabled = false;
1115 firstPartyCookiesEnabled = false;
1116 thirdPartyCookiesEnabled = false;
1117 domStorageEnabled = false;
1118 saveFormDataEnabled = false;
1121 // Initialize `webViewTitle`.
1122 webViewTitle = getString(R.string.no_title);
1124 // Initialize `favoriteIconBitmap`. We have to use `ContextCompat` until API >= 21.
1125 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
1126 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
1127 favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
1129 // If the favorite icon is null, load the default.
1130 if (favoriteIconBitmap == null) {
1131 favoriteIconBitmap = favoriteIconDefaultBitmap;
1134 // Apply the app settings from the shared preferences.
1137 // Load `formattedUrlString` if we are not waiting for Orbot to connect.
1138 if (!waitingForOrbot) {
1139 loadUrl(formattedUrlString);
1144 protected void onNewIntent(Intent intent) {
1145 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1148 if (intent.getData() != null) {
1149 // Get the intent data and convert it to a string.
1150 final Uri intentUriData = intent.getData();
1151 formattedUrlString = intentUriData.toString();
1154 // Close the navigation drawer if it is open.
1155 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1156 drawerLayout.closeDrawer(GravityCompat.START);
1159 // Load the website.
1160 loadUrl(formattedUrlString);
1162 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1163 mainWebView.requestFocus();
1167 public void onRestart() {
1170 // Apply the app settings, which may have been changed in `SettingsActivity`.
1173 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1174 updatePrivacyIcons(true);
1176 // Set the display webpage images mode.
1177 setDisplayWebpageImages();
1179 // Reload the webpage if displaying of images has been disabled in `SettingsFragment`.
1180 if (reloadOnRestart) {
1181 // Reload `mainWebView`.
1182 mainWebView.reload();
1184 // Reset `reloadOnRestartBoolean`.
1185 reloadOnRestart = false;
1188 // Load the URL on restart to apply changes to night mode.
1189 if (loadUrlOnRestart) {
1190 // Load the current `formattedUrlString`.
1191 loadUrl(formattedUrlString);
1193 // Reset `loadUrlOnRestart.
1194 loadUrlOnRestart = false;
1198 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1200 public void onResume() {
1203 // Resume JavaScript (if enabled).
1204 mainWebView.resumeTimers();
1206 // Resume `mainWebView`.
1207 mainWebView.onResume();
1209 // Resume the adView for the free flavor.
1210 if (BuildConfig.FLAVOR.contentEquals("free")) {
1211 BannerAd.resumeAd(adView);
1216 public void onPause() {
1217 // Pause `mainWebView`.
1218 mainWebView.onPause();
1220 // Stop all JavaScript.
1221 mainWebView.pauseTimers();
1223 // Pause the adView or it will continue to consume resources in the background on the free flavor.
1224 if (BuildConfig.FLAVOR.contentEquals("free")) {
1225 BannerAd.pauseAd(adView);
1232 public boolean onCreateOptionsMenu(Menu menu) {
1233 // Inflate the menu; this adds items to the action bar if it is present.
1234 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1236 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1239 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1240 updatePrivacyIcons(false);
1242 // Get handles for the menu items.
1243 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1244 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1245 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1246 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1248 // Only display third-party cookies if SDK >= 21
1249 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1251 // Get the shared preference values. `this` references the current context.
1252 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1254 // Set the status of the additional app bar icons. The default is `false`.
1255 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
1256 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1257 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1258 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1259 } else { //Do not display the additional icons.
1260 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1261 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1262 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1269 public boolean onPrepareOptionsMenu(Menu menu) {
1270 // Get handles for the menu items.
1271 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1272 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1273 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1274 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1275 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1276 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1277 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);
1278 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1279 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1280 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1282 // Set the status of the menu item checkboxes.
1283 toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1284 toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1285 toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1286 toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);
1287 displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1289 // Enable third-party cookies if first-party cookies are enabled.
1290 toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1292 // Enable `DOM Storage` if JavaScript is enabled.
1293 toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
1295 // Enable `Clear Cookies` if there are any.
1296 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1298 // Get a count of the number of files in the `Local Storage` directory.
1299 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1300 int localStorageDirectoryNumberOfFiles = 0;
1301 if (localStorageDirectory.exists()) {
1302 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1305 // Get a count of the number of files in the `IndexedDB` directory.
1306 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1307 int indexedDBDirectoryNumberOfFiles = 0;
1308 if (indexedDBDirectory.exists()) {
1309 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1312 // Enable `Clear DOM Storage` if there is any.
1313 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1315 // Enable `Clear Form Data` is there is any.
1316 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1317 clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
1319 // Initialize font size variables.
1320 int fontSize = mainWebView.getSettings().getTextZoom();
1321 String fontSizeTitle;
1322 MenuItem selectedFontSizeMenuItem;
1324 // Prepare the font size title and current size menu item.
1327 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
1328 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1332 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
1333 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1337 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
1338 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1342 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1343 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1347 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
1348 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1352 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
1353 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1357 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
1358 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1362 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
1363 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1367 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1368 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1372 // Set the font size title and select the current size menu item.
1373 fontSizeMenuItem.setTitle(fontSizeTitle);
1374 selectedFontSizeMenuItem.setChecked(true);
1376 // Only show `Refresh` if `swipeToRefresh` is disabled.
1377 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
1379 // Run all the other default commands.
1380 super.onPrepareOptionsMenu(menu);
1382 // `return true` displays the menu.
1387 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1388 @SuppressLint("SetJavaScriptEnabled")
1389 // removeAllCookies is deprecated, but it is required for API < 21.
1390 @SuppressWarnings("deprecation")
1391 public boolean onOptionsItemSelected(MenuItem menuItem) {
1392 int menuItemId = menuItem.getItemId();
1394 // Set the commands that relate to the menu entries.
1395 switch (menuItemId) {
1396 case R.id.toggle_javascript:
1397 // Switch the status of javaScriptEnabled.
1398 javaScriptEnabled = !javaScriptEnabled;
1400 // Apply the new JavaScript status.
1401 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1403 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1404 updatePrivacyIcons(true);
1406 // Display a `Snackbar`.
1407 if (javaScriptEnabled) { // JavaScrip is enabled.
1408 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1409 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
1410 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1411 } else { // Privacy mode.
1412 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1415 // Reload the WebView.
1416 mainWebView.reload();
1419 case R.id.toggle_first_party_cookies:
1420 // Switch the status of firstPartyCookiesEnabled.
1421 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1423 // Update the menu checkbox.
1424 menuItem.setChecked(firstPartyCookiesEnabled);
1426 // Apply the new cookie status.
1427 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1429 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1430 updatePrivacyIcons(true);
1432 // Display a `Snackbar`.
1433 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1434 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1435 } else if (javaScriptEnabled){ // JavaScript is still enabled.
1436 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1437 } else { // Privacy mode.
1438 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1441 // Reload the WebView.
1442 mainWebView.reload();
1445 case R.id.toggle_third_party_cookies:
1446 if (Build.VERSION.SDK_INT >= 21) {
1447 // Switch the status of thirdPartyCookiesEnabled.
1448 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1450 // Update the menu checkbox.
1451 menuItem.setChecked(thirdPartyCookiesEnabled);
1453 // Apply the new cookie status.
1454 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1456 // Display a `Snackbar`.
1457 if (thirdPartyCookiesEnabled) {
1458 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1460 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1463 // Reload the WebView.
1464 mainWebView.reload();
1465 } // Else do nothing because SDK < 21.
1468 case R.id.toggle_dom_storage:
1469 // Switch the status of domStorageEnabled.
1470 domStorageEnabled = !domStorageEnabled;
1472 // Update the menu checkbox.
1473 menuItem.setChecked(domStorageEnabled);
1475 // Apply the new DOM Storage status.
1476 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1478 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1479 updatePrivacyIcons(true);
1481 // Display a `Snackbar`.
1482 if (domStorageEnabled) {
1483 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1485 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1488 // Reload the WebView.
1489 mainWebView.reload();
1492 case R.id.toggle_save_form_data:
1493 // Switch the status of saveFormDataEnabled.
1494 saveFormDataEnabled = !saveFormDataEnabled;
1496 // Update the menu checkbox.
1497 menuItem.setChecked(saveFormDataEnabled);
1499 // Apply the new form data status.
1500 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1502 // Display a `Snackbar`.
1503 if (saveFormDataEnabled) {
1504 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1506 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1509 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1510 updatePrivacyIcons(true);
1512 // Reload the WebView.
1513 mainWebView.reload();
1516 case R.id.clear_cookies:
1517 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1518 .setAction(R.string.undo, new View.OnClickListener() {
1520 public void onClick(View v) {
1521 // Do nothing because everything will be handled by `onDismissed()` below.
1524 .addCallback(new Snackbar.Callback() {
1526 public void onDismissed(Snackbar snackbar, int event) {
1528 // The user pushed the `Undo` button.
1529 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1533 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1535 // `cookieManager.removeAllCookie()` varies by SDK.
1536 if (Build.VERSION.SDK_INT < 21) {
1537 cookieManager.removeAllCookie();
1539 // `null` indicates no callback.
1540 cookieManager.removeAllCookies(null);
1548 case R.id.clear_dom_storage:
1549 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1550 .setAction(R.string.undo, new View.OnClickListener() {
1552 public void onClick(View v) {
1553 // Do nothing because everything will be handled by `onDismissed()` below.
1556 .addCallback(new Snackbar.Callback() {
1558 public void onDismissed(Snackbar snackbar, int event) {
1560 // The user pushed the `Undo` button.
1561 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1565 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1567 // Delete the DOM Storage.
1568 WebStorage webStorage = WebStorage.getInstance();
1569 webStorage.deleteAllData();
1571 // Manually remove `IndexedDB` if it exists.
1573 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1574 } catch (IOException e) {
1575 // Do nothing if an error is thrown.
1583 case R.id.clear_form_data:
1584 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1585 .setAction(R.string.undo, new View.OnClickListener() {
1587 public void onClick(View v) {
1588 // Do nothing because everything will be handled by `onDismissed()` below.
1591 .addCallback(new Snackbar.Callback() {
1593 public void onDismissed(Snackbar snackbar, int event) {
1595 // The user pushed the `Undo` button.
1596 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1600 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1602 // Delete the form data.
1603 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1604 mainWebViewDatabase.clearFormData();
1611 case R.id.font_size_twenty_five_percent:
1612 mainWebView.getSettings().setTextZoom(25);
1615 case R.id.font_size_fifty_percent:
1616 mainWebView.getSettings().setTextZoom(50);
1619 case R.id.font_size_seventy_five_percent:
1620 mainWebView.getSettings().setTextZoom(75);
1623 case R.id.font_size_one_hundred_percent:
1624 mainWebView.getSettings().setTextZoom(100);
1627 case R.id.font_size_one_hundred_twenty_five_percent:
1628 mainWebView.getSettings().setTextZoom(125);
1631 case R.id.font_size_one_hundred_fifty_percent:
1632 mainWebView.getSettings().setTextZoom(150);
1635 case R.id.font_size_one_hundred_seventy_five_percent:
1636 mainWebView.getSettings().setTextZoom(175);
1639 case R.id.font_size_two_hundred_percent:
1640 mainWebView.getSettings().setTextZoom(200);
1643 case R.id.display_images:
1644 if (mainWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1645 mainWebView.getSettings().setLoadsImagesAutomatically(false);
1646 mainWebView.reload();
1647 } else { // Images are not currently loaded automatically.
1648 mainWebView.getSettings().setLoadsImagesAutomatically(true);
1651 // Set `onTheFlyDisplayImagesSet`.
1652 onTheFlyDisplayImagesSet = true;
1656 // Setup the share string.
1657 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
1659 // Create the share intent.
1660 Intent shareIntent = new Intent();
1661 shareIntent.setAction(Intent.ACTION_SEND);
1662 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1663 shareIntent.setType("text/plain");
1666 startActivity(Intent.createChooser(shareIntent, "Share URL"));
1669 case R.id.find_on_page:
1670 // Hide the URL app bar.
1671 supportAppBar.setVisibility(View.GONE);
1673 // Show the Find on Page `RelativeLayout`.
1674 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1676 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android. http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1677 findOnPageEditText.postDelayed(new Runnable() {
1681 // Set the focus on `findOnPageEditText`.
1682 findOnPageEditText.requestFocus();
1684 // Display the keyboard. `0` sets no input flags.
1685 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1691 // Get a `PrintManager` instance.
1692 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1694 // Convert `mainWebView` to `printDocumentAdapter`.
1695 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
1697 // Print the document. The print attributes are `null`.
1698 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1701 case R.id.add_to_homescreen:
1702 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
1703 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
1704 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
1706 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
1710 mainWebView.reload();
1714 // Don't consume the event.
1715 return super.onOptionsItemSelected(menuItem);
1719 // removeAllCookies is deprecated, but it is required for API < 21.
1720 @SuppressWarnings("deprecation")
1722 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1723 int menuItemId = menuItem.getItemId();
1725 switch (menuItemId) {
1731 if (mainWebView.canGoBack()) {
1732 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1733 navigatingHistory = true;
1735 // Load the previous website in the history.
1736 mainWebView.goBack();
1741 if (mainWebView.canGoForward()) {
1742 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1743 navigatingHistory = true;
1745 // Load the next website in the history.
1746 mainWebView.goForward();
1751 // Get the `WebBackForwardList`.
1752 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
1754 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
1755 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
1756 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
1759 case R.id.bookmarks:
1760 // Launch BookmarksActivity.
1761 Intent bookmarksIntent = new Intent(this, BookmarksActivity.class);
1762 startActivity(bookmarksIntent);
1765 case R.id.downloads:
1766 // Launch the system Download Manager.
1767 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1769 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1770 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1772 startActivity(downloadManagerIntent);
1776 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1777 currentDomainName = "";
1779 // Launch `SettingsActivity`.
1780 Intent settingsIntent = new Intent(this, SettingsActivity.class);
1781 startActivity(settingsIntent);
1785 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1786 currentDomainName = "";
1788 // Launch `DomainsActivity`.
1789 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1790 startActivity(domainsIntent);
1794 // Launch `GuideActivity`.
1795 Intent guideIntent = new Intent(this, GuideActivity.class);
1796 startActivity(guideIntent);
1800 // Launch `AboutActivity`.
1801 Intent aboutIntent = new Intent(this, AboutActivity.class);
1802 startActivity(aboutIntent);
1805 case R.id.clearAndExit:
1806 // Get a handle for `sharedPreferences`. `this` references the current context.
1807 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1809 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
1812 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
1813 // The command to remove cookies changed slightly in API 21.
1814 if (Build.VERSION.SDK_INT >= 21) {
1815 cookieManager.removeAllCookies(null);
1817 cookieManager.removeAllCookie();
1820 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1822 // We have to use two commands because `Runtime.exec()` does not like `*`.
1823 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
1824 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
1825 } catch (IOException e) {
1826 // Do nothing if an error is thrown.
1830 // Clear DOM storage.
1831 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
1832 // Ask `WebStorage` to clear the DOM storage.
1833 WebStorage webStorage = WebStorage.getInstance();
1834 webStorage.deleteAllData();
1836 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1838 // We have to use a `String[]` because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1839 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1841 // We have to use multiple commands because `Runtime.exec()` does not like `*`.
1842 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1843 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1844 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1845 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1846 } catch (IOException e) {
1847 // Do nothing if an error is thrown.
1852 if (clearEverything || sharedPreferences.getBoolean("clear_form_data", true)) {
1853 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1854 webViewDatabase.clearFormData();
1856 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1858 // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1859 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
1860 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
1861 } catch (IOException e) {
1862 // Do nothing if an error is thrown.
1867 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
1868 // `true` includes disk files.
1869 mainWebView.clearCache(true);
1871 // Manually delete the cache directories.
1873 // Delete the main cache directory.
1874 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1876 // 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.
1877 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1878 } catch (IOException e) {
1879 // Do nothing if an error is thrown.
1883 // Clear SSL certificate preferences.
1884 mainWebView.clearSslPreferences();
1886 // Clear the back/forward history.
1887 mainWebView.clearHistory();
1889 // Clear `formattedUrlString`.
1890 formattedUrlString = null;
1892 // Clear `customHeaders`.
1893 customHeaders.clear();
1895 // Detach all views from `mainWebViewRelativeLayout`.
1896 mainWebViewRelativeLayout.removeAllViews();
1898 // Destroy the internal state of `mainWebView`.
1899 mainWebView.destroy();
1901 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
1902 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
1903 if (clearEverything) {
1905 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
1906 } catch (IOException e) {
1907 // Do nothing if an error is thrown.
1911 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
1912 if (Build.VERSION.SDK_INT >= 21) {
1913 finishAndRemoveTask();
1918 // Remove the terminated program from RAM. The status code is `0`.
1923 // Close the navigation drawer.
1924 drawerLayout.closeDrawer(GravityCompat.START);
1929 public void onPostCreate(Bundle savedInstanceState) {
1930 super.onPostCreate(savedInstanceState);
1932 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
1933 drawerToggle.syncState();
1937 public void onConfigurationChanged(Configuration newConfig) {
1938 super.onConfigurationChanged(newConfig);
1940 // Reload the ad for the free flavor if we are not in full screen mode.
1941 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
1943 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1945 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1946 adView = findViewById(R.id.adview);
1949 // `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
1950 // ActivityCompat.invalidateOptionsMenu(this);
1954 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
1955 // Store the `HitTestResult`.
1956 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
1959 final String imageUrl;
1960 final String linkUrl;
1962 // Get a handle for the `ClipboardManager`.
1963 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
1965 switch (hitTestResult.getType()) {
1966 // `SRC_ANCHOR_TYPE` is a link.
1967 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1968 // Get the target URL.
1969 linkUrl = hitTestResult.getExtra();
1971 // Set the target URL as the title of the `ContextMenu`.
1972 menu.setHeaderTitle(linkUrl);
1974 // Add a `Load URL` entry.
1975 menu.add(R.string.load_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1977 public boolean onMenuItemClick(MenuItem item) {
1983 // Add a `Copy URL` entry.
1984 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1986 public boolean onMenuItemClick(MenuItem item) {
1987 // Save the link URL in a `ClipData`.
1988 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
1990 // Set the `ClipData` as the clipboard's primary clip.
1991 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
1996 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1997 menu.add(R.string.cancel);
2000 case WebView.HitTestResult.EMAIL_TYPE:
2001 // Get the target URL.
2002 linkUrl = hitTestResult.getExtra();
2004 // Set the target URL as the title of the `ContextMenu`.
2005 menu.setHeaderTitle(linkUrl);
2007 // Add a `Write Email` entry.
2008 menu.add(R.string.write_email).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2010 public boolean onMenuItemClick(MenuItem item) {
2011 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2012 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2014 // Parse the url and set it as the data for the `Intent`.
2015 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2017 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2018 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2021 startActivity(emailIntent);
2026 // Add a `Copy Email Address` entry.
2027 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2029 public boolean onMenuItemClick(MenuItem item) {
2030 // Save the email address in a `ClipData`.
2031 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2033 // Set the `ClipData` as the clipboard's primary clip.
2034 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2039 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2040 menu.add(R.string.cancel);
2043 // `IMAGE_TYPE` is an image.
2044 case WebView.HitTestResult.IMAGE_TYPE:
2045 // Get the image URL.
2046 imageUrl = hitTestResult.getExtra();
2048 // Set the image URL as the title of the `ContextMenu`.
2049 menu.setHeaderTitle(imageUrl);
2051 // Add a `View Image` entry.
2052 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2054 public boolean onMenuItemClick(MenuItem item) {
2060 // Add a `Download Image` entry.
2061 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2063 public boolean onMenuItemClick(MenuItem item) {
2064 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
2065 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2066 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2071 // Add a `Copy URL` entry.
2072 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2074 public boolean onMenuItemClick(MenuItem item) {
2075 // Save the image URL in a `ClipData`.
2076 ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2078 // Set the `ClipData` as the clipboard's primary clip.
2079 clipboardManager.setPrimaryClip(srcImageTypeClipData);
2084 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2085 menu.add(R.string.cancel);
2089 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2090 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2091 // Get the image URL.
2092 imageUrl = hitTestResult.getExtra();
2094 // Set the image URL as the title of the `ContextMenu`.
2095 menu.setHeaderTitle(imageUrl);
2097 // Add a `View Image` entry.
2098 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2100 public boolean onMenuItemClick(MenuItem item) {
2106 // Add a `Download Image` entry.
2107 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2109 public boolean onMenuItemClick(MenuItem item) {
2110 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
2111 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2112 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2117 // Add a `Copy URL` entry.
2118 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2120 public boolean onMenuItemClick(MenuItem item) {
2121 // Save the image URL in a `ClipData`.
2122 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2124 // Set the `ClipData` as the clipboard's primary clip.
2125 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2130 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2131 menu.add(R.string.cancel);
2137 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
2138 // Get shortcutNameEditText from the alert dialog.
2139 EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
2141 // Create the bookmark shortcut based on formattedUrlString.
2142 Intent bookmarkShortcut = new Intent();
2143 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
2144 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
2146 // Place the bookmark shortcut on the home screen.
2147 Intent placeBookmarkShortcut = new Intent();
2148 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
2149 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
2150 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIconBitmap);
2151 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
2152 sendBroadcast(placeBookmarkShortcut);
2156 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
2157 // Download the image if it has an HTTP or HTTPS URI.
2158 if (imageUrl.startsWith("http")) {
2159 // Get a handle for the system `DOWNLOAD_SERVICE`.
2160 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2162 // Parse `imageUrl`.
2163 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
2165 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
2166 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2167 if (firstPartyCookiesEnabled) {
2168 // Get the cookies for `imageUrl`.
2169 String cookies = cookieManager.getCookie(imageUrl);
2171 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2172 downloadRequest.addRequestHeader("Cookie", cookies);
2175 // Get the file name from `dialogFragment`.
2176 EditText downloadImageNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_image_name);
2177 String imageName = downloadImageNameEditText.getText().toString();
2179 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
2180 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `imageName`.
2181 downloadRequest.setDestinationInExternalFilesDir(this, "/", imageName);
2182 } else { // Only set the title using `imageName`.
2183 downloadRequest.setTitle(imageName);
2186 // Allow `MediaScanner` to index the download if it is a media file.
2187 downloadRequest.allowScanningByMediaScanner();
2189 // Add the URL as the description for the download.
2190 downloadRequest.setDescription(imageUrl);
2192 // Show the download notification after the download is completed.
2193 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2195 // Initiate the download.
2196 downloadManager.enqueue(downloadRequest);
2197 } else { // The image is not an HTTP or HTTPS URI.
2198 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
2203 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
2204 // Download the file if it has an HTTP or HTTPS URI.
2205 if (downloadUrl.startsWith("http")) {
2207 // Get a handle for the system `DOWNLOAD_SERVICE`.
2208 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2210 // Parse `downloadUrl`.
2211 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
2213 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
2214 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2215 if (firstPartyCookiesEnabled) {
2216 // Get the cookies for `downloadUrl`.
2217 String cookies = cookieManager.getCookie(downloadUrl);
2219 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2220 downloadRequest.addRequestHeader("Cookie", cookies);
2223 // Get the file name from `dialogFragment`.
2224 EditText downloadFileNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_file_name);
2225 String fileName = downloadFileNameEditText.getText().toString();
2227 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
2228 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download location to `/sdcard/Android/data/com.stoutner.privacybrowser.standard/files` named `fileName`.
2229 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
2230 } else { // Only set the title using `fileName`.
2231 downloadRequest.setTitle(fileName);
2234 // Allow `MediaScanner` to index the download if it is a media file.
2235 downloadRequest.allowScanningByMediaScanner();
2237 // Add the URL as the description for the download.
2238 downloadRequest.setDescription(downloadUrl);
2240 // Show the download notification after the download is completed.
2241 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2243 // Initiate the download.
2244 downloadManager.enqueue(downloadRequest);
2245 } else { // The download is not an HTTP or HTTPS URI.
2246 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
2251 public void onHttpAuthenticationCancel() {
2252 // Cancel the `HttpAuthHandler`.
2253 httpAuthHandler.cancel();
2257 public void onHttpAuthenticationProceed(AppCompatDialogFragment dialogFragment) {
2258 // Get handles for the `EditTexts`.
2259 EditText usernameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.http_authentication_username);
2260 EditText passwordEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.http_authentication_password);
2262 // Proceed with the HTTP authentication.
2263 httpAuthHandler.proceed(usernameEditText.getText().toString(), passwordEditText.getText().toString());
2266 public void viewSslCertificate(View view) {
2267 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
2268 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
2269 viewSslCertificateDialogFragment.show(getFragmentManager(), getString(R.string.view_ssl_certificate));
2273 public void onSslErrorCancel() {
2274 sslErrorHandler.cancel();
2278 public void onSslErrorProceed() {
2279 sslErrorHandler.proceed();
2283 public void onSslMismatchBack() {
2284 if (mainWebView.canGoBack()) { // There is a back page in the history.
2285 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2286 navigatingHistory = true;
2289 mainWebView.goBack();
2290 } else { // There are no pages to go back to.
2291 // Load a blank page
2297 public void onSslMismatchProceed() {
2298 // Do not check the pinned SSL certificate for this domain again until the domain changes.
2299 ignorePinnedSslCertificate = true;
2303 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
2304 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2305 navigatingHistory = true;
2307 // Load the history entry.
2308 mainWebView.goBackOrForward(moveBackOrForwardSteps);
2312 public void onClearHistory() {
2313 // Clear the history.
2314 mainWebView.clearHistory();
2317 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
2319 public void onBackPressed() {
2320 // Close the navigation drawer if it is available. GravityCompat.START is the drawer on the left on Left-to-Right layout text.
2321 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
2322 drawerLayout.closeDrawer(GravityCompat.START);
2324 // Load the previous URL if available.
2325 if (mainWebView.canGoBack()) {
2326 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2327 navigatingHistory = true;
2330 mainWebView.goBack();
2332 // Pass `onBackPressed()` to the system.
2333 super.onBackPressed();
2338 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
2339 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
2340 String unformattedUrlString = urlTextBox.getText().toString().trim();
2342 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
2343 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
2344 // Add `http://` at the beginning if it is missing. Otherwise the app will segfault.
2345 if (!unformattedUrlString.startsWith("http")) {
2346 unformattedUrlString = "http://" + unformattedUrlString;
2349 // Initialize `unformattedUrl`.
2350 URL unformattedUrl = null;
2352 // 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.
2354 unformattedUrl = new URL(unformattedUrlString);
2355 } catch (MalformedURLException e) {
2356 e.printStackTrace();
2359 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2360 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2361 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2362 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2363 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2364 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2367 Uri.Builder formattedUri = new Uri.Builder();
2368 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2370 // Decode `formattedUri` as a `String` in `UTF-8`.
2371 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
2373 // Sanitize the search input and convert it to a search.
2374 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2376 // Add the base search URL.
2377 formattedUrlString = searchURL + encodedUrlString;
2380 loadUrl(formattedUrlString);
2382 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
2383 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2387 private void loadUrl(String url) {
2388 // Apply any custom domain settings.
2389 applyDomainSettings(url);
2392 mainWebView.loadUrl(url, customHeaders);
2394 // Set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
2395 urlIsLoading = true;
2398 public void findPreviousOnPage(View view) {
2399 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
2400 mainWebView.findNext(false);
2403 public void findNextOnPage(View view) {
2404 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2405 mainWebView.findNext(true);
2408 public void closeFindOnPage(View view) {
2409 // Delete the contents of `find_on_page_edittext`.
2410 findOnPageEditText.setText(null);
2412 // Clear the highlighted phrases.
2413 mainWebView.clearMatches();
2415 // Hide the Find on Page `RelativeLayout`.
2416 findOnPageLinearLayout.setVisibility(View.GONE);
2418 // Show the URL app bar.
2419 supportAppBar.setVisibility(View.VISIBLE);
2421 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
2422 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2425 private void applyAppSettings() {
2426 // Get a handle for `sharedPreferences`. `this` references the current context.
2427 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2429 // Store the values from `sharedPreferences` in variables.
2430 String homepageString = sharedPreferences.getString("homepage", "https://start.duckduckgo.com");
2431 String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
2432 String torSearchString = sharedPreferences.getString("tor_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
2433 String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
2434 String searchString = sharedPreferences.getString("search", "https://duckduckgo.com/html/?q=");
2435 String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
2436 adBlockerEnabled = sharedPreferences.getBoolean("block_ads", true);
2437 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
2438 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
2439 boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
2440 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
2441 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
2442 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
2443 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh", false);
2444 displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
2446 // Set the homepage, search, and proxy options.
2447 if (proxyThroughOrbot) { // Set the Tor options.
2448 // Set `torHomepageString` as `homepage`.
2449 homepage = torHomepageString;
2451 // If formattedUrlString is null assign the homepage to it.
2452 if (formattedUrlString == null) {
2453 formattedUrlString = homepage;
2456 // Set the search URL.
2457 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
2458 searchURL = torSearchCustomURLString;
2459 } else { // Use the string from the pre-built list.
2460 searchURL = torSearchString;
2463 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
2464 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
2466 // Set the `appBar` background to indicate proxying through Orbot is enabled. `this` refers to the context.
2468 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
2470 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
2473 // Display a message to the user if we are waiting on Orbot.
2474 if (!orbotStatus.equals("ON")) {
2475 // Set `waitingForOrbot`.
2476 waitingForOrbot = true;
2478 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
2479 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
2481 } else { // Set the non-Tor options.
2482 // Set `homepageString` as `homepage`.
2483 homepage = homepageString;
2485 // If formattedUrlString is null assign the homepage to it.
2486 if (formattedUrlString == null) {
2487 formattedUrlString = homepage;
2490 // Set the search URL.
2491 if (searchString.equals("Custom URL")) { // Get the custom URL string.
2492 searchURL = searchCustomURLString;
2493 } else { // Use the string from the pre-built list.
2494 searchURL = searchString;
2497 // Reset the proxy to default. The host is `""` and the port is `"0"`.
2498 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
2500 // Set the default `appBar` background. `this` refers to the context.
2502 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
2504 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
2507 // Reset `waitingForOrbot.
2508 waitingForOrbot = false;
2511 // Set swipe to refresh.
2512 swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
2514 // Set Do Not Track status.
2515 if (doNotTrackEnabled) {
2516 customHeaders.put("DNT", "1");
2518 customHeaders.remove("DNT");
2521 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
2522 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
2523 if (hideSystemBarsOnFullscreen) { // Hide everything.
2524 // Remove the translucent navigation setting if it is currently flagged.
2525 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2527 // Remove the translucent status bar overlay.
2528 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2530 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
2531 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
2533 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
2534 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
2535 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
2537 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
2538 } else { // Hide everything except the status and navigation bars.
2539 // Add the translucent status flag if it is unset.
2540 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2542 if (translucentNavigationBarOnFullscreen) {
2543 // Set the navigation bar to be translucent.
2544 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2546 // Set the navigation bar to be black.
2547 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2550 } else { // Switch to normal viewing mode.
2551 // Reset `inFullScreenBrowsingMode` to `false`.
2552 inFullScreenBrowsingMode = false;
2554 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
2555 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
2559 // Show the `BannerAd` in the free flavor.
2560 if (BuildConfig.FLAVOR.contentEquals("free")) {
2561 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
2562 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2564 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2565 adView = findViewById(R.id.adview);
2568 // Remove the translucent navigation bar flag if it is set.
2569 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2571 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
2572 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2574 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
2575 rootCoordinatorLayout.setSystemUiVisibility(0);
2577 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
2578 rootCoordinatorLayout.setFitsSystemWindows(true);
2582 // We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2583 @SuppressWarnings("deprecation")
2584 private void applyDomainSettings(String url) {
2585 // Reset `navigatingHistory`.
2586 navigatingHistory = false;
2588 // Parse the URL into a URI.
2589 Uri uri = Uri.parse(url);
2591 // Extract the domain from `uri`.
2592 String hostName = uri.getHost();
2594 // Initialize `loadingNewDomainName`.
2595 boolean loadingNewDomainName;
2597 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
2598 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
2599 //noinspection SimplifiableIfStatement
2600 if ((hostName == null) || (currentDomainName == null)) {
2601 loadingNewDomainName = true;
2602 } else { // Determine if `hostName` equals `currentDomainName`.
2603 loadingNewDomainName = !hostName.equals(currentDomainName);
2606 // 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.
2607 if (loadingNewDomainName) {
2608 // Set the new `hostname` as the `currentDomainName`.
2609 currentDomainName = hostName;
2611 // Reset `ignorePinnedSslCertificate`.
2612 ignorePinnedSslCertificate = false;
2614 // Reset `favoriteIconBitmap` and display it in the `appbar`.
2615 favoriteIconBitmap = favoriteIconDefaultBitmap;
2616 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
2618 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
2619 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2620 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2622 // Get a full cursor from `domainsDatabaseHelper`.
2623 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
2625 // Initialize `domainSettingsSet`.
2626 Set<String> domainSettingsSet = new HashSet<>();
2628 // Get the domain name column index.
2629 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
2631 // Populate `domainSettingsSet`.
2632 for (int i = 0; i < domainNameCursor.getCount(); i++) {
2633 // Move `domainsCursor` to the current row.
2634 domainNameCursor.moveToPosition(i);
2636 // Store the domain name in `domainSettingsSet`.
2637 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
2640 // Close `domainNameCursor.
2641 domainNameCursor.close();
2643 // Initialize variables to track if domain settings will be applied and, if so, under which name.
2644 domainSettingsApplied = false;
2645 String domainNameInDatabase = null;
2647 // Check the hostname.
2648 if (domainSettingsSet.contains(hostName)) {
2649 domainSettingsApplied = true;
2650 domainNameInDatabase = hostName;
2653 // If `hostName` is not `null`, check all the subdomains of `hostName` against wildcard domains in `domainCursor`.
2654 if (hostName != null) {
2655 while (hostName.contains(".") && !domainSettingsApplied) { // Stop checking if we run out of `.` or if we already know that `domainSettingsApplied` is `true`.
2656 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
2657 domainSettingsApplied = true;
2658 domainNameInDatabase = "*." + hostName;
2661 // Strip out the lowest subdomain of `host`.
2662 hostName = hostName.substring(hostName.indexOf(".") + 1);
2666 // Get a handle for the shared preference. `this` references the current context.
2667 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2669 // Store the general preference information.
2670 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
2671 String defaultUserAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
2672 String defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
2673 nightMode = sharedPreferences.getBoolean("night_mode", false);
2675 if (domainSettingsApplied) { // The url we are loading has custom domain settings.
2676 // Get a cursor for the current host and move it to the first position.
2677 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
2678 currentHostDomainSettingsCursor.moveToFirst();
2680 // Get the settings from the cursor.
2681 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
2682 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
2683 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
2684 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
2685 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
2686 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
2687 String userAgentString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
2688 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
2689 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
2690 int nightModeInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
2691 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
2692 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
2693 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
2694 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
2695 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
2696 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
2697 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
2699 // Set `nightMode` according to `nightModeInt`. If `nightModeInt` is `DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT` the current setting from `sharedPreferences` will be used.
2700 switch (nightModeInt) {
2701 case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
2705 case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
2710 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
2712 javaScriptEnabled = true;
2715 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
2716 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
2717 pinnedDomainSslStartDate = null;
2719 pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
2722 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
2723 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
2724 pinnedDomainSslEndDate = null;
2726 pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
2729 // Close `currentHostDomainSettingsCursor`.
2730 currentHostDomainSettingsCursor.close();
2732 // Apply the domain settings.
2733 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2734 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2735 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2736 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2738 // Apply the font size.
2739 if (fontSize == 0) { // Apply the default font size.
2740 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
2741 } else { // Apply the specified font size.
2742 mainWebView.getSettings().setTextZoom(fontSize);
2745 // Set third-party cookies status if API >= 21.
2746 if (Build.VERSION.SDK_INT >= 21) {
2747 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2750 // Only set the user agent if the webpage is not currently loading. Otherwise, changing the user agent on redirects can cause the original website to reload. <https://redmine.stoutner.com/issues/160>
2751 if (!urlIsLoading) {
2752 switch (userAgentString) {
2753 case "System default user agent":
2754 // Set the user agent according to the system default.
2755 switch (defaultUserAgentString) {
2756 case "WebView default user agent":
2757 // Set the user agent to `""`, which uses the default value.
2758 mainWebView.getSettings().setUserAgentString("");
2761 case "Custom user agent":
2762 // Set the custom user agent.
2763 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
2767 // Use the selected user agent.
2768 mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
2772 case "WebView default user agent":
2773 // Set the user agent to `""`, which uses the default value.
2774 mainWebView.getSettings().setUserAgentString("");
2778 // Use the selected user agent.
2779 mainWebView.getSettings().setUserAgentString(userAgentString);
2783 // 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.
2785 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
2787 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
2789 } else { // The URL we are loading does not have custom domain settings. Load the defaults.
2790 // Store the values from `sharedPreferences` in variables.
2791 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
2792 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
2793 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
2794 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
2795 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
2797 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
2799 javaScriptEnabled = true;
2802 // Apply the default settings.
2803 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2804 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2805 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2806 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2807 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
2809 // Reset the pinned SSL certificate information.
2810 domainSettingsDatabaseId = -1;
2811 pinnedDomainSslCertificate = false;
2812 pinnedDomainSslIssuedToCNameString = "";
2813 pinnedDomainSslIssuedToONameString = "";
2814 pinnedDomainSslIssuedToUNameString = "";
2815 pinnedDomainSslIssuedByCNameString = "";
2816 pinnedDomainSslIssuedByONameString = "";
2817 pinnedDomainSslIssuedByUNameString = "";
2818 pinnedDomainSslStartDate = null;
2819 pinnedDomainSslEndDate = null;
2821 // Set third-party cookies status if API >= 21.
2822 if (Build.VERSION.SDK_INT >= 21) {
2823 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2826 // Only set the user agent if the webpage is not currently loading. Otherwise, changing the user agent on redirects can cause the original website to reload. <https://redmine.stoutner.com/issues/160>
2827 if (!urlIsLoading) {
2828 switch (defaultUserAgentString) {
2829 case "WebView default user agent":
2830 // Set the user agent to `""`, which uses the default value.
2831 mainWebView.getSettings().setUserAgentString("");
2834 case "Custom user agent":
2835 // Set the custom user agent.
2836 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
2840 // Use the selected user agent.
2841 mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
2845 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2846 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
2849 // Close `domainsDatabaseHelper`.
2850 domainsDatabaseHelper.close();
2852 // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode. `true` indicates that custom domain settings are applied.
2853 onTheFlyDisplayImagesSet = false;
2854 setDisplayWebpageImages();
2856 // Update the privacy icons, but only if `mainMenu` has already been populated.
2857 if (mainMenu != null) {
2858 updatePrivacyIcons(true);
2863 private void setDisplayWebpageImages() {
2864 if (!onTheFlyDisplayImagesSet) {
2865 if (domainSettingsApplied) { // Custom domain settings are applied.
2866 switch (displayWebpageImagesInt) {
2867 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
2868 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
2871 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
2872 mainWebView.getSettings().setLoadsImagesAutomatically(true);
2875 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
2876 mainWebView.getSettings().setLoadsImagesAutomatically(false);
2879 } else { // Default settings are applied.
2880 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
2885 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
2886 // Get handles for the icons.
2887 MenuItem privacyIconMenuItem = mainMenu.findItem(R.id.toggle_javascript);
2888 MenuItem firstPartyCookiesIconMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
2889 MenuItem domStorageIconMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
2890 MenuItem formDataIconMenuItem = mainMenu.findItem(R.id.toggle_save_form_data);
2892 // Update `privacyIcon`.
2893 if (javaScriptEnabled) { // JavaScript is enabled.
2894 privacyIconMenuItem.setIcon(R.drawable.javascript_enabled);
2895 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
2896 privacyIconMenuItem.setIcon(R.drawable.warning);
2897 } else { // All the dangerous features are disabled.
2898 privacyIconMenuItem.setIcon(R.drawable.privacy_mode);
2901 // Update `firstPartyCookiesIcon`.
2902 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
2903 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_enabled);
2904 } else { // First-party cookies are disabled.
2906 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_dark);
2908 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_light);
2912 // Update `domStorageIcon`.
2913 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
2914 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_enabled);
2915 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
2917 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
2919 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
2921 } else { // JavaScript is disabled, so DOM storage is ghosted.
2923 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
2925 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
2929 // Update `formDataIcon`.
2930 if (saveFormDataEnabled) { // Form data is enabled.
2931 formDataIconMenuItem.setIcon(R.drawable.form_data_enabled);
2932 } else { // Form data is disabled.
2934 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_dark);
2936 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_light);
2940 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`. `this` references the current activity.
2941 if (runInvalidateOptionsMenu) {
2942 ActivityCompat.invalidateOptionsMenu(this);
2946 private void highlightUrlText() {
2947 String urlString = urlTextBox.getText().toString();
2949 if (urlString.startsWith("http://")) { // Highlight connections that are not encrypted.
2950 urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
2951 } else if (urlString.startsWith("https://")) { // Highlight connections that are encrypted.
2952 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
2955 // Get the index of the `/` immediately after the domain name.
2956 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
2958 // De-emphasize the text after the domain name.
2959 if (endOfDomainName > 0) {
2960 urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);