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.ValueCallback;
81 import android.webkit.WebBackForwardList;
82 import android.webkit.WebChromeClient;
83 import android.webkit.WebResourceResponse;
84 import android.webkit.WebStorage;
85 import android.webkit.WebView;
86 import android.webkit.WebViewClient;
87 import android.webkit.WebViewDatabase;
88 import android.widget.EditText;
89 import android.widget.FrameLayout;
90 import android.widget.ImageView;
91 import android.widget.LinearLayout;
92 import android.widget.ProgressBar;
93 import android.widget.RelativeLayout;
94 import android.widget.TextView;
96 import com.stoutner.privacybrowser.BannerAd;
97 import com.stoutner.privacybrowser.BuildConfig;
98 import com.stoutner.privacybrowser.R;
99 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
100 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
101 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
102 import com.stoutner.privacybrowser.dialogs.PinnedSslCertificateMismatchDialog;
103 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
104 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
105 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
106 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
107 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
108 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
110 import java.io.BufferedReader;
111 import java.io.ByteArrayInputStream;
113 import java.io.IOException;
114 import java.io.InputStreamReader;
115 import java.io.UnsupportedEncodingException;
116 import java.net.MalformedURLException;
118 import java.net.URLDecoder;
119 import java.net.URLEncoder;
120 import java.util.Date;
121 import java.util.HashMap;
122 import java.util.HashSet;
123 import java.util.Map;
124 import java.util.Set;
126 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
127 public class MainWebViewActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, CreateHomeScreenShortcutDialog.CreateHomeScreenSchortcutListener,
128 HttpAuthenticationDialog.HttpAuthenticationListener, PinnedSslCertificateMismatchDialog.PinnedSslCertificateMismatchListener, SslCertificateErrorDialog.SslCertificateErrorListener, DownloadFileDialog.DownloadFileListener,
129 DownloadImageDialog.DownloadImageListener, UrlHistoryDialog.UrlHistoryListener {
131 // `darkTheme` is public static so it can be accessed from `AboutActivity`, `GuideActivity`, `AddDomainDialog`, `SettingsActivity`, `DomainsActivity`, `DomainsListFragment`, `BookmarksActivity`, `BookmarksDatabaseViewActivity`,
132 // `CreateBookmarkDialog`, `CreateBookmarkFolderDialog`, `DownloadFileDialog`, `DownloadImageDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`, `HttpAuthenticationDialog`, `MoveToFolderDialog`, `SslCertificateErrorDialog`, `UrlHistoryDialog`,
133 // `ViewSslCertificateDialog`, `CreateHomeScreenShortcutDialog`, and `OrbotProxyHelper`. It is also used in `onCreate()`, `applyAppSettings()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
134 public static boolean darkTheme;
136 // `favoriteIconBitmap` is public static so it can be accessed from `CreateHomeScreenShortcutDialog`, `BookmarksActivity`, `CreateBookmarkDialog`, `CreateBookmarkFolderDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`,
137 // and `ViewSslCertificateDialog`. It is also used in `onCreate()`, `onCreateHomeScreenShortcutCreate()`, and `applyDomainSettings`.
138 public static Bitmap favoriteIconBitmap;
140 // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`, `CreateBookmarkDialog`, and `AddDomainDialog`.
141 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
142 public static String formattedUrlString;
144 // `sslCertificate` is public static so it can be accessed from `DomainsActivity`, `DomainsListFragment`, `DomainSettingsFragment`, `PinnedSslCertificateMismatchDialog`, and `ViewSslCertificateDialog`. It is also used in `onCreate()`.
145 public static SslCertificate sslCertificate;
147 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`.
148 public static String orbotStatus;
150 // `webViewTitle` is public static so it can be accessed from `CreateBookmarkDialog` and `CreateHomeScreenShortcutDialog`. It is also used in `onCreate()`.
151 public static String webViewTitle;
153 // `displayWebpageImagesBoolean` is public static so it can be accessed from `DomainSettingsFragment`. It is also used in `applyAppSettings()` and `applyDomainSettings()`.
154 public static boolean displayWebpageImagesBoolean;
156 // `reloadOnRestart` is public static so it can be accessed from `SettingsFragment`. It is also used in `onRestart()`
157 public static boolean reloadOnRestart;
159 // `reloadUrlOnRestart` is public static so it can be accessed from `SettingsFragment`. It is also used in `onRestart()`.
160 public static boolean loadUrlOnRestart;
162 // The pinned domain SSL Certificate variables are public static so they can be accessed from `PinnedSslCertificateMismatchDialog`. They are also used in `onCreate()` and `applyDomainSettings()`.
163 public static int domainSettingsDatabaseId;
164 public static String pinnedDomainSslIssuedToCNameString;
165 public static String pinnedDomainSslIssuedToONameString;
166 public static String pinnedDomainSslIssuedToUNameString;
167 public static String pinnedDomainSslIssuedByCNameString;
168 public static String pinnedDomainSslIssuedByONameString;
169 public static String pinnedDomainSslIssuedByUNameString;
170 public static Date pinnedDomainSslStartDate;
171 public static Date pinnedDomainSslEndDate;
174 // `appBar` is used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applyAppSettings()`.
175 private ActionBar appBar;
177 // `navigatingHistory` is used in `onCreate()`, `onNavigationItemSelected()`, `onSslMismatchBack()`, and `applyDomainSettings()`.
178 private boolean navigatingHistory;
180 // `favoriteIconDefaultBitmap` is used in `onCreate()` and `applyDomainSettings`.
181 private Bitmap favoriteIconDefaultBitmap;
183 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, and `onBackPressed()`.
184 private DrawerLayout drawerLayout;
186 // `rootCoordinatorLayout` is used in `onCreate()` and `applyAppSettings()`.
187 private CoordinatorLayout rootCoordinatorLayout;
189 // `mainWebView` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`, `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`
190 // `onSslMismatchBack()`, and `setDisplayWebpageImages()`.
191 private WebView mainWebView;
193 // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
194 private FrameLayout fullScreenVideoFrameLayout;
196 // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu`, and `onRestart()`.
197 private SwipeRefreshLayout swipeRefreshLayout;
199 // `urlAppBarRelativeLayout` is used in `onCreate()` and `applyDomainSettings()`.
200 private RelativeLayout urlAppBarRelativeLayout;
202 // `favoriteIconImageView` is used in `onCreate()` and `applyDomainSettings()`
203 private ImageView favoriteIconImageView;
205 // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `loadUrlFromTextBox()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
206 private CookieManager cookieManager;
208 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
209 private final Map<String, String> customHeaders = new HashMap<>();
211 // `javaScriptEnabled` is also used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
212 private boolean javaScriptEnabled;
214 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applyDomainSettings()`.
215 private boolean firstPartyCookiesEnabled;
217 // `thirdPartyCookiesEnabled` used in `onCreate()`, `onPrepareOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
218 private boolean thirdPartyCookiesEnabled;
220 // `domStorageEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
221 private boolean domStorageEnabled;
223 // `saveFormDataEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
224 private boolean saveFormDataEnabled;
226 // `nightMode` is used in `onCreate()` and `applyDomainSettings()`.
227 private boolean nightMode;
229 // `swipeToRefreshEnabled` is used in `onPrepareOptionsMenu()` and `applyAppSettings()`.
230 private boolean swipeToRefreshEnabled;
232 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applyAppSettings()`.
233 private String homepage;
235 // `searchURL` is used in `loadURLFromTextBox()` and `applyAppSettings()`.
236 private String searchURL;
238 // `adBlockerEnabled` is used in `onCreate()` and `applyAppSettings()`.
239 private boolean adBlockerEnabled;
241 // `privacyBrowserRuntime` is used in `onCreate()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
242 private Runtime privacyBrowserRuntime;
244 // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
245 private boolean incognitoModeEnabled;
247 // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
248 private boolean fullScreenBrowsingModeEnabled;
250 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
251 private boolean inFullScreenBrowsingMode;
253 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
254 private boolean hideSystemBarsOnFullscreen;
256 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
257 private boolean translucentNavigationBarOnFullscreen;
259 // `currentDomainName` is used in `onCreate()`, `onNavigationItemSelected()`, `onSslMismatchProceed()`, and `applyDomainSettings()`.
260 private String currentDomainName;
262 // `ignorePinnedSslCertificateForDomain` is used in `onCreate()`, `onSslMismatchProceed()`, and `applyDomainSettings()`.
263 private boolean ignorePinnedSslCertificate;
265 // `waitingForOrbot` is used in `onCreate()` and `applyAppSettings()`.
266 private boolean waitingForOrbot;
268 // `domainSettingsApplied` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
269 private boolean domainSettingsApplied;
271 // `displayWebpageImagesInt` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
272 private int displayWebpageImagesInt;
274 // `onTheFlyDisplayImagesSet` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
275 private boolean onTheFlyDisplayImagesSet;
277 // `waitingForOrbotData` is used in `onCreate()` and `applyAppSettings()`.
278 private String waitingForOrbotHTMLString;
280 // `privateDataDirectoryString` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
281 private String privateDataDirectoryString;
283 // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
284 private LinearLayout findOnPageLinearLayout;
286 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
287 private EditText findOnPageEditText;
289 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
290 private Menu mainMenu;
292 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
293 private ActionBarDrawerToggle drawerToggle;
295 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
296 private Toolbar supportAppBar;
298 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, `loadUrl()`, and `highlightUrlText()`.
299 private EditText urlTextBox;
301 // `redColorSpan` is used in `onCreate()` and `highlightUrlText()`.
302 private ForegroundColorSpan redColorSpan;
304 // `initialGrayColorSpan` is sued in `onCreate()` and `highlightUrlText()`.
305 private ForegroundColorSpan initialGrayColorSpan;
307 // `finalGrayColorSpam` is used in `onCreate()` and `highlightUrlText()`.
308 private ForegroundColorSpan finalGrayColorSpan;
310 // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
313 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
314 private SslErrorHandler sslErrorHandler;
316 // `httpAuthHandler` is used in `onCreate()`, `onHttpAuthenticationCancel()`, and `onHttpAuthenticationProceed()`.
317 private static HttpAuthHandler httpAuthHandler;
319 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
320 private InputMethodManager inputMethodManager;
322 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
323 private RelativeLayout mainWebViewRelativeLayout;
325 // `urlIsLoading` is used in `onCreate()`, `loadUrl()`, and `applyDomainSettings()`.
326 private boolean urlIsLoading;
328 // `pinnedDomainSslCertificate` is used in `onCreate()` and `applyDomainSettings()`.
329 private boolean pinnedDomainSslCertificate;
333 // 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.
334 @SuppressLint("SetJavaScriptEnabled")
335 // Remove Android Studio's warning about deprecations. We have to use the deprecated `getColor()` until API >= 23.
336 @SuppressWarnings("deprecation")
337 protected void onCreate(Bundle savedInstanceState) {
338 // Get a handle for `sharedPreferences`. `this` references the current context.
339 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
341 // Get the theme preference.
342 darkTheme = sharedPreferences.getBoolean("dark_theme", false);
344 // Set the activity theme.
346 setTheme(R.style.PrivacyBrowserDark);
348 setTheme(R.style.PrivacyBrowserLight);
351 // Run the default commands.
352 super.onCreate(savedInstanceState);
354 // Set the content view.
355 setContentView(R.layout.main_drawerlayout);
357 // Get a handle for `inputMethodManager`.
358 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
360 // We need to use the `SupportActionBar` from `android.support.v7.app.ActionBar` until the minimum API is >= 21.
361 supportAppBar = (Toolbar) findViewById(R.id.app_bar);
362 setSupportActionBar(supportAppBar);
363 appBar = getSupportActionBar();
365 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
366 assert appBar != null;
368 // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
369 appBar.setCustomView(R.layout.url_app_bar);
370 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
372 // Initialize the `ForegroundColorSpans` and `StyleSpan` for highlighting `urlTextBox`. We have to use the deprecated `getColor()` until API >= 23.
373 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
374 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
375 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
377 // Get a handle for `urlTextBox`.
378 urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.url_edittext);
380 // Remove the formatting from `urlTextBar` when the user is editing the text.
381 urlTextBox.setOnFocusChangeListener(new View.OnFocusChangeListener() {
383 public void onFocusChange(View v, boolean hasFocus) {
384 if (hasFocus) { // The user is editing `urlTextBox`.
385 // Remove the highlighting.
386 urlTextBox.getText().removeSpan(redColorSpan);
387 urlTextBox.getText().removeSpan(initialGrayColorSpan);
388 urlTextBox.getText().removeSpan(finalGrayColorSpan);
389 } else { // The user has stopped editing `urlTextBox`.
390 // Reapply the highlighting.
396 // Set the `Go` button on the keyboard to load the URL in `urlTextBox`.
397 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
399 public boolean onKey(View v, int keyCode, KeyEvent event) {
400 // If the event is a key-down event on the `enter` button, load the URL.
401 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
402 // Load the URL into the mainWebView and consume the event.
404 loadUrlFromTextBox();
405 } catch (UnsupportedEncodingException e) {
408 // If the enter key was pressed, consume the event.
411 // If any other key was pressed, do not consume the event.
417 // Set `waitingForOrbotHTMLString`.
418 waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
420 // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
421 currentDomainName = "";
422 orbotStatus = "unknown";
423 waitingForOrbot = false;
425 // Create an Orbot status `BroadcastReceiver`.
426 BroadcastReceiver orbotStatusBroadcastReceiver = new BroadcastReceiver() {
428 public void onReceive(Context context, Intent intent) {
429 // Store the content of the status message in `orbotStatus`.
430 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
432 // If we are waiting on Orbot, load the website now that Orbot is connected.
433 if (orbotStatus.equals("ON") && waitingForOrbot) {
434 // Reset `waitingForOrbot`.
435 waitingForOrbot = false;
437 // Load `formattedUrlString
438 loadUrl(formattedUrlString);
443 // Register `orbotStatusBroadcastReceiver` on `this` context.
444 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
446 // Get handles for views that need to be accessed.
447 drawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout);
448 rootCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.root_coordinatorlayout);
449 mainWebViewRelativeLayout = (RelativeLayout) findViewById(R.id.main_webview_relativelayout);
450 mainWebView = (WebView) findViewById(R.id.main_webview);
451 findOnPageLinearLayout = (LinearLayout) findViewById(R.id.find_on_page_linearlayout);
452 findOnPageEditText = (EditText) findViewById(R.id.find_on_page_edittext);
453 fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.full_screen_video_framelayout);
454 urlAppBarRelativeLayout = (RelativeLayout) findViewById(R.id.url_app_bar_relativelayout);
455 favoriteIconImageView = (ImageView) findViewById(R.id.favorite_icon);
457 // Create a double-tap listener to toggle full-screen mode.
458 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
459 // Override `onDoubleTap()`. All other events are handled using the default settings.
461 public boolean onDoubleTap(MotionEvent event) {
462 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
463 // Toggle `inFullScreenBrowsingMode`.
464 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
466 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
467 // Hide the `appBar`.
470 // Hide the `BannerAd` in the free flavor.
471 if (BuildConfig.FLAVOR.contentEquals("free")) {
472 BannerAd.hideAd(adView);
475 // Modify the system bars.
476 if (hideSystemBarsOnFullscreen) { // Hide everything.
477 // Remove the translucent overlays.
478 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
480 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
481 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
483 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
484 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
485 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
487 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
489 // Set `rootCoordinatorLayout` to fill the whole screen.
490 rootCoordinatorLayout.setFitsSystemWindows(false);
491 } else { // Hide everything except the status and navigation bars.
492 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
493 rootCoordinatorLayout.setFitsSystemWindows(false);
495 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.
496 // Set the navigation bar to be translucent.
497 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
500 } else { // Switch to normal viewing mode.
501 // Show the `appBar`.
504 // Show the `BannerAd` in the free flavor.
505 if (BuildConfig.FLAVOR.contentEquals("free")) {
506 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
507 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
509 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
510 adView = findViewById(R.id.adview);
513 // Remove the translucent navigation bar flag if it is set.
514 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
516 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
517 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
519 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
520 rootCoordinatorLayout.setSystemUiVisibility(0);
522 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
523 rootCoordinatorLayout.setFitsSystemWindows(true);
526 // Consume the double-tap.
528 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
534 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
535 mainWebView.setOnTouchListener(new View.OnTouchListener() {
537 public boolean onTouch(View v, MotionEvent event) {
538 // Send the `event` to `gestureDetector`.
539 return gestureDetector.onTouchEvent(event);
543 // Update `findOnPageCountTextView`.
544 mainWebView.setFindListener(new WebView.FindListener() {
545 // Get a handle for `findOnPageCountTextView`.
546 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
549 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
550 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
551 // Set `findOnPageCountTextView` to `0/0`.
552 findOnPageCountTextView.setText(R.string.zero_of_zero);
553 } else if (isDoneCounting) { // There are matches.
554 // `activeMatchOrdinal` is zero-based.
555 int activeMatch = activeMatchOrdinal + 1;
557 // Set `findOnPageCountTextView`.
558 findOnPageCountTextView.setText(activeMatch + "/" + numberOfMatches);
563 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
564 findOnPageEditText.addTextChangedListener(new TextWatcher() {
566 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
571 public void onTextChanged(CharSequence s, int start, int before, int count) {
576 public void afterTextChanged(Editable s) {
577 // Search for the text in `mainWebView`.
578 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
582 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
583 findOnPageEditText.setOnKeyListener(new View.OnKeyListener() {
585 public boolean onKey(View v, int keyCode, KeyEvent event) {
586 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
587 // Hide the soft keyboard. `0` indicates no additional flags.
588 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
590 // Consume the event.
592 } else { // A different key was pressed.
593 // Do not consume the event.
599 // Implement swipe to refresh
600 swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refreshlayout);
601 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
602 swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
604 public void onRefresh() {
605 mainWebView.reload();
609 // `DrawerTitle` identifies the `DrawerLayout` in accessibility mode.
610 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
612 // Listen for touches on the navigation menu.
613 final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationview);
614 navigationView.setNavigationItemSelectedListener(this);
616 // 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.
617 final Menu navigationMenu = navigationView.getMenu();
618 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
619 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
620 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
622 // The `DrawerListener` allows us to update the Navigation Menu.
623 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
625 public void onDrawerSlide(View drawerView, float slideOffset) {
629 public void onDrawerOpened(View drawerView) {
633 public void onDrawerClosed(View drawerView) {
637 public void onDrawerStateChanged(int newState) {
638 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // The drawer is opening or closing.
639 // Update the `Back`, `Forward`, and `History` menu items.
640 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
641 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
642 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
644 // Hide the keyboard (if displayed) so we can see the navigation menu. `0` indicates no additional flags.
645 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
647 // Clear the focus from `urlTextBox` if it has it.
648 urlTextBox.clearFocus();
653 // drawerToggle creates the hamburger icon at the start of the AppBar.
654 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
656 // Initialize `adServerSet`.
657 final Set<String> adServersSet = new HashSet<>();
659 // Load the list of ad servers into memory.
661 // Load `pgl.yoyo.org_adservers.txt` into a `BufferedReader`.
662 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(getAssets().open("pgl.yoyo.org_adservers.txt")));
664 // Create a string for storing each ad server.
667 // Populate `adServersSet`.
668 while ((adServer = bufferedReader.readLine()) != null) {
669 adServersSet.add(adServer);
672 // Close `bufferedReader`.
673 bufferedReader.close();
674 } catch (IOException ioException) {
675 // We're pretty sure the asset exists, so we don't need to worry about the `IOException` ever being thrown.
678 mainWebView.setWebViewClient(new WebViewClient() {
679 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
680 // We have to use the deprecated `shouldOverrideUrlLoading` until API >= 24.
681 @SuppressWarnings("deprecation")
683 public boolean shouldOverrideUrlLoading(WebView view, String url) {
684 if (url.startsWith("mailto:")) { // Load the URL in an external email program because it begins with `mailto:`.
685 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
686 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
688 // Parse the url and set it as the data for the `Intent`.
689 emailIntent.setData(Uri.parse(url));
691 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
692 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
695 startActivity(emailIntent);
697 // Returning `true` indicates the application is handling the URL.
699 } else { // Load the URL in Privacy Browser.
700 // Apply the domain settings for the new URL.
701 applyDomainSettings(url);
703 // Returning `false` causes the current `WebView` to handle the URL and prevents it from adding redirects to the history list.
708 // Block ads. We have to use the deprecated `shouldInterceptRequest` until minimum API >= 21.
709 @SuppressWarnings("deprecation")
711 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
712 if (adBlockerEnabled) { // Block ads.
713 // Extract the host from `url`.
714 Uri requestUri = Uri.parse(url);
715 String requestHost = requestUri.getHost();
717 // Initialize a variable to track if this is an ad server.
718 boolean requestHostIsAdServer = false;
720 // Check all the subdomains of `requestHost` if it is not `null` against the ad server database.
721 if (requestHost != null) {
722 while (requestHost.contains(".") && !requestHostIsAdServer) { // Stop checking if we run out of `.` or if we already know that `requestHostIsAdServer` is `true`.
723 if (adServersSet.contains(requestHost)) {
724 requestHostIsAdServer = true;
727 // Strip out the lowest subdomain of `requestHost`.
728 requestHost = requestHost.substring(requestHost.indexOf(".") + 1);
732 if (requestHostIsAdServer) { // It is an ad server.
733 // Return an empty `WebResourceResponse`.
734 return new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
735 } else { // It is not an ad server.
736 // `return null` loads the requested resource.
739 } else { // Ad blocking is disabled.
740 // `return null` loads the requested resource.
745 // Handle HTTP authentication requests.
747 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
748 // Store `handler` so it can be accessed from `onHttpAuthenticationCancel()` and `onHttpAuthenticationProceed()`.
749 httpAuthHandler = handler;
751 // Display the HTTP authentication dialog.
752 AppCompatDialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm);
753 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
756 // Update the URL in urlTextBox when the page starts to load.
758 public void onPageStarted(WebView view, String url, Bitmap favicon) {
759 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
761 mainWebView.setVisibility(View.INVISIBLE);
764 // Check to see if we are waiting on Orbot.
765 if (!waitingForOrbot) { // We are not waiting on Orbot, so we need to process the URL.
766 // 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.
767 formattedUrlString = url;
769 // Display the formatted URL text.
770 urlTextBox.setText(formattedUrlString);
772 // Apply text highlighting to `urlTextBox`.
775 // Apply any custom domain settings if the URL was loaded by navigating history.
776 if (navigatingHistory) {
777 applyDomainSettings(url);
780 // 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.
785 // It is necessary to update `formattedUrlString` and `urlTextBox` after the page finishes loading because the final URL can change during load.
787 public void onPageFinished(WebView view, String url) {
788 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
789 urlIsLoading = false;
791 // Clear the cache and history if Incognito Mode is enabled.
792 if (incognitoModeEnabled) {
793 // Clear the cache. `true` includes disk files.
794 mainWebView.clearCache(true);
796 // Clear the back/forward history.
797 mainWebView.clearHistory();
799 // Manually delete cache folders.
801 // Delete the main `cache` folder.
802 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
804 // 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`.
805 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
806 } catch (IOException e) {
807 // Do nothing if an error is thrown.
811 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
812 if (!waitingForOrbot) {
813 // Check to see if `WebView` has set `url` to be `about:blank`.
814 if (url.equals("about:blank")) { // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
815 // Set `formattedUrlString` to `""`.
816 formattedUrlString = "";
818 urlTextBox.setText(formattedUrlString);
820 // Request focus for `urlTextBox`.
821 urlTextBox.requestFocus();
823 // Display the keyboard.
824 inputMethodManager.showSoftInput(urlTextBox, 0);
826 // Apply the domain settings. This clears any settings from the previous domain.
827 applyDomainSettings(formattedUrlString);
828 } else { // `WebView` has loaded a webpage.
829 // Set `formattedUrlString`.
830 formattedUrlString = url;
832 // Only update `urlTextBox` if the user is not typing in it.
833 if (!urlTextBox.hasFocus()) {
834 // Display the formatted URL text.
835 urlTextBox.setText(formattedUrlString);
837 // Apply text highlighting to `urlTextBox`.
842 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
843 sslCertificate = mainWebView.getCertificate();
845 // 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.
846 if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate) {
847 // Initialize the current SSL certificate variables.
848 String currentWebsiteIssuedToCName = "";
849 String currentWebsiteIssuedToOName = "";
850 String currentWebsiteIssuedToUName = "";
851 String currentWebsiteIssuedByCName = "";
852 String currentWebsiteIssuedByOName = "";
853 String currentWebsiteIssuedByUName = "";
854 Date currentWebsiteSslStartDate = null;
855 Date currentWebsiteSslEndDate = null;
858 // Extract the individual pieces of information from the current website SSL certificate if it is not null.
859 if (sslCertificate != null) {
860 currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
861 currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
862 currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
863 currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
864 currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
865 currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
866 currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
867 currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
870 // 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`.
871 String currentWebsiteSslStartDateString = "";
872 String currentWebsiteSslEndDateString = "";
873 String pinnedDomainSslStartDateString = "";
874 String pinnedDomainSslEndDateString = "";
876 // Convert the `Dates` to `Strings` if they are not `null`.
877 if (currentWebsiteSslStartDate != null) {
878 currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
881 if (currentWebsiteSslEndDate != null) {
882 currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
885 if (pinnedDomainSslStartDate != null) {
886 pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
889 if (pinnedDomainSslEndDate != null) {
890 pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
893 // Check to see if the pinned SSL certificate matches the current website certificate.
894 if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) || !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) ||
895 !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) || !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
896 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) { // The pinned SSL certificate doesn't match the current domain certificate.
897 //Display the pinned SSL certificate mismatch `AlertDialog`.
898 AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
899 pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
905 // Handle SSL Certificate errors.
907 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
908 // Get the current website SSL certificate.
909 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
911 // Extract the individual pieces of information from the current website SSL certificate.
912 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
913 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
914 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
915 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
916 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
917 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
918 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
919 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
921 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
922 if (pinnedDomainSslCertificate &&
923 currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) && currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) &&
924 currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) && currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
925 currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) { // An SSL certificate is pinned and matches the current domain certificate.
926 // Proceed to the website without displaying an error.
928 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
929 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
930 sslErrorHandler = handler;
932 // Display the SSL error `AlertDialog`.
933 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
934 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
939 // Get a handle for the progress bar.
940 final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress_bar);
942 mainWebView.setWebChromeClient(new WebChromeClient() {
943 // Update the progress bar when a page is loading.
945 public void onProgressChanged(WebView view, int progress) {
946 progressBar.setProgress(progress);
947 if (progress < 100) {
948 // Show the progress bar.
949 progressBar.setVisibility(View.VISIBLE);
951 // Hide the progress bar.
952 progressBar.setVisibility(View.GONE);
954 // Inject the night mode CSS if night mode is enabled.
955 if (nightMode) { // Night mode is enabled.
956 // `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.
957 // `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.
958 // `a {color: #1565C0}` sets links to be a dark blue. `!important` takes precedent over any existing sub-settings.
959 mainWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; style.innerHTML = '" +
960 "* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important; text-shadow: none !important; border: none !important;}" +
961 "a {color: #1565C0 !important;}" +
962 "'; parent.appendChild(style)})()", new ValueCallback<String>() {
964 public void onReceiveValue(String value) {
965 // Initialize a `Handler` to display `mainWebView`.
966 Handler displayWebViewHandler = new Handler();
968 // Setup a `Runnable` to display `mainWebView` after a delay to allow the CSS to be applied.
969 Runnable displayWebViewRunnable = new Runnable() {
971 mainWebView.setVisibility(View.VISIBLE);
975 // Use `displayWebViewHandler` to delay the displaying of `mainWebView` for 500 milliseconds.
976 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
979 } else { // Night mode is disabled.
980 // Display `mainWebView` in case it was hidden before loading domain settings.
981 mainWebView.setVisibility(View.VISIBLE);
984 //Stop the `SwipeToRefresh` indicator if it is running
985 swipeRefreshLayout.setRefreshing(false);
989 // Set the favorite icon when it changes.
991 public void onReceivedIcon(WebView view, Bitmap icon) {
992 // Only update the favorite icon if the website has finished loading.
993 if (progressBar.getVisibility() == View.GONE) {
994 // Save a copy of the favorite icon.
995 favoriteIconBitmap = icon;
997 // Place the favorite icon in the appBar.
998 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
1002 // Save a copy of the title when it changes.
1004 public void onReceivedTitle(WebView view, String title) {
1005 // Save a copy of the title.
1006 webViewTitle = title;
1009 // Enter full screen video
1011 public void onShowCustomView(View view, CustomViewCallback callback) {
1012 // Pause the ad if this is the free flavor.
1013 if (BuildConfig.FLAVOR.contentEquals("free")) {
1014 BannerAd.pauseAd(adView);
1017 // Remove the translucent overlays.
1018 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1020 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1021 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1023 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1024 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1025 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
1027 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1029 // Set `rootCoordinatorLayout` to fill the entire screen.
1030 rootCoordinatorLayout.setFitsSystemWindows(false);
1032 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
1033 fullScreenVideoFrameLayout.addView(view);
1034 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
1037 // Exit full screen video
1038 public void onHideCustomView() {
1039 // Hide `fullScreenVideoFrameLayout`.
1040 fullScreenVideoFrameLayout.removeAllViews();
1041 fullScreenVideoFrameLayout.setVisibility(View.GONE);
1043 // Add the translucent status flag. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1044 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1046 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars. This also clears the `SYSTEM_UI` flags.
1047 rootCoordinatorLayout.setFitsSystemWindows(true);
1049 // Show the ad if this is the free flavor.
1050 if (BuildConfig.FLAVOR.contentEquals("free")) {
1051 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
1052 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1054 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1055 adView = findViewById(R.id.adview);
1060 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
1061 registerForContextMenu(mainWebView);
1063 // Allow the downloading of files.
1064 mainWebView.setDownloadListener(new DownloadListener() {
1066 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
1067 // Show the `DownloadFileDialog` `AlertDialog` and name this instance `@string/download`.
1068 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
1069 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
1073 // Allow pinch to zoom.
1074 mainWebView.getSettings().setBuiltInZoomControls(true);
1076 // Hide zoom controls.
1077 mainWebView.getSettings().setDisplayZoomControls(false);
1079 // Set `mainWebView` to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
1080 mainWebView.getSettings().setUseWideViewPort(true);
1082 // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
1083 mainWebView.getSettings().setLoadWithOverviewMode(true);
1085 // Explicitly disable geolocation.
1086 mainWebView.getSettings().setGeolocationEnabled(false);
1088 // Initialize cookieManager.
1089 cookieManager = CookieManager.getInstance();
1091 // 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).
1092 customHeaders.put("X-Requested-With", "");
1094 // 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.
1095 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
1097 // Get the intent that started the app.
1098 final Intent launchingIntent = getIntent();
1100 // Extract the launching intent data as `launchingIntentUriData`.
1101 final Uri launchingIntentUriData = launchingIntent.getData();
1103 // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
1104 if (launchingIntentUriData != null) {
1105 formattedUrlString = launchingIntentUriData.toString();
1108 // Get a handle for the `Runtime`.
1109 privacyBrowserRuntime = Runtime.getRuntime();
1111 // Store the application's private data directory.
1112 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`.
1114 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
1115 inFullScreenBrowsingMode = false;
1117 // Initialize AdView for the free flavor.
1118 adView = findViewById(R.id.adview);
1120 // Initialize the privacy settings variables.
1121 javaScriptEnabled = false;
1122 firstPartyCookiesEnabled = false;
1123 thirdPartyCookiesEnabled = false;
1124 domStorageEnabled = false;
1125 saveFormDataEnabled = false;
1128 // Initialize `webViewTitle`.
1129 webViewTitle = getString(R.string.no_title);
1131 // Initialize `favoriteIconBitmap`. We have to use `ContextCompat` until API >= 21.
1132 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
1133 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
1134 favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
1136 // If the favorite icon is null, load the default.
1137 if (favoriteIconBitmap == null) {
1138 favoriteIconBitmap = favoriteIconDefaultBitmap;
1141 // Apply the app settings from the shared preferences.
1144 // Load `formattedUrlString` if we are not waiting for Orbot to connect.
1145 if (!waitingForOrbot) {
1146 loadUrl(formattedUrlString);
1151 protected void onNewIntent(Intent intent) {
1152 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1155 if (intent.getData() != null) {
1156 // Get the intent data and convert it to a string.
1157 final Uri intentUriData = intent.getData();
1158 formattedUrlString = intentUriData.toString();
1161 // Close the navigation drawer if it is open.
1162 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1163 drawerLayout.closeDrawer(GravityCompat.START);
1166 // Load the website.
1167 loadUrl(formattedUrlString);
1169 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1170 mainWebView.requestFocus();
1174 public void onRestart() {
1177 // Apply the app settings, which may have been changed in `SettingsActivity`.
1180 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1181 updatePrivacyIcons(true);
1183 // Set the display webpage images mode.
1184 setDisplayWebpageImages();
1186 // Reload the webpage if displaying of images has been disabled in `SettingsFragment`.
1187 if (reloadOnRestart) {
1188 // Reload `mainWebView`.
1189 mainWebView.reload();
1191 // Reset `reloadOnRestartBoolean`.
1192 reloadOnRestart = false;
1195 // Load the URL on restart to apply changes to night mode.
1196 if (loadUrlOnRestart) {
1197 // Load the current `formattedUrlString`.
1198 loadUrl(formattedUrlString);
1200 // Reset `loadUrlOnRestart.
1201 loadUrlOnRestart = false;
1205 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1207 public void onResume() {
1210 // Resume JavaScript (if enabled).
1211 mainWebView.resumeTimers();
1213 // Resume `mainWebView`.
1214 mainWebView.onResume();
1216 // Resume the adView for the free flavor.
1217 if (BuildConfig.FLAVOR.contentEquals("free")) {
1218 BannerAd.resumeAd(adView);
1223 public void onPause() {
1224 // Pause `mainWebView`.
1225 mainWebView.onPause();
1227 // Stop all JavaScript.
1228 mainWebView.pauseTimers();
1230 // Pause the adView or it will continue to consume resources in the background on the free flavor.
1231 if (BuildConfig.FLAVOR.contentEquals("free")) {
1232 BannerAd.pauseAd(adView);
1239 public boolean onCreateOptionsMenu(Menu menu) {
1240 // Inflate the menu; this adds items to the action bar if it is present.
1241 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1243 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1246 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1247 updatePrivacyIcons(false);
1249 // Get handles for the menu items.
1250 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1251 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1252 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1253 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1255 // Only display third-party cookies if SDK >= 21
1256 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1258 // Get the shared preference values. `this` references the current context.
1259 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1261 // Set the status of the additional app bar icons. The default is `false`.
1262 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
1263 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1264 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1265 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1266 } else { //Do not display the additional icons.
1267 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1268 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1269 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1276 public boolean onPrepareOptionsMenu(Menu menu) {
1277 // Get handles for the menu items.
1278 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1279 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1280 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1281 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1282 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1283 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1284 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);
1285 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1286 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1287 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1289 // Set the status of the menu item checkboxes.
1290 toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1291 toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1292 toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1293 toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);
1294 displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1296 // Enable third-party cookies if first-party cookies are enabled.
1297 toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1299 // Enable `DOM Storage` if JavaScript is enabled.
1300 toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
1302 // Enable `Clear Cookies` if there are any.
1303 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1305 // Get a count of the number of files in the `Local Storage` directory.
1306 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1307 int localStorageDirectoryNumberOfFiles = 0;
1308 if (localStorageDirectory.exists()) {
1309 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1312 // Get a count of the number of files in the `IndexedDB` directory.
1313 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1314 int indexedDBDirectoryNumberOfFiles = 0;
1315 if (indexedDBDirectory.exists()) {
1316 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1319 // Enable `Clear DOM Storage` if there is any.
1320 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1322 // Enable `Clear Form Data` is there is any.
1323 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1324 clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
1326 // Initialize font size variables.
1327 int fontSize = mainWebView.getSettings().getTextZoom();
1328 String fontSizeTitle;
1329 MenuItem selectedFontSizeMenuItem;
1331 // Prepare the font size title and current size menu item.
1334 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
1335 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1339 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
1340 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1344 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
1345 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1349 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1350 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1354 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
1355 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1359 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
1360 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1364 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
1365 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1369 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
1370 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1374 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1375 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1379 // Set the font size title and select the current size menu item.
1380 fontSizeMenuItem.setTitle(fontSizeTitle);
1381 selectedFontSizeMenuItem.setChecked(true);
1383 // Only show `Refresh` if `swipeToRefresh` is disabled.
1384 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
1386 // Run all the other default commands.
1387 super.onPrepareOptionsMenu(menu);
1389 // `return true` displays the menu.
1394 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1395 @SuppressLint("SetJavaScriptEnabled")
1396 // removeAllCookies is deprecated, but it is required for API < 21.
1397 @SuppressWarnings("deprecation")
1398 public boolean onOptionsItemSelected(MenuItem menuItem) {
1399 int menuItemId = menuItem.getItemId();
1401 // Set the commands that relate to the menu entries.
1402 switch (menuItemId) {
1403 case R.id.toggle_javascript:
1404 // Switch the status of javaScriptEnabled.
1405 javaScriptEnabled = !javaScriptEnabled;
1407 // Apply the new JavaScript status.
1408 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1410 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1411 updatePrivacyIcons(true);
1413 // Display a `Snackbar`.
1414 if (javaScriptEnabled) { // JavaScrip is enabled.
1415 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1416 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
1417 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1418 } else { // Privacy mode.
1419 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1422 // Reload the WebView.
1423 mainWebView.reload();
1426 case R.id.toggle_first_party_cookies:
1427 // Switch the status of firstPartyCookiesEnabled.
1428 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1430 // Update the menu checkbox.
1431 menuItem.setChecked(firstPartyCookiesEnabled);
1433 // Apply the new cookie status.
1434 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1436 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1437 updatePrivacyIcons(true);
1439 // Display a `Snackbar`.
1440 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1441 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1442 } else if (javaScriptEnabled){ // JavaScript is still enabled.
1443 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1444 } else { // Privacy mode.
1445 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1448 // Reload the WebView.
1449 mainWebView.reload();
1452 case R.id.toggle_third_party_cookies:
1453 if (Build.VERSION.SDK_INT >= 21) {
1454 // Switch the status of thirdPartyCookiesEnabled.
1455 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1457 // Update the menu checkbox.
1458 menuItem.setChecked(thirdPartyCookiesEnabled);
1460 // Apply the new cookie status.
1461 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1463 // Display a `Snackbar`.
1464 if (thirdPartyCookiesEnabled) {
1465 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1467 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1470 // Reload the WebView.
1471 mainWebView.reload();
1472 } // Else do nothing because SDK < 21.
1475 case R.id.toggle_dom_storage:
1476 // Switch the status of domStorageEnabled.
1477 domStorageEnabled = !domStorageEnabled;
1479 // Update the menu checkbox.
1480 menuItem.setChecked(domStorageEnabled);
1482 // Apply the new DOM Storage status.
1483 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1485 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1486 updatePrivacyIcons(true);
1488 // Display a `Snackbar`.
1489 if (domStorageEnabled) {
1490 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1492 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1495 // Reload the WebView.
1496 mainWebView.reload();
1499 case R.id.toggle_save_form_data:
1500 // Switch the status of saveFormDataEnabled.
1501 saveFormDataEnabled = !saveFormDataEnabled;
1503 // Update the menu checkbox.
1504 menuItem.setChecked(saveFormDataEnabled);
1506 // Apply the new form data status.
1507 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1509 // Display a `Snackbar`.
1510 if (saveFormDataEnabled) {
1511 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1513 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1516 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1517 updatePrivacyIcons(true);
1519 // Reload the WebView.
1520 mainWebView.reload();
1523 case R.id.clear_cookies:
1524 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1525 .setAction(R.string.undo, new View.OnClickListener() {
1527 public void onClick(View v) {
1528 // Do nothing because everything will be handled by `onDismissed()` below.
1531 .addCallback(new Snackbar.Callback() {
1533 public void onDismissed(Snackbar snackbar, int event) {
1535 // The user pushed the `Undo` button.
1536 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1540 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1542 // `cookieManager.removeAllCookie()` varies by SDK.
1543 if (Build.VERSION.SDK_INT < 21) {
1544 cookieManager.removeAllCookie();
1546 // `null` indicates no callback.
1547 cookieManager.removeAllCookies(null);
1555 case R.id.clear_dom_storage:
1556 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1557 .setAction(R.string.undo, new View.OnClickListener() {
1559 public void onClick(View v) {
1560 // Do nothing because everything will be handled by `onDismissed()` below.
1563 .addCallback(new Snackbar.Callback() {
1565 public void onDismissed(Snackbar snackbar, int event) {
1567 // The user pushed the `Undo` button.
1568 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1572 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1574 // Delete the DOM Storage.
1575 WebStorage webStorage = WebStorage.getInstance();
1576 webStorage.deleteAllData();
1578 // Manually remove `IndexedDB` if it exists.
1580 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1581 } catch (IOException e) {
1582 // Do nothing if an error is thrown.
1590 case R.id.clear_form_data:
1591 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1592 .setAction(R.string.undo, new View.OnClickListener() {
1594 public void onClick(View v) {
1595 // Do nothing because everything will be handled by `onDismissed()` below.
1598 .addCallback(new Snackbar.Callback() {
1600 public void onDismissed(Snackbar snackbar, int event) {
1602 // The user pushed the `Undo` button.
1603 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1607 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1609 // Delete the form data.
1610 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1611 mainWebViewDatabase.clearFormData();
1618 case R.id.font_size_twenty_five_percent:
1619 mainWebView.getSettings().setTextZoom(25);
1622 case R.id.font_size_fifty_percent:
1623 mainWebView.getSettings().setTextZoom(50);
1626 case R.id.font_size_seventy_five_percent:
1627 mainWebView.getSettings().setTextZoom(75);
1630 case R.id.font_size_one_hundred_percent:
1631 mainWebView.getSettings().setTextZoom(100);
1634 case R.id.font_size_one_hundred_twenty_five_percent:
1635 mainWebView.getSettings().setTextZoom(125);
1638 case R.id.font_size_one_hundred_fifty_percent:
1639 mainWebView.getSettings().setTextZoom(150);
1642 case R.id.font_size_one_hundred_seventy_five_percent:
1643 mainWebView.getSettings().setTextZoom(175);
1646 case R.id.font_size_two_hundred_percent:
1647 mainWebView.getSettings().setTextZoom(200);
1650 case R.id.display_images:
1651 if (mainWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1652 mainWebView.getSettings().setLoadsImagesAutomatically(false);
1653 mainWebView.reload();
1654 } else { // Images are not currently loaded automatically.
1655 mainWebView.getSettings().setLoadsImagesAutomatically(true);
1658 // Set `onTheFlyDisplayImagesSet`.
1659 onTheFlyDisplayImagesSet = true;
1663 // Setup the share string.
1664 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
1666 // Create the share intent.
1667 Intent shareIntent = new Intent();
1668 shareIntent.setAction(Intent.ACTION_SEND);
1669 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1670 shareIntent.setType("text/plain");
1673 startActivity(Intent.createChooser(shareIntent, "Share URL"));
1676 case R.id.find_on_page:
1677 // Hide the URL app bar.
1678 supportAppBar.setVisibility(View.GONE);
1680 // Show the Find on Page `RelativeLayout`.
1681 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1683 // 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
1684 findOnPageEditText.postDelayed(new Runnable() {
1688 // Set the focus on `findOnPageEditText`.
1689 findOnPageEditText.requestFocus();
1691 // Display the keyboard. `0` sets no input flags.
1692 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1698 // Get a `PrintManager` instance.
1699 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1701 // Convert `mainWebView` to `printDocumentAdapter`.
1702 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
1704 // Print the document. The print attributes are `null`.
1705 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1708 case R.id.add_to_homescreen:
1709 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
1710 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
1711 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
1713 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
1717 mainWebView.reload();
1721 // Don't consume the event.
1722 return super.onOptionsItemSelected(menuItem);
1726 // removeAllCookies is deprecated, but it is required for API < 21.
1727 @SuppressWarnings("deprecation")
1729 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1730 int menuItemId = menuItem.getItemId();
1732 switch (menuItemId) {
1738 if (mainWebView.canGoBack()) {
1739 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1740 navigatingHistory = true;
1742 // Load the previous website in the history.
1743 mainWebView.goBack();
1748 if (mainWebView.canGoForward()) {
1749 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1750 navigatingHistory = true;
1752 // Load the next website in the history.
1753 mainWebView.goForward();
1758 // Get the `WebBackForwardList`.
1759 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
1761 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
1762 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
1763 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
1766 case R.id.bookmarks:
1767 // Launch BookmarksActivity.
1768 Intent bookmarksIntent = new Intent(this, BookmarksActivity.class);
1769 startActivity(bookmarksIntent);
1772 case R.id.downloads:
1773 // Launch the system Download Manager.
1774 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1776 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1777 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1779 startActivity(downloadManagerIntent);
1783 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1784 currentDomainName = "";
1786 // Launch `SettingsActivity`.
1787 Intent settingsIntent = new Intent(this, SettingsActivity.class);
1788 startActivity(settingsIntent);
1792 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1793 currentDomainName = "";
1795 // Launch `DomainsActivity`.
1796 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1797 startActivity(domainsIntent);
1801 // Launch `GuideActivity`.
1802 Intent guideIntent = new Intent(this, GuideActivity.class);
1803 startActivity(guideIntent);
1807 // Launch `AboutActivity`.
1808 Intent aboutIntent = new Intent(this, AboutActivity.class);
1809 startActivity(aboutIntent);
1812 case R.id.clearAndExit:
1813 // Get a handle for `sharedPreferences`. `this` references the current context.
1814 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1816 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
1819 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
1820 // The command to remove cookies changed slightly in API 21.
1821 if (Build.VERSION.SDK_INT >= 21) {
1822 cookieManager.removeAllCookies(null);
1824 cookieManager.removeAllCookie();
1827 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1829 // We have to use two commands because `Runtime.exec()` does not like `*`.
1830 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
1831 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
1832 } catch (IOException e) {
1833 // Do nothing if an error is thrown.
1837 // Clear DOM storage.
1838 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
1839 // Ask `WebStorage` to clear the DOM storage.
1840 WebStorage webStorage = WebStorage.getInstance();
1841 webStorage.deleteAllData();
1843 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1845 // We have to use a `String[]` because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1846 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1848 // We have to use multiple commands because `Runtime.exec()` does not like `*`.
1849 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1850 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1851 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1852 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1853 } catch (IOException e) {
1854 // Do nothing if an error is thrown.
1859 if (clearEverything || sharedPreferences.getBoolean("clear_form_data", true)) {
1860 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1861 webViewDatabase.clearFormData();
1863 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1865 // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1866 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
1867 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
1868 } catch (IOException e) {
1869 // Do nothing if an error is thrown.
1874 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
1875 // `true` includes disk files.
1876 mainWebView.clearCache(true);
1878 // Manually delete the cache directories.
1880 // Delete the main cache directory.
1881 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1883 // 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.
1884 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1885 } catch (IOException e) {
1886 // Do nothing if an error is thrown.
1890 // Clear SSL certificate preferences.
1891 mainWebView.clearSslPreferences();
1893 // Clear the back/forward history.
1894 mainWebView.clearHistory();
1896 // Clear `formattedUrlString`.
1897 formattedUrlString = null;
1899 // Clear `customHeaders`.
1900 customHeaders.clear();
1902 // Detach all views from `mainWebViewRelativeLayout`.
1903 mainWebViewRelativeLayout.removeAllViews();
1905 // Destroy the internal state of `mainWebView`.
1906 mainWebView.destroy();
1908 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
1909 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
1910 if (clearEverything) {
1912 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
1913 } catch (IOException e) {
1914 // Do nothing if an error is thrown.
1918 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
1919 if (Build.VERSION.SDK_INT >= 21) {
1920 finishAndRemoveTask();
1925 // Remove the terminated program from RAM. The status code is `0`.
1930 // Close the navigation drawer.
1931 drawerLayout.closeDrawer(GravityCompat.START);
1936 public void onPostCreate(Bundle savedInstanceState) {
1937 super.onPostCreate(savedInstanceState);
1939 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
1940 drawerToggle.syncState();
1944 public void onConfigurationChanged(Configuration newConfig) {
1945 super.onConfigurationChanged(newConfig);
1947 // Reload the ad for the free flavor if we are not in full screen mode.
1948 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
1950 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1952 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1953 adView = findViewById(R.id.adview);
1956 // `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
1957 // ActivityCompat.invalidateOptionsMenu(this);
1961 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
1962 // Store the `HitTestResult`.
1963 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
1966 final String imageUrl;
1967 final String linkUrl;
1969 // Get a handle for the `ClipboardManager`.
1970 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
1972 switch (hitTestResult.getType()) {
1973 // `SRC_ANCHOR_TYPE` is a link.
1974 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1975 // Get the target URL.
1976 linkUrl = hitTestResult.getExtra();
1978 // Set the target URL as the title of the `ContextMenu`.
1979 menu.setHeaderTitle(linkUrl);
1981 // Add a `Load URL` entry.
1982 menu.add(R.string.load_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1984 public boolean onMenuItemClick(MenuItem item) {
1990 // Add a `Copy URL` entry.
1991 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1993 public boolean onMenuItemClick(MenuItem item) {
1994 // Save the link URL in a `ClipData`.
1995 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
1997 // Set the `ClipData` as the clipboard's primary clip.
1998 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2003 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2004 menu.add(R.string.cancel);
2007 case WebView.HitTestResult.EMAIL_TYPE:
2008 // Get the target URL.
2009 linkUrl = hitTestResult.getExtra();
2011 // Set the target URL as the title of the `ContextMenu`.
2012 menu.setHeaderTitle(linkUrl);
2014 // Add a `Write Email` entry.
2015 menu.add(R.string.write_email).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2017 public boolean onMenuItemClick(MenuItem item) {
2018 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2019 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2021 // Parse the url and set it as the data for the `Intent`.
2022 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2024 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2025 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2028 startActivity(emailIntent);
2033 // Add a `Copy Email Address` entry.
2034 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2036 public boolean onMenuItemClick(MenuItem item) {
2037 // Save the email address in a `ClipData`.
2038 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2040 // Set the `ClipData` as the clipboard's primary clip.
2041 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2046 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2047 menu.add(R.string.cancel);
2050 // `IMAGE_TYPE` is an image.
2051 case WebView.HitTestResult.IMAGE_TYPE:
2052 // Get the image URL.
2053 imageUrl = hitTestResult.getExtra();
2055 // Set the image URL as the title of the `ContextMenu`.
2056 menu.setHeaderTitle(imageUrl);
2058 // Add a `View Image` entry.
2059 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2061 public boolean onMenuItemClick(MenuItem item) {
2067 // Add a `Download Image` entry.
2068 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2070 public boolean onMenuItemClick(MenuItem item) {
2071 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
2072 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2073 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2078 // Add a `Copy URL` entry.
2079 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2081 public boolean onMenuItemClick(MenuItem item) {
2082 // Save the image URL in a `ClipData`.
2083 ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2085 // Set the `ClipData` as the clipboard's primary clip.
2086 clipboardManager.setPrimaryClip(srcImageTypeClipData);
2091 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2092 menu.add(R.string.cancel);
2096 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2097 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2098 // Get the image URL.
2099 imageUrl = hitTestResult.getExtra();
2101 // Set the image URL as the title of the `ContextMenu`.
2102 menu.setHeaderTitle(imageUrl);
2104 // Add a `View Image` entry.
2105 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2107 public boolean onMenuItemClick(MenuItem item) {
2113 // Add a `Download Image` entry.
2114 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2116 public boolean onMenuItemClick(MenuItem item) {
2117 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
2118 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2119 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2124 // Add a `Copy URL` entry.
2125 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2127 public boolean onMenuItemClick(MenuItem item) {
2128 // Save the image URL in a `ClipData`.
2129 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2131 // Set the `ClipData` as the clipboard's primary clip.
2132 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2137 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2138 menu.add(R.string.cancel);
2144 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
2145 // Get shortcutNameEditText from the alert dialog.
2146 EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
2148 // Create the bookmark shortcut based on formattedUrlString.
2149 Intent bookmarkShortcut = new Intent();
2150 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
2151 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
2153 // Place the bookmark shortcut on the home screen.
2154 Intent placeBookmarkShortcut = new Intent();
2155 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
2156 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
2157 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIconBitmap);
2158 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
2159 sendBroadcast(placeBookmarkShortcut);
2163 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
2164 // Download the image if it has an HTTP or HTTPS URI.
2165 if (imageUrl.startsWith("http")) {
2166 // Get a handle for the system `DOWNLOAD_SERVICE`.
2167 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2169 // Parse `imageUrl`.
2170 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
2172 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
2173 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2174 if (firstPartyCookiesEnabled) {
2175 // Get the cookies for `imageUrl`.
2176 String cookies = cookieManager.getCookie(imageUrl);
2178 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2179 downloadRequest.addRequestHeader("Cookie", cookies);
2182 // Get the file name from `dialogFragment`.
2183 EditText downloadImageNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_image_name);
2184 String imageName = downloadImageNameEditText.getText().toString();
2186 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
2187 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `imageName`.
2188 downloadRequest.setDestinationInExternalFilesDir(this, "/", imageName);
2189 } else { // Only set the title using `imageName`.
2190 downloadRequest.setTitle(imageName);
2193 // Allow `MediaScanner` to index the download if it is a media file.
2194 downloadRequest.allowScanningByMediaScanner();
2196 // Add the URL as the description for the download.
2197 downloadRequest.setDescription(imageUrl);
2199 // Show the download notification after the download is completed.
2200 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2202 // Initiate the download.
2203 downloadManager.enqueue(downloadRequest);
2204 } else { // The image is not an HTTP or HTTPS URI.
2205 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
2210 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
2211 // Download the file if it has an HTTP or HTTPS URI.
2212 if (downloadUrl.startsWith("http")) {
2214 // Get a handle for the system `DOWNLOAD_SERVICE`.
2215 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2217 // Parse `downloadUrl`.
2218 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
2220 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
2221 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2222 if (firstPartyCookiesEnabled) {
2223 // Get the cookies for `downloadUrl`.
2224 String cookies = cookieManager.getCookie(downloadUrl);
2226 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2227 downloadRequest.addRequestHeader("Cookie", cookies);
2230 // Get the file name from `dialogFragment`.
2231 EditText downloadFileNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_file_name);
2232 String fileName = downloadFileNameEditText.getText().toString();
2234 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
2235 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download location to `/sdcard/Android/data/com.stoutner.privacybrowser.standard/files` named `fileName`.
2236 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
2237 } else { // Only set the title using `fileName`.
2238 downloadRequest.setTitle(fileName);
2241 // Allow `MediaScanner` to index the download if it is a media file.
2242 downloadRequest.allowScanningByMediaScanner();
2244 // Add the URL as the description for the download.
2245 downloadRequest.setDescription(downloadUrl);
2247 // Show the download notification after the download is completed.
2248 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2250 // Initiate the download.
2251 downloadManager.enqueue(downloadRequest);
2252 } else { // The download is not an HTTP or HTTPS URI.
2253 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
2258 public void onHttpAuthenticationCancel() {
2259 // Cancel the `HttpAuthHandler`.
2260 httpAuthHandler.cancel();
2264 public void onHttpAuthenticationProceed(AppCompatDialogFragment dialogFragment) {
2265 // Get handles for the `EditTexts`.
2266 EditText usernameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.http_authentication_username);
2267 EditText passwordEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.http_authentication_password);
2269 // Proceed with the HTTP authentication.
2270 httpAuthHandler.proceed(usernameEditText.getText().toString(), passwordEditText.getText().toString());
2273 public void viewSslCertificate(View view) {
2274 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
2275 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
2276 viewSslCertificateDialogFragment.show(getFragmentManager(), getString(R.string.view_ssl_certificate));
2280 public void onSslErrorCancel() {
2281 sslErrorHandler.cancel();
2285 public void onSslErrorProceed() {
2286 sslErrorHandler.proceed();
2290 public void onSslMismatchBack() {
2291 if (mainWebView.canGoBack()) { // There is a back page in the history.
2292 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2293 navigatingHistory = true;
2296 mainWebView.goBack();
2297 } else { // There are no pages to go back to.
2298 // Load a blank page
2304 public void onSslMismatchProceed() {
2305 // Do not check the pinned SSL certificate for this domain again until the domain changes.
2306 ignorePinnedSslCertificate = true;
2310 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
2311 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2312 navigatingHistory = true;
2314 // Load the history entry.
2315 mainWebView.goBackOrForward(moveBackOrForwardSteps);
2319 public void onClearHistory() {
2320 // Clear the history.
2321 mainWebView.clearHistory();
2324 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
2326 public void onBackPressed() {
2327 // Close the navigation drawer if it is available. GravityCompat.START is the drawer on the left on Left-to-Right layout text.
2328 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
2329 drawerLayout.closeDrawer(GravityCompat.START);
2331 // Load the previous URL if available.
2332 if (mainWebView.canGoBack()) {
2333 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2334 navigatingHistory = true;
2337 mainWebView.goBack();
2339 // Pass `onBackPressed()` to the system.
2340 super.onBackPressed();
2345 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
2346 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
2347 String unformattedUrlString = urlTextBox.getText().toString().trim();
2349 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
2350 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
2351 // Add `http://` at the beginning if it is missing. Otherwise the app will segfault.
2352 if (!unformattedUrlString.startsWith("http")) {
2353 unformattedUrlString = "http://" + unformattedUrlString;
2356 // Initialize `unformattedUrl`.
2357 URL unformattedUrl = null;
2359 // 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.
2361 unformattedUrl = new URL(unformattedUrlString);
2362 } catch (MalformedURLException e) {
2363 e.printStackTrace();
2366 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2367 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2368 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2369 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2370 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2371 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2374 Uri.Builder formattedUri = new Uri.Builder();
2375 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2377 // Decode `formattedUri` as a `String` in `UTF-8`.
2378 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
2380 // Sanitize the search input and convert it to a search.
2381 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2383 // Add the base search URL.
2384 formattedUrlString = searchURL + encodedUrlString;
2387 loadUrl(formattedUrlString);
2389 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
2390 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2394 private void loadUrl(String url) {
2395 // Apply any custom domain settings.
2396 applyDomainSettings(url);
2399 mainWebView.loadUrl(url, customHeaders);
2401 // Set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
2402 urlIsLoading = true;
2405 public void findPreviousOnPage(View view) {
2406 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
2407 mainWebView.findNext(false);
2410 public void findNextOnPage(View view) {
2411 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2412 mainWebView.findNext(true);
2415 public void closeFindOnPage(View view) {
2416 // Delete the contents of `find_on_page_edittext`.
2417 findOnPageEditText.setText(null);
2419 // Clear the highlighted phrases.
2420 mainWebView.clearMatches();
2422 // Hide the Find on Page `RelativeLayout`.
2423 findOnPageLinearLayout.setVisibility(View.GONE);
2425 // Show the URL app bar.
2426 supportAppBar.setVisibility(View.VISIBLE);
2428 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
2429 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2432 private void applyAppSettings() {
2433 // Get a handle for `sharedPreferences`. `this` references the current context.
2434 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2436 // Store the values from `sharedPreferences` in variables.
2437 String homepageString = sharedPreferences.getString("homepage", "https://start.duckduckgo.com");
2438 String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
2439 String torSearchString = sharedPreferences.getString("tor_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
2440 String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
2441 String searchString = sharedPreferences.getString("search", "https://duckduckgo.com/html/?q=");
2442 String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
2443 adBlockerEnabled = sharedPreferences.getBoolean("block_ads", true);
2444 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
2445 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
2446 boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
2447 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
2448 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
2449 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
2450 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh", false);
2451 displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
2453 // Set the homepage, search, and proxy options.
2454 if (proxyThroughOrbot) { // Set the Tor options.
2455 // Set `torHomepageString` as `homepage`.
2456 homepage = torHomepageString;
2458 // If formattedUrlString is null assign the homepage to it.
2459 if (formattedUrlString == null) {
2460 formattedUrlString = homepage;
2463 // Set the search URL.
2464 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
2465 searchURL = torSearchCustomURLString;
2466 } else { // Use the string from the pre-built list.
2467 searchURL = torSearchString;
2470 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
2471 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
2473 // Set the `appBar` background to indicate proxying through Orbot is enabled. `this` refers to the context.
2475 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
2477 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
2480 // Display a message to the user if we are waiting on Orbot.
2481 if (!orbotStatus.equals("ON")) {
2482 // Set `waitingForOrbot`.
2483 waitingForOrbot = true;
2485 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
2486 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
2488 } else { // Set the non-Tor options.
2489 // Set `homepageString` as `homepage`.
2490 homepage = homepageString;
2492 // If formattedUrlString is null assign the homepage to it.
2493 if (formattedUrlString == null) {
2494 formattedUrlString = homepage;
2497 // Set the search URL.
2498 if (searchString.equals("Custom URL")) { // Get the custom URL string.
2499 searchURL = searchCustomURLString;
2500 } else { // Use the string from the pre-built list.
2501 searchURL = searchString;
2504 // Reset the proxy to default. The host is `""` and the port is `"0"`.
2505 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
2507 // Set the default `appBar` background. `this` refers to the context.
2509 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
2511 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
2514 // Reset `waitingForOrbot.
2515 waitingForOrbot = false;
2518 // Set swipe to refresh.
2519 swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
2521 // Set Do Not Track status.
2522 if (doNotTrackEnabled) {
2523 customHeaders.put("DNT", "1");
2525 customHeaders.remove("DNT");
2528 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
2529 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
2530 if (hideSystemBarsOnFullscreen) { // Hide everything.
2531 // Remove the translucent navigation setting if it is currently flagged.
2532 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2534 // Remove the translucent status bar overlay.
2535 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2537 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
2538 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
2540 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
2541 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
2542 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
2544 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
2545 } else { // Hide everything except the status and navigation bars.
2546 // Add the translucent status flag if it is unset.
2547 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2549 if (translucentNavigationBarOnFullscreen) {
2550 // Set the navigation bar to be translucent.
2551 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2553 // Set the navigation bar to be black.
2554 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2557 } else { // Switch to normal viewing mode.
2558 // Reset `inFullScreenBrowsingMode` to `false`.
2559 inFullScreenBrowsingMode = false;
2561 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
2562 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
2566 // Show the `BannerAd` in the free flavor.
2567 if (BuildConfig.FLAVOR.contentEquals("free")) {
2568 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
2569 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2571 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2572 adView = findViewById(R.id.adview);
2575 // Remove the translucent navigation bar flag if it is set.
2576 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2578 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
2579 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2581 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
2582 rootCoordinatorLayout.setSystemUiVisibility(0);
2584 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
2585 rootCoordinatorLayout.setFitsSystemWindows(true);
2589 // We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2590 @SuppressWarnings("deprecation")
2591 private void applyDomainSettings(String url) {
2592 // Reset `navigatingHistory`.
2593 navigatingHistory = false;
2595 // Parse the URL into a URI.
2596 Uri uri = Uri.parse(url);
2598 // Extract the domain from `uri`.
2599 String hostName = uri.getHost();
2601 // Initialize `loadingNewDomainName`.
2602 boolean loadingNewDomainName;
2604 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
2605 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
2606 //noinspection SimplifiableIfStatement
2607 if ((hostName == null) || (currentDomainName == null)) {
2608 loadingNewDomainName = true;
2609 } else { // Determine if `hostName` equals `currentDomainName`.
2610 loadingNewDomainName = !hostName.equals(currentDomainName);
2613 // 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.
2614 if (loadingNewDomainName) {
2615 // Set the new `hostname` as the `currentDomainName`.
2616 currentDomainName = hostName;
2618 // Reset `ignorePinnedSslCertificate`.
2619 ignorePinnedSslCertificate = false;
2621 // Reset `favoriteIconBitmap` and display it in the `appbar`.
2622 favoriteIconBitmap = favoriteIconDefaultBitmap;
2623 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
2625 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
2626 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2627 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2629 // Get a full cursor from `domainsDatabaseHelper`.
2630 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
2632 // Initialize `domainSettingsSet`.
2633 Set<String> domainSettingsSet = new HashSet<>();
2635 // Get the domain name column index.
2636 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
2638 // Populate `domainSettingsSet`.
2639 for (int i = 0; i < domainNameCursor.getCount(); i++) {
2640 // Move `domainsCursor` to the current row.
2641 domainNameCursor.moveToPosition(i);
2643 // Store the domain name in `domainSettingsSet`.
2644 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
2647 // Close `domainNameCursor.
2648 domainNameCursor.close();
2650 // Initialize variables to track if domain settings will be applied and, if so, under which name.
2651 domainSettingsApplied = false;
2652 String domainNameInDatabase = null;
2654 // Check the hostname.
2655 if (domainSettingsSet.contains(hostName)) {
2656 domainSettingsApplied = true;
2657 domainNameInDatabase = hostName;
2660 // If `hostName` is not `null`, check all the subdomains of `hostName` against wildcard domains in `domainCursor`.
2661 if (hostName != null) {
2662 while (hostName.contains(".") && !domainSettingsApplied) { // Stop checking if we run out of `.` or if we already know that `domainSettingsApplied` is `true`.
2663 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
2664 domainSettingsApplied = true;
2665 domainNameInDatabase = "*." + hostName;
2668 // Strip out the lowest subdomain of `host`.
2669 hostName = hostName.substring(hostName.indexOf(".") + 1);
2673 // Get a handle for the shared preference. `this` references the current context.
2674 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2676 // Store the general preference information.
2677 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
2678 String defaultUserAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
2679 String defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
2680 nightMode = sharedPreferences.getBoolean("night_mode", false);
2682 if (domainSettingsApplied) { // The url we are loading has custom domain settings.
2683 // Get a cursor for the current host and move it to the first position.
2684 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
2685 currentHostDomainSettingsCursor.moveToFirst();
2687 // Get the settings from the cursor.
2688 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
2689 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
2690 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
2691 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
2692 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
2693 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
2694 String userAgentString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
2695 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
2696 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
2697 int nightModeInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
2698 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
2699 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
2700 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
2701 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
2702 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
2703 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
2704 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
2706 // Set `nightMode` according to `nightModeInt`. If `nightModeInt` is `DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT` the current setting from `sharedPreferences` will be used.
2707 switch (nightModeInt) {
2708 case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
2712 case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
2717 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
2719 javaScriptEnabled = true;
2722 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
2723 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
2724 pinnedDomainSslStartDate = null;
2726 pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
2729 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
2730 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
2731 pinnedDomainSslEndDate = null;
2733 pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
2736 // Close `currentHostDomainSettingsCursor`.
2737 currentHostDomainSettingsCursor.close();
2739 // Apply the domain settings.
2740 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2741 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2742 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2743 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2745 // Apply the font size.
2746 if (fontSize == 0) { // Apply the default font size.
2747 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
2748 } else { // Apply the specified font size.
2749 mainWebView.getSettings().setTextZoom(fontSize);
2752 // Set third-party cookies status if API >= 21.
2753 if (Build.VERSION.SDK_INT >= 21) {
2754 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2757 // 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>
2758 if (!urlIsLoading) {
2759 switch (userAgentString) {
2760 case "System default user agent":
2761 // Set the user agent according to the system default.
2762 switch (defaultUserAgentString) {
2763 case "WebView default user agent":
2764 // Set the user agent to `""`, which uses the default value.
2765 mainWebView.getSettings().setUserAgentString("");
2768 case "Custom user agent":
2769 // Set the custom user agent.
2770 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
2774 // Use the selected user agent.
2775 mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
2779 case "WebView default user agent":
2780 // Set the user agent to `""`, which uses the default value.
2781 mainWebView.getSettings().setUserAgentString("");
2785 // Use the selected user agent.
2786 mainWebView.getSettings().setUserAgentString(userAgentString);
2790 // 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.
2792 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
2794 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
2796 } else { // The URL we are loading does not have custom domain settings. Load the defaults.
2797 // Store the values from `sharedPreferences` in variables.
2798 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
2799 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
2800 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
2801 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
2802 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
2804 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
2806 javaScriptEnabled = true;
2809 // Apply the default settings.
2810 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2811 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2812 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2813 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2814 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
2816 // Reset the pinned SSL certificate information.
2817 domainSettingsDatabaseId = -1;
2818 pinnedDomainSslCertificate = false;
2819 pinnedDomainSslIssuedToCNameString = "";
2820 pinnedDomainSslIssuedToONameString = "";
2821 pinnedDomainSslIssuedToUNameString = "";
2822 pinnedDomainSslIssuedByCNameString = "";
2823 pinnedDomainSslIssuedByONameString = "";
2824 pinnedDomainSslIssuedByUNameString = "";
2825 pinnedDomainSslStartDate = null;
2826 pinnedDomainSslEndDate = null;
2828 // Set third-party cookies status if API >= 21.
2829 if (Build.VERSION.SDK_INT >= 21) {
2830 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2833 // 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>
2834 if (!urlIsLoading) {
2835 switch (defaultUserAgentString) {
2836 case "WebView default user agent":
2837 // Set the user agent to `""`, which uses the default value.
2838 mainWebView.getSettings().setUserAgentString("");
2841 case "Custom user agent":
2842 // Set the custom user agent.
2843 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
2847 // Use the selected user agent.
2848 mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
2852 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2853 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
2856 // Close `domainsDatabaseHelper`.
2857 domainsDatabaseHelper.close();
2859 // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode. `true` indicates that custom domain settings are applied.
2860 onTheFlyDisplayImagesSet = false;
2861 setDisplayWebpageImages();
2863 // Update the privacy icons, but only if `mainMenu` has already been populated.
2864 if (mainMenu != null) {
2865 updatePrivacyIcons(true);
2870 private void setDisplayWebpageImages() {
2871 if (!onTheFlyDisplayImagesSet) {
2872 if (domainSettingsApplied) { // Custom domain settings are applied.
2873 switch (displayWebpageImagesInt) {
2874 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
2875 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
2878 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
2879 mainWebView.getSettings().setLoadsImagesAutomatically(true);
2882 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
2883 mainWebView.getSettings().setLoadsImagesAutomatically(false);
2886 } else { // Default settings are applied.
2887 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
2892 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
2893 // Get handles for the icons.
2894 MenuItem privacyIconMenuItem = mainMenu.findItem(R.id.toggle_javascript);
2895 MenuItem firstPartyCookiesIconMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
2896 MenuItem domStorageIconMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
2897 MenuItem formDataIconMenuItem = mainMenu.findItem(R.id.toggle_save_form_data);
2899 // Update `privacyIcon`.
2900 if (javaScriptEnabled) { // JavaScript is enabled.
2901 privacyIconMenuItem.setIcon(R.drawable.javascript_enabled);
2902 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
2903 privacyIconMenuItem.setIcon(R.drawable.warning);
2904 } else { // All the dangerous features are disabled.
2905 privacyIconMenuItem.setIcon(R.drawable.privacy_mode);
2908 // Update `firstPartyCookiesIcon`.
2909 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
2910 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_enabled);
2911 } else { // First-party cookies are disabled.
2913 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_dark);
2915 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_light);
2919 // Update `domStorageIcon`.
2920 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
2921 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_enabled);
2922 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
2924 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
2926 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
2928 } else { // JavaScript is disabled, so DOM storage is ghosted.
2930 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
2932 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
2936 // Update `formDataIcon`.
2937 if (saveFormDataEnabled) { // Form data is enabled.
2938 formDataIconMenuItem.setIcon(R.drawable.form_data_enabled);
2939 } else { // Form data is disabled.
2941 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_dark);
2943 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_light);
2947 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`. `this` references the current activity.
2948 if (runInvalidateOptionsMenu) {
2949 ActivityCompat.invalidateOptionsMenu(this);
2953 private void highlightUrlText() {
2954 String urlString = urlTextBox.getText().toString();
2956 if (urlString.startsWith("http://")) { // Highlight connections that are not encrypted.
2957 urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
2958 } else if (urlString.startsWith("https://")) { // Highlight connections that are encrypted.
2959 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
2962 // Get the index of the `/` immediately after the domain name.
2963 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
2965 // De-emphasize the text after the domain name.
2966 if (endOfDomainName > 0) {
2967 urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);