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.preference.PreferenceManager;
45 import android.print.PrintDocumentAdapter;
46 import android.print.PrintManager;
47 import android.support.annotation.NonNull;
48 import android.support.design.widget.CoordinatorLayout;
49 import android.support.design.widget.NavigationView;
50 import android.support.design.widget.Snackbar;
51 import android.support.v4.app.ActivityCompat;
52 import android.support.v4.content.ContextCompat;
53 import android.support.v4.view.GravityCompat;
54 import android.support.v4.widget.DrawerLayout;
55 import android.support.v4.widget.SwipeRefreshLayout;
56 import android.support.v7.app.ActionBar;
57 import android.support.v7.app.ActionBarDrawerToggle;
58 import android.support.v7.app.AppCompatActivity;
59 import android.support.v7.app.AppCompatDialogFragment;
60 import android.support.v7.widget.Toolbar;
61 import android.text.Editable;
62 import android.text.Spanned;
63 import android.text.TextWatcher;
64 import android.text.style.ForegroundColorSpan;
65 import android.util.Patterns;
66 import android.view.ContextMenu;
67 import android.view.GestureDetector;
68 import android.view.KeyEvent;
69 import android.view.Menu;
70 import android.view.MenuItem;
71 import android.view.MotionEvent;
72 import android.view.View;
73 import android.view.WindowManager;
74 import android.view.inputmethod.InputMethodManager;
75 import android.webkit.CookieManager;
76 import android.webkit.DownloadListener;
77 import android.webkit.HttpAuthHandler;
78 import android.webkit.SslErrorHandler;
79 import android.webkit.WebBackForwardList;
80 import android.webkit.WebChromeClient;
81 import android.webkit.WebResourceResponse;
82 import android.webkit.WebStorage;
83 import android.webkit.WebView;
84 import android.webkit.WebViewClient;
85 import android.webkit.WebViewDatabase;
86 import android.widget.EditText;
87 import android.widget.FrameLayout;
88 import android.widget.ImageView;
89 import android.widget.LinearLayout;
90 import android.widget.ProgressBar;
91 import android.widget.RelativeLayout;
92 import android.widget.TextView;
94 import com.stoutner.privacybrowser.BannerAd;
95 import com.stoutner.privacybrowser.BuildConfig;
96 import com.stoutner.privacybrowser.R;
97 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
98 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
99 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
100 import com.stoutner.privacybrowser.dialogs.PinnedSslCertificateMismatchDialog;
101 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
102 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
103 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
104 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
105 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
106 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
108 import java.io.BufferedReader;
109 import java.io.ByteArrayInputStream;
111 import java.io.IOException;
112 import java.io.InputStreamReader;
113 import java.io.UnsupportedEncodingException;
114 import java.net.MalformedURLException;
116 import java.net.URLDecoder;
117 import java.net.URLEncoder;
118 import java.util.Date;
119 import java.util.HashMap;
120 import java.util.HashSet;
121 import java.util.Map;
122 import java.util.Set;
124 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
125 public class MainWebViewActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, CreateHomeScreenShortcutDialog.CreateHomeScreenSchortcutListener,
126 HttpAuthenticationDialog.HttpAuthenticationListener, PinnedSslCertificateMismatchDialog.PinnedSslCertificateMismatchListener, SslCertificateErrorDialog.SslCertificateErrorListener, DownloadFileDialog.DownloadFileListener,
127 DownloadImageDialog.DownloadImageListener, UrlHistoryDialog.UrlHistoryListener {
129 // `darkTheme` is public static so it can be accessed from `AboutActivity`, `GuideActivity`, `AddDomainDialog`, `SettingsActivity`, `DomainsActivity`, `DomainsListFragment`, `BookmarksActivity`, `BookmarksDatabaseViewActivity`,
130 // `CreateBookmarkDialog`, `CreateBookmarkFolderDialog`, `DownloadFileDialog`, `DownloadImageDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`, `HttpAuthenticationDialog`, `MoveToFolderDialog`, `SslCertificateErrorDialog`, `UrlHistoryDialog`,
131 // `ViewSslCertificateDialog`, `CreateHomeScreenShortcutDialog`, and `OrbotProxyHelper`. It is also used in `onCreate()`, `applyAppSettings()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
132 public static boolean darkTheme;
134 // `favoriteIconBitmap` is public static so it can be accessed from `CreateHomeScreenShortcutDialog`, `BookmarksActivity`, `CreateBookmarkDialog`, `CreateBookmarkFolderDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`,
135 // and `ViewSslCertificateDialog`. It is also used in `onCreate()`, `onCreateHomeScreenShortcutCreate()`, and `applyDomainSettings`.
136 public static Bitmap favoriteIconBitmap;
138 // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`, `CreateBookmarkDialog`, and `AddDomainDialog`.
139 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
140 public static String formattedUrlString;
142 // `sslCertificate` is public static so it can be accessed from `DomainsActivity`, `DomainsListFragment`, `DomainSettingsFragment`, `PinnedSslCertificateMismatchDialog`, and `ViewSslCertificateDialog`. It is also used in `onCreate()`.
143 public static SslCertificate sslCertificate;
145 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`.
146 public static String orbotStatus;
148 // `webViewTitle` is public static so it can be accessed from `CreateBookmarkDialog` and `CreateHomeScreenShortcutDialog`. It is also used in `onCreate()`.
149 public static String webViewTitle;
151 // `displayWebpageImagesBoolean` is public static so it can be accessed from `DomainSettingsFragment`. It is also used in `applyAppSettings()` and `applyDomainSettings()`.
152 public static boolean displayWebpageImagesBoolean;
154 // `reloadOnRestartBoolean` is public static so it can be accessed from `SettingsFragment`. It is also used in `onRestart()`
155 public static boolean reloadOnRestartBoolean;
157 // The pinned domain SSL Certificate variables are public static so they can be accessed from `PinnedSslCertificateMismatchDialog`. They are also used in `onCreate()` and `applyDomainSettings()`.
158 public static int domainSettingsDatabaseId;
159 public static String pinnedDomainSslIssuedToCNameString;
160 public static String pinnedDomainSslIssuedToONameString;
161 public static String pinnedDomainSslIssuedToUNameString;
162 public static String pinnedDomainSslIssuedByCNameString;
163 public static String pinnedDomainSslIssuedByONameString;
164 public static String pinnedDomainSslIssuedByUNameString;
165 public static Date pinnedDomainSslStartDate;
166 public static Date pinnedDomainSslEndDate;
169 // `appBar` is used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applyAppSettings()`.
170 private ActionBar appBar;
172 // `navigatingHistory` is used in `onCreate()`, `onNavigationItemSelected()`, `onSslMismatchBack()`, and `applyDomainSettings()`.
173 private boolean navigatingHistory;
175 // `favoriteIconDefaultBitmap` is used in `onCreate()` and `applyDomainSettings`.
176 private Bitmap favoriteIconDefaultBitmap;
178 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, and `onBackPressed()`.
179 private DrawerLayout drawerLayout;
181 // `rootCoordinatorLayout` is used in `onCreate()` and `applyAppSettings()`.
182 private CoordinatorLayout rootCoordinatorLayout;
184 // `mainWebView` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`, `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`
185 // `onSslMismatchBack()`, and `setDisplayWebpageImages()`.
186 private WebView mainWebView;
188 // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
189 private FrameLayout fullScreenVideoFrameLayout;
191 // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu`, and `onRestart()`.
192 private SwipeRefreshLayout swipeRefreshLayout;
194 // `urlAppBarRelativeLayout` is used in `onCreate()` and `applyDomainSettings()`.
195 private RelativeLayout urlAppBarRelativeLayout;
197 // `favoriteIconImageView` is used in `onCreate()` and `applyDomainSettings()`
198 private ImageView favoriteIconImageView;
200 // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `loadUrlFromTextBox()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
201 private CookieManager cookieManager;
203 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
204 private final Map<String, String> customHeaders = new HashMap<>();
206 // `javaScriptEnabled` is also used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `applyAppSettings()`.
207 // It is `Boolean` instead of `boolean` because `applyAppSettings()` needs to know if it is `null`.
208 private Boolean javaScriptEnabled;
210 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applyAppSettings()`.
211 private boolean firstPartyCookiesEnabled;
213 // `thirdPartyCookiesEnabled` used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
214 private boolean thirdPartyCookiesEnabled;
216 // `domStorageEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
217 private boolean domStorageEnabled;
219 // `saveFormDataEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
220 private boolean saveFormDataEnabled;
222 // `swipeToRefreshEnabled` is used in `onPrepareOptionsMenu()` and `applyAppSettings()`.
223 private boolean swipeToRefreshEnabled;
225 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applyAppSettings()`.
226 private String homepage;
228 // `searchURL` is used in `loadURLFromTextBox()` and `applyAppSettings()`.
229 private String searchURL;
231 // `adBlockerEnabled` is used in `onCreate()` and `applyAppSettings()`.
232 private boolean adBlockerEnabled;
234 // `privacyBrowserRuntime` is used in `onCreate()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
235 private Runtime privacyBrowserRuntime;
237 // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
238 private boolean incognitoModeEnabled;
240 // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
241 private boolean fullScreenBrowsingModeEnabled;
243 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
244 private boolean inFullScreenBrowsingMode;
246 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
247 private boolean hideSystemBarsOnFullscreen;
249 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
250 private boolean translucentNavigationBarOnFullscreen;
252 // `currentDomainName` is used in `onCreate()`, `onNavigationItemSelected()`, `onSslMismatchProceed()`, and `applyDomainSettings()`.
253 private String currentDomainName;
255 // `ignorePinnedSslCertificateForDomain` is used in `onCreate()`, `onSslMismatchProceed()`, and `applyDomainSettings()`.
256 private boolean ignorePinnedSslCertificate;
258 // `waitingForOrbot` is used in `onCreate()` and `applyAppSettings()`.
259 private boolean waitingForOrbot;
261 // `domainSettingsApplied` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
262 private boolean domainSettingsApplied;
264 // `displayWebpageImagesInt` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
265 private int displayWebpageImagesInt;
267 // `onTheFlyDisplayImagesSet` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
268 private boolean onTheFlyDisplayImagesSet;
270 // `waitingForOrbotData` is used in `onCreate()` and `applyAppSettings()`.
271 private String waitingForOrbotHTMLString;
273 // `privateDataDirectoryString` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
274 private String privateDataDirectoryString;
276 // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
277 private LinearLayout findOnPageLinearLayout;
279 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
280 private EditText findOnPageEditText;
282 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
283 private Menu mainMenu;
285 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
286 private ActionBarDrawerToggle drawerToggle;
288 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
289 private Toolbar supportAppBar;
291 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, `loadUrl()`, and `highlightUrlText()`.
292 private EditText urlTextBox;
294 // `redColorSpan` is used in `onCreate()` and `highlightUrlText()`.
295 private ForegroundColorSpan redColorSpan;
297 // `initialGrayColorSpan` is sued in `onCreate()` and `highlightUrlText()`.
298 private ForegroundColorSpan initialGrayColorSpan;
300 // `finalGrayColorSpam` is used in `onCreate()` and `highlightUrlText()`.
301 private ForegroundColorSpan finalGrayColorSpan;
303 // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
306 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
307 private SslErrorHandler sslErrorHandler;
309 // `httpAuthHandler` is used in `onCreate()`, `onHttpAuthenticationCancel()`, and `onHttpAuthenticationProceed()`.
310 private static HttpAuthHandler httpAuthHandler;
312 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
313 private InputMethodManager inputMethodManager;
315 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
316 private RelativeLayout mainWebViewRelativeLayout;
318 // `urlIsLoading` is used in `onCreate()`, `loadUrl()`, and `applyDomainSettings()`.
319 private boolean urlIsLoading;
321 // `pinnedDomainSslCertificate` is used in `onCreate()` and `applyDomainSettings()`.
322 private boolean pinnedDomainSslCertificate;
326 // 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.
327 @SuppressLint("SetJavaScriptEnabled")
328 // Remove Android Studio's warning about deprecations. We have to use the deprecated `getColor()` until API >= 23.
329 @SuppressWarnings("deprecation")
330 protected void onCreate(Bundle savedInstanceState) {
331 // Get a handle for `sharedPreferences`. `this` references the current context.
332 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
334 // Get the theme preference.
335 darkTheme = sharedPreferences.getBoolean("dark_theme", false);
337 // Set the activity theme.
339 setTheme(R.style.PrivacyBrowserDark);
341 setTheme(R.style.PrivacyBrowserLight);
344 // Run the default commands.
345 super.onCreate(savedInstanceState);
347 // Set the content view.
348 setContentView(R.layout.main_drawerlayout);
350 // Get a handle for `inputMethodManager`.
351 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
353 // We need to use the `SupportActionBar` from `android.support.v7.app.ActionBar` until the minimum API is >= 21.
354 supportAppBar = (Toolbar) findViewById(R.id.app_bar);
355 setSupportActionBar(supportAppBar);
356 appBar = getSupportActionBar();
358 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
359 assert appBar != null;
361 // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
362 appBar.setCustomView(R.layout.url_app_bar);
363 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
365 // Initialize the `ForegroundColorSpans` and `StyleSpan` for highlighting `urlTextBox`. We have to use the deprecated `getColor()` until API >= 23.
366 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
367 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
368 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
370 // Get a handle for `urlTextBox`.
371 urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.url_edittext);
373 // Remove the formatting from `urlTextBar` when the user is editing the text.
374 urlTextBox.setOnFocusChangeListener(new View.OnFocusChangeListener() {
376 public void onFocusChange(View v, boolean hasFocus) {
377 if (hasFocus) { // The user is editing `urlTextBox`.
378 // Remove the highlighting.
379 urlTextBox.getText().removeSpan(redColorSpan);
380 urlTextBox.getText().removeSpan(initialGrayColorSpan);
381 urlTextBox.getText().removeSpan(finalGrayColorSpan);
382 } else { // The user has stopped editing `urlTextBox`.
383 // Reapply the highlighting.
389 // Set the `Go` button on the keyboard to load the URL in `urlTextBox`.
390 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
392 public boolean onKey(View v, int keyCode, KeyEvent event) {
393 // If the event is a key-down event on the `enter` button, load the URL.
394 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
395 // Load the URL into the mainWebView and consume the event.
397 loadUrlFromTextBox();
398 } catch (UnsupportedEncodingException e) {
401 // If the enter key was pressed, consume the event.
404 // If any other key was pressed, do not consume the event.
410 // Set `waitingForOrbotHTMLString`.
411 waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
413 // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
414 currentDomainName = "";
415 orbotStatus = "unknown";
416 waitingForOrbot = false;
418 // Create an Orbot status `BroadcastReceiver`.
419 BroadcastReceiver orbotStatusBroadcastReceiver = new BroadcastReceiver() {
421 public void onReceive(Context context, Intent intent) {
422 // Store the content of the status message in `orbotStatus`.
423 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
425 // If we are waiting on Orbot, load the website now that Orbot is connected.
426 if (orbotStatus.equals("ON") && waitingForOrbot) {
427 // Reset `waitingForOrbot`.
428 waitingForOrbot = false;
430 // Load `formattedUrlString
431 loadUrl(formattedUrlString);
436 // Register `orbotStatusBroadcastReceiver` on `this` context.
437 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
439 // Get handles for views that need to be accessed.
440 drawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout);
441 rootCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.root_coordinatorlayout);
442 mainWebViewRelativeLayout = (RelativeLayout) findViewById(R.id.main_webview_relativelayout);
443 mainWebView = (WebView) findViewById(R.id.main_webview);
444 findOnPageLinearLayout = (LinearLayout) findViewById(R.id.find_on_page_linearlayout);
445 findOnPageEditText = (EditText) findViewById(R.id.find_on_page_edittext);
446 fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.full_screen_video_framelayout);
447 urlAppBarRelativeLayout = (RelativeLayout) findViewById(R.id.url_app_bar_relativelayout);
448 favoriteIconImageView = (ImageView) findViewById(R.id.favorite_icon);
450 // Create a double-tap listener to toggle full-screen mode.
451 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
452 // Override `onDoubleTap()`. All other events are handled using the default settings.
454 public boolean onDoubleTap(MotionEvent event) {
455 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
456 // Toggle `inFullScreenBrowsingMode`.
457 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
459 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
460 // Hide the `appBar`.
463 // Hide the `BannerAd` in the free flavor.
464 if (BuildConfig.FLAVOR.contentEquals("free")) {
465 BannerAd.hideAd(adView);
468 // Modify the system bars.
469 if (hideSystemBarsOnFullscreen) { // Hide everything.
470 // Remove the translucent overlays.
471 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
473 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
474 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
476 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
477 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
478 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
480 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
482 // Set `rootCoordinatorLayout` to fill the whole screen.
483 rootCoordinatorLayout.setFitsSystemWindows(false);
484 } else { // Hide everything except the status and navigation bars.
485 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
486 rootCoordinatorLayout.setFitsSystemWindows(false);
488 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.
489 // Set the navigation bar to be translucent.
490 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
493 } else { // Switch to normal viewing mode.
494 // Show the `appBar`.
497 // Show the `BannerAd` in the free flavor.
498 if (BuildConfig.FLAVOR.contentEquals("free")) {
499 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
500 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
502 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
503 adView = findViewById(R.id.adview);
506 // Remove the translucent navigation bar flag if it is set.
507 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
509 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
510 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
512 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
513 rootCoordinatorLayout.setSystemUiVisibility(0);
515 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
516 rootCoordinatorLayout.setFitsSystemWindows(true);
519 // Consume the double-tap.
521 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
527 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
528 mainWebView.setOnTouchListener(new View.OnTouchListener() {
530 public boolean onTouch(View v, MotionEvent event) {
531 // Send the `event` to `gestureDetector`.
532 return gestureDetector.onTouchEvent(event);
536 // Update `findOnPageCountTextView`.
537 mainWebView.setFindListener(new WebView.FindListener() {
538 // Get a handle for `findOnPageCountTextView`.
539 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
542 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
543 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
544 // Set `findOnPageCountTextView` to `0/0`.
545 findOnPageCountTextView.setText(R.string.zero_of_zero);
546 } else if (isDoneCounting) { // There are matches.
547 // `activeMatchOrdinal` is zero-based.
548 int activeMatch = activeMatchOrdinal + 1;
550 // Set `findOnPageCountTextView`.
551 findOnPageCountTextView.setText(activeMatch + "/" + numberOfMatches);
556 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
557 findOnPageEditText.addTextChangedListener(new TextWatcher() {
559 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
564 public void onTextChanged(CharSequence s, int start, int before, int count) {
569 public void afterTextChanged(Editable s) {
570 // Search for the text in `mainWebView`.
571 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
575 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
576 findOnPageEditText.setOnKeyListener(new View.OnKeyListener() {
578 public boolean onKey(View v, int keyCode, KeyEvent event) {
579 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
580 // Hide the soft keyboard. `0` indicates no additional flags.
581 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
583 // Consume the event.
585 } else { // A different key was pressed.
586 // Do not consume the event.
592 // Implement swipe to refresh
593 swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refreshlayout);
594 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
595 swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
597 public void onRefresh() {
598 mainWebView.reload();
602 // `DrawerTitle` identifies the `DrawerLayout` in accessibility mode.
603 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
605 // Listen for touches on the navigation menu.
606 final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationview);
607 navigationView.setNavigationItemSelectedListener(this);
609 // 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.
610 final Menu navigationMenu = navigationView.getMenu();
611 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
612 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
613 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
615 // The `DrawerListener` allows us to update the Navigation Menu.
616 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
618 public void onDrawerSlide(View drawerView, float slideOffset) {
622 public void onDrawerOpened(View drawerView) {
626 public void onDrawerClosed(View drawerView) {
630 public void onDrawerStateChanged(int newState) {
631 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // The drawer is opening or closing.
632 // Update the `Back`, `Forward`, and `History` menu items.
633 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
634 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
635 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
637 // Hide the keyboard (if displayed) so we can see the navigation menu. `0` indicates no additional flags.
638 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
640 // Clear the focus from `urlTextBox` if it has it.
641 urlTextBox.clearFocus();
646 // drawerToggle creates the hamburger icon at the start of the AppBar.
647 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
649 // Initialize `adServerSet`.
650 final Set<String> adServersSet = new HashSet<>();
652 // Load the list of ad servers into memory.
654 // Load `pgl.yoyo.org_adservers.txt` into a `BufferedReader`.
655 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(getAssets().open("pgl.yoyo.org_adservers.txt")));
657 // Create a string for storing each ad server.
660 // Populate `adServersSet`.
661 while ((adServer = bufferedReader.readLine()) != null) {
662 adServersSet.add(adServer);
665 // Close `bufferedReader`.
666 bufferedReader.close();
667 } catch (IOException ioException) {
668 // We're pretty sure the asset exists, so we don't need to worry about the `IOException` ever being thrown.
671 mainWebView.setWebViewClient(new WebViewClient() {
672 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
673 // We have to use the deprecated `shouldOverrideUrlLoading` until API >= 24.
674 @SuppressWarnings("deprecation")
676 public boolean shouldOverrideUrlLoading(WebView view, String url) {
677 if (url.startsWith("mailto:")) { // Load the URL in an external email program because it begins with `mailto:`.
678 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
679 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
681 // Parse the url and set it as the data for the `Intent`.
682 emailIntent.setData(Uri.parse(url));
684 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
685 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
688 startActivity(emailIntent);
690 // Returning `true` indicates the application is handling the URL.
692 } else { // Load the URL in Privacy Browser.
693 // Apply the domain settings for the new URL.
694 applyDomainSettings(url);
696 // Returning `false` causes the current `WebView` to handle the URL and prevents it from adding redirects to the history list.
701 // Block ads. We have to use the deprecated `shouldInterceptRequest` until minimum API >= 21.
702 @SuppressWarnings("deprecation")
704 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
705 if (adBlockerEnabled) { // Block ads.
706 // Extract the host from `url`.
707 Uri requestUri = Uri.parse(url);
708 String requestHost = requestUri.getHost();
710 // Initialize a variable to track if this is an ad server.
711 boolean requestHostIsAdServer = false;
713 // Check all the subdomains of `requestHost` if it is not `null` against the ad server database.
714 if (requestHost != null) {
715 while (requestHost.contains(".") && !requestHostIsAdServer) { // Stop checking if we run out of `.` or if we already know that `requestHostIsAdServer` is `true`.
716 if (adServersSet.contains(requestHost)) {
717 requestHostIsAdServer = true;
720 // Strip out the lowest subdomain of `requestHost`.
721 requestHost = requestHost.substring(requestHost.indexOf(".") + 1);
725 if (requestHostIsAdServer) { // It is an ad server.
726 // Return an empty `WebResourceResponse`.
727 return new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
728 } else { // It is not an ad server.
729 // `return null` loads the requested resource.
732 } else { // Ad blocking is disabled.
733 // `return null` loads the requested resource.
738 // Handle HTTP authentication requests.
740 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
741 // Store `handler` so it can be accessed from `onHttpAuthenticationCancel()` and `onHttpAuthenticationProceed()`.
742 httpAuthHandler = handler;
744 // Display the HTTP authentication dialog.
745 AppCompatDialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm);
746 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
749 // Update the URL in urlTextBox when the page starts to load.
751 public void onPageStarted(WebView view, String url, Bitmap favicon) {
752 // Check to see if we are waiting on Orbot.
753 if (!waitingForOrbot) { // We are not waiting on Orbot, so we need to process the URL.
754 // 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.
755 formattedUrlString = url;
757 // Display the formatted URL text.
758 urlTextBox.setText(formattedUrlString);
760 // Apply text highlighting to `urlTextBox`.
763 // Apply any custom domain settings if the URL was loaded by navigating history.
764 if (navigatingHistory) {
765 applyDomainSettings(url);
768 // 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.
773 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
775 public void onPageFinished(WebView view, String url) {
776 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
777 urlIsLoading = false;
779 // Clear the cache and history if Incognito Mode is enabled.
780 if (incognitoModeEnabled) {
781 // Clear the cache. `true` includes disk files.
782 mainWebView.clearCache(true);
784 // Clear the back/forward history.
785 mainWebView.clearHistory();
787 // Manually delete cache folders.
789 // Delete the main `cache` folder.
790 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
792 // 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`.
793 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
794 } catch (IOException e) {
795 // Do nothing if an error is thrown.
799 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
800 if (!waitingForOrbot) {
801 // Check to see if `WebView` has set `url` to be `about:blank`.
802 if (url.equals("about:blank")) { // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
803 // Set `formattedUrlString` to `""`.
804 formattedUrlString = "";
806 urlTextBox.setText(formattedUrlString);
808 // Request focus for `urlTextBox`.
809 urlTextBox.requestFocus();
811 // Display the keyboard.
812 inputMethodManager.showSoftInput(urlTextBox, 0);
814 // Apply the domain settings. This clears any settings from the previous domain.
815 applyDomainSettings(formattedUrlString);
816 } else { // `WebView` has loaded a webpage.
817 // Set `formattedUrlString`.
818 formattedUrlString = url;
820 // Only update `urlTextBox` if the user is not typing in it.
821 if (!urlTextBox.hasFocus()) {
822 // Display the formatted URL text.
823 urlTextBox.setText(formattedUrlString);
825 // Apply text highlighting to `urlTextBox`.
830 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
831 sslCertificate = mainWebView.getCertificate();
833 // 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.
834 if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate) {
835 // Initialize the current SSL certificate variables.
836 String currentWebsiteIssuedToCName = "";
837 String currentWebsiteIssuedToOName = "";
838 String currentWebsiteIssuedToUName = "";
839 String currentWebsiteIssuedByCName = "";
840 String currentWebsiteIssuedByOName = "";
841 String currentWebsiteIssuedByUName = "";
842 Date currentWebsiteSslStartDate = null;
843 Date currentWebsiteSslEndDate = null;
846 // Extract the individual pieces of information from the current website SSL certificate if it is not null.
847 if (sslCertificate != null) {
848 currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
849 currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
850 currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
851 currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
852 currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
853 currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
854 currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
855 currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
858 // 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`.
859 String currentWebsiteSslStartDateString = "";
860 String currentWebsiteSslEndDateString = "";
861 String pinnedDomainSslStartDateString = "";
862 String pinnedDomainSslEndDateString = "";
864 // Convert the `Dates` to `Strings` if they are not `null`.
865 if (currentWebsiteSslStartDate != null) {
866 currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
869 if (currentWebsiteSslEndDate != null) {
870 currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
873 if (pinnedDomainSslStartDate != null) {
874 pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
877 if (pinnedDomainSslEndDate != null) {
878 pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
881 // Check to see if the pinned SSL certificate matches the current website certificate.
882 if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) || !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) ||
883 !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) || !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
884 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) { // The pinned SSL certificate doesn't match the current domain certificate.
885 //Display the pinned SSL certificate mismatch `AlertDialog`.
886 AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
887 pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
893 // Handle SSL Certificate errors.
895 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
896 // Get the current website SSL certificate.
897 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
899 // Extract the individual pieces of information from the current website SSL certificate.
900 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
901 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
902 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
903 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
904 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
905 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
906 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
907 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
909 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
910 if (pinnedDomainSslCertificate &&
911 currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) && currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) &&
912 currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) && currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
913 currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) { // An SSL certificate is pinned and matches the current domain certificate.
914 // Proceed to the website without displaying an error.
916 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
917 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
918 sslErrorHandler = handler;
920 // Display the SSL error `AlertDialog`.
921 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
922 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
927 // Get a handle for the progress bar.
928 final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress_bar);
930 mainWebView.setWebChromeClient(new WebChromeClient() {
931 // Update the progress bar when a page is loading.
933 public void onProgressChanged(WebView view, int progress) {
934 progressBar.setProgress(progress);
935 if (progress < 100) {
936 progressBar.setVisibility(View.VISIBLE);
938 progressBar.setVisibility(View.GONE);
940 //Stop the `SwipeToRefresh` indicator if it is running
941 swipeRefreshLayout.setRefreshing(false);
945 // Set the favorite icon when it changes.
947 public void onReceivedIcon(WebView view, Bitmap icon) {
948 // Only update the favorite icon if the website has finished loading.
949 if (progressBar.getVisibility() == View.GONE) {
950 // Save a copy of the favorite icon.
951 favoriteIconBitmap = icon;
953 // Place the favorite icon in the appBar.
954 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
958 // Save a copy of the title when it changes.
960 public void onReceivedTitle(WebView view, String title) {
961 // Save a copy of the title.
962 webViewTitle = title;
965 // Enter full screen video
967 public void onShowCustomView(View view, CustomViewCallback callback) {
968 // Pause the ad if this is the free flavor.
969 if (BuildConfig.FLAVOR.contentEquals("free")) {
970 BannerAd.pauseAd(adView);
973 // Remove the translucent overlays.
974 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
976 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
977 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
979 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
980 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
981 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
983 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
985 // Set `rootCoordinatorLayout` to fill the entire screen.
986 rootCoordinatorLayout.setFitsSystemWindows(false);
988 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
989 fullScreenVideoFrameLayout.addView(view);
990 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
993 // Exit full screen video
994 public void onHideCustomView() {
995 // Hide `fullScreenVideoFrameLayout`.
996 fullScreenVideoFrameLayout.removeAllViews();
997 fullScreenVideoFrameLayout.setVisibility(View.GONE);
999 // Add the translucent status flag. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1000 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1002 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars. This also clears the `SYSTEM_UI` flags.
1003 rootCoordinatorLayout.setFitsSystemWindows(true);
1005 // Show the ad if this is the free flavor.
1006 if (BuildConfig.FLAVOR.contentEquals("free")) {
1007 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
1008 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1010 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1011 adView = findViewById(R.id.adview);
1016 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
1017 registerForContextMenu(mainWebView);
1019 // Allow the downloading of files.
1020 mainWebView.setDownloadListener(new DownloadListener() {
1022 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
1023 // Show the `DownloadFileDialog` `AlertDialog` and name this instance `@string/download`.
1024 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
1025 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
1029 // Allow pinch to zoom.
1030 mainWebView.getSettings().setBuiltInZoomControls(true);
1032 // Hide zoom controls.
1033 mainWebView.getSettings().setDisplayZoomControls(false);
1035 // Set `mainWebView` to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
1036 mainWebView.getSettings().setUseWideViewPort(true);
1038 // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
1039 mainWebView.getSettings().setLoadWithOverviewMode(true);
1041 // Explicitly disable geolocation.
1042 mainWebView.getSettings().setGeolocationEnabled(false);
1044 // Initialize cookieManager.
1045 cookieManager = CookieManager.getInstance();
1047 // 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).
1048 customHeaders.put("X-Requested-With", "");
1050 // 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.
1051 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
1053 // Get the intent that started the app.
1054 final Intent launchingIntent = getIntent();
1056 // Extract the launching intent data as `launchingIntentUriData`.
1057 final Uri launchingIntentUriData = launchingIntent.getData();
1059 // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
1060 if (launchingIntentUriData != null) {
1061 formattedUrlString = launchingIntentUriData.toString();
1064 // Get a handle for the `Runtime`.
1065 privacyBrowserRuntime = Runtime.getRuntime();
1067 // Store the application's private data directory.
1068 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`.
1070 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
1071 inFullScreenBrowsingMode = false;
1073 // Initialize AdView for the free flavor.
1074 adView = findViewById(R.id.adview);
1076 // Initialize the privacy settings variables.
1077 javaScriptEnabled = false;
1078 firstPartyCookiesEnabled = false;
1079 thirdPartyCookiesEnabled = false;
1080 domStorageEnabled = false;
1081 saveFormDataEnabled = false;
1083 // Initialize `webViewTitle`.
1084 webViewTitle = getString(R.string.no_title);
1086 // Initialize `favoriteIconBitmap`. We have to use `ContextCompat` until API >= 21.
1087 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
1088 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
1089 favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
1091 // If the favorite icon is null, load the default.
1092 if (favoriteIconBitmap == null) {
1093 favoriteIconBitmap = favoriteIconDefaultBitmap;
1096 // Apply the app settings from the shared preferences.
1099 // Load `formattedUrlString` if we are not waiting for Orbot to connect.
1100 if (!waitingForOrbot) {
1101 loadUrl(formattedUrlString);
1106 protected void onNewIntent(Intent intent) {
1107 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1110 if (intent.getData() != null) {
1111 // Get the intent data and convert it to a string.
1112 final Uri intentUriData = intent.getData();
1113 formattedUrlString = intentUriData.toString();
1116 // Close the navigation drawer if it is open.
1117 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1118 drawerLayout.closeDrawer(GravityCompat.START);
1121 // Load the website.
1122 loadUrl(formattedUrlString);
1124 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1125 mainWebView.requestFocus();
1129 public void onRestart() {
1132 // Apply the app settings, which may have been changed in `SettingsActivity`.
1135 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1136 updatePrivacyIcons(true);
1138 // Set the display webpage images mode.
1139 setDisplayWebpageImages();
1141 // Reload the webpage if displaying of images has been disabled in `SettingsFragment`.
1142 if (reloadOnRestartBoolean) {
1143 // Reload `mainWebView`.
1144 mainWebView.reload();
1146 // Reset `reloadOnRestartBoolean`.
1147 reloadOnRestartBoolean = false;
1151 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1153 public void onResume() {
1156 // Resume JavaScript (if enabled).
1157 mainWebView.resumeTimers();
1159 // Resume `mainWebView`.
1160 mainWebView.onResume();
1162 // Resume the adView for the free flavor.
1163 if (BuildConfig.FLAVOR.contentEquals("free")) {
1164 BannerAd.resumeAd(adView);
1169 public void onPause() {
1170 // Pause `mainWebView`.
1171 mainWebView.onPause();
1173 // Stop all JavaScript.
1174 mainWebView.pauseTimers();
1176 // Pause the adView or it will continue to consume resources in the background on the free flavor.
1177 if (BuildConfig.FLAVOR.contentEquals("free")) {
1178 BannerAd.pauseAd(adView);
1185 public boolean onCreateOptionsMenu(Menu menu) {
1186 // Inflate the menu; this adds items to the action bar if it is present.
1187 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1189 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1192 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1193 updatePrivacyIcons(false);
1195 // Get handles for the menu items.
1196 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1197 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1198 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1199 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1201 // Only display third-party cookies if SDK >= 21
1202 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1204 // Get the shared preference values. `this` references the current context.
1205 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1207 // Set the status of the additional app bar icons. The default is `false`.
1208 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
1209 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1210 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1211 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1212 } else { //Do not display the additional icons.
1213 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1214 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1215 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1222 public boolean onPrepareOptionsMenu(Menu menu) {
1223 // Get handles for the menu items.
1224 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1225 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1226 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1227 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1228 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1229 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1230 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);
1231 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1232 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1233 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1235 // Set the status of the menu item checkboxes.
1236 toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1237 toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1238 toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1239 toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);
1240 displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1242 // Enable third-party cookies if first-party cookies are enabled.
1243 toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1245 // Enable `DOM Storage` if JavaScript is enabled.
1246 toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
1248 // Enable `Clear Cookies` if there are any.
1249 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1251 // Get a count of the number of files in the `Local Storage` directory.
1252 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1253 int localStorageDirectoryNumberOfFiles = 0;
1254 if (localStorageDirectory.exists()) {
1255 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1258 // Get a count of the number of files in the `IndexedDB` directory.
1259 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1260 int indexedDBDirectoryNumberOfFiles = 0;
1261 if (indexedDBDirectory.exists()) {
1262 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1265 // Enable `Clear DOM Storage` if there is any.
1266 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1268 // Enable `Clear Form Data` is there is any.
1269 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1270 clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
1272 // Initialize font size variables.
1273 int fontSize = mainWebView.getSettings().getTextZoom();
1274 String fontSizeTitle;
1275 MenuItem selectedFontSizeMenuItem;
1277 // Prepare the font size title and current size menu item.
1280 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
1281 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1285 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
1286 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1290 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
1291 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1295 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1296 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1300 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
1301 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1305 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
1306 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1310 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
1311 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1315 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
1316 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1320 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1321 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1325 // Set the font size title and select the current size menu item.
1326 fontSizeMenuItem.setTitle(fontSizeTitle);
1327 selectedFontSizeMenuItem.setChecked(true);
1329 // Only show `Refresh` if `swipeToRefresh` is disabled.
1330 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
1332 // Run all the other default commands.
1333 super.onPrepareOptionsMenu(menu);
1335 // `return true` displays the menu.
1340 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1341 @SuppressLint("SetJavaScriptEnabled")
1342 // removeAllCookies is deprecated, but it is required for API < 21.
1343 @SuppressWarnings("deprecation")
1344 public boolean onOptionsItemSelected(MenuItem menuItem) {
1345 int menuItemId = menuItem.getItemId();
1347 // Set the commands that relate to the menu entries.
1348 switch (menuItemId) {
1349 case R.id.toggle_javascript:
1350 // Switch the status of javaScriptEnabled.
1351 javaScriptEnabled = !javaScriptEnabled;
1353 // Apply the new JavaScript status.
1354 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1356 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1357 updatePrivacyIcons(true);
1359 // Display a `Snackbar`.
1360 if (javaScriptEnabled) { // JavaScrip is enabled.
1361 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1362 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
1363 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1364 } else { // Privacy mode.
1365 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1368 // Reload the WebView.
1369 mainWebView.reload();
1372 case R.id.toggle_first_party_cookies:
1373 // Switch the status of firstPartyCookiesEnabled.
1374 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1376 // Update the menu checkbox.
1377 menuItem.setChecked(firstPartyCookiesEnabled);
1379 // Apply the new cookie status.
1380 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1382 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1383 updatePrivacyIcons(true);
1385 // Display a `Snackbar`.
1386 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1387 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1388 } else if (javaScriptEnabled){ // JavaScript is still enabled.
1389 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1390 } else { // Privacy mode.
1391 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1394 // Reload the WebView.
1395 mainWebView.reload();
1398 case R.id.toggle_third_party_cookies:
1399 if (Build.VERSION.SDK_INT >= 21) {
1400 // Switch the status of thirdPartyCookiesEnabled.
1401 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1403 // Update the menu checkbox.
1404 menuItem.setChecked(thirdPartyCookiesEnabled);
1406 // Apply the new cookie status.
1407 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1409 // Display a `Snackbar`.
1410 if (thirdPartyCookiesEnabled) {
1411 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1413 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1416 // Reload the WebView.
1417 mainWebView.reload();
1418 } // Else do nothing because SDK < 21.
1421 case R.id.toggle_dom_storage:
1422 // Switch the status of domStorageEnabled.
1423 domStorageEnabled = !domStorageEnabled;
1425 // Update the menu checkbox.
1426 menuItem.setChecked(domStorageEnabled);
1428 // Apply the new DOM Storage status.
1429 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1431 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1432 updatePrivacyIcons(true);
1434 // Display a `Snackbar`.
1435 if (domStorageEnabled) {
1436 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1438 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1441 // Reload the WebView.
1442 mainWebView.reload();
1445 case R.id.toggle_save_form_data:
1446 // Switch the status of saveFormDataEnabled.
1447 saveFormDataEnabled = !saveFormDataEnabled;
1449 // Update the menu checkbox.
1450 menuItem.setChecked(saveFormDataEnabled);
1452 // Apply the new form data status.
1453 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1455 // Display a `Snackbar`.
1456 if (saveFormDataEnabled) {
1457 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1459 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1462 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1463 updatePrivacyIcons(true);
1465 // Reload the WebView.
1466 mainWebView.reload();
1469 case R.id.clear_cookies:
1470 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1471 .setAction(R.string.undo, new View.OnClickListener() {
1473 public void onClick(View v) {
1474 // Do nothing because everything will be handled by `onDismissed()` below.
1477 .addCallback(new Snackbar.Callback() {
1479 public void onDismissed(Snackbar snackbar, int event) {
1481 // The user pushed the `Undo` button.
1482 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1486 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1488 // `cookieManager.removeAllCookie()` varies by SDK.
1489 if (Build.VERSION.SDK_INT < 21) {
1490 cookieManager.removeAllCookie();
1492 // `null` indicates no callback.
1493 cookieManager.removeAllCookies(null);
1501 case R.id.clear_dom_storage:
1502 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1503 .setAction(R.string.undo, new View.OnClickListener() {
1505 public void onClick(View v) {
1506 // Do nothing because everything will be handled by `onDismissed()` below.
1509 .addCallback(new Snackbar.Callback() {
1511 public void onDismissed(Snackbar snackbar, int event) {
1513 // The user pushed the `Undo` button.
1514 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1518 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1520 // Delete the DOM Storage.
1521 WebStorage webStorage = WebStorage.getInstance();
1522 webStorage.deleteAllData();
1524 // Manually remove `IndexedDB` if it exists.
1526 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1527 } catch (IOException e) {
1528 // Do nothing if an error is thrown.
1536 case R.id.clear_form_data:
1537 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1538 .setAction(R.string.undo, new View.OnClickListener() {
1540 public void onClick(View v) {
1541 // Do nothing because everything will be handled by `onDismissed()` below.
1544 .addCallback(new Snackbar.Callback() {
1546 public void onDismissed(Snackbar snackbar, int event) {
1548 // The user pushed the `Undo` button.
1549 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1553 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1555 // Delete the form data.
1556 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1557 mainWebViewDatabase.clearFormData();
1564 case R.id.font_size_twenty_five_percent:
1565 mainWebView.getSettings().setTextZoom(25);
1568 case R.id.font_size_fifty_percent:
1569 mainWebView.getSettings().setTextZoom(50);
1572 case R.id.font_size_seventy_five_percent:
1573 mainWebView.getSettings().setTextZoom(75);
1576 case R.id.font_size_one_hundred_percent:
1577 mainWebView.getSettings().setTextZoom(100);
1580 case R.id.font_size_one_hundred_twenty_five_percent:
1581 mainWebView.getSettings().setTextZoom(125);
1584 case R.id.font_size_one_hundred_fifty_percent:
1585 mainWebView.getSettings().setTextZoom(150);
1588 case R.id.font_size_one_hundred_seventy_five_percent:
1589 mainWebView.getSettings().setTextZoom(175);
1592 case R.id.font_size_two_hundred_percent:
1593 mainWebView.getSettings().setTextZoom(200);
1596 case R.id.display_images:
1597 if (mainWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1598 mainWebView.getSettings().setLoadsImagesAutomatically(false);
1599 mainWebView.reload();
1600 } else { // Images are not currently loaded automatically.
1601 mainWebView.getSettings().setLoadsImagesAutomatically(true);
1604 // Set `onTheFlyDisplayImagesSet`.
1605 onTheFlyDisplayImagesSet = true;
1609 // Setup the share string.
1610 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
1612 // Create the share intent.
1613 Intent shareIntent = new Intent();
1614 shareIntent.setAction(Intent.ACTION_SEND);
1615 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1616 shareIntent.setType("text/plain");
1619 startActivity(Intent.createChooser(shareIntent, "Share URL"));
1622 case R.id.find_on_page:
1623 // Hide the URL app bar.
1624 supportAppBar.setVisibility(View.GONE);
1626 // Show the Find on Page `RelativeLayout`.
1627 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1629 // 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
1630 findOnPageEditText.postDelayed(new Runnable() {
1634 // Set the focus on `findOnPageEditText`.
1635 findOnPageEditText.requestFocus();
1637 // Display the keyboard. `0` sets no input flags.
1638 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1644 // Get a `PrintManager` instance.
1645 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1647 // Convert `mainWebView` to `printDocumentAdapter`.
1648 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
1650 // Print the document. The print attributes are `null`.
1651 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1654 case R.id.add_to_homescreen:
1655 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
1656 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
1657 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
1659 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
1663 mainWebView.reload();
1667 // Don't consume the event.
1668 return super.onOptionsItemSelected(menuItem);
1672 // removeAllCookies is deprecated, but it is required for API < 21.
1673 @SuppressWarnings("deprecation")
1675 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1676 int menuItemId = menuItem.getItemId();
1678 switch (menuItemId) {
1684 if (mainWebView.canGoBack()) {
1685 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1686 navigatingHistory = true;
1688 // Load the previous website in the history.
1689 mainWebView.goBack();
1694 if (mainWebView.canGoForward()) {
1695 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1696 navigatingHistory = true;
1698 // Load the next website in the history.
1699 mainWebView.goForward();
1704 // Get the `WebBackForwardList`.
1705 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
1707 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
1708 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
1709 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
1712 case R.id.bookmarks:
1713 // Launch BookmarksActivity.
1714 Intent bookmarksIntent = new Intent(this, BookmarksActivity.class);
1715 startActivity(bookmarksIntent);
1718 case R.id.downloads:
1719 // Launch the system Download Manager.
1720 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1722 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1723 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1725 startActivity(downloadManagerIntent);
1729 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1730 currentDomainName = "";
1732 // Launch `SettingsActivity`.
1733 Intent settingsIntent = new Intent(this, SettingsActivity.class);
1734 startActivity(settingsIntent);
1738 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1739 currentDomainName = "";
1741 // Launch `DomainsActivity`.
1742 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1743 startActivity(domainsIntent);
1747 // Launch `GuideActivity`.
1748 Intent guideIntent = new Intent(this, GuideActivity.class);
1749 startActivity(guideIntent);
1753 // Launch `AboutActivity`.
1754 Intent aboutIntent = new Intent(this, AboutActivity.class);
1755 startActivity(aboutIntent);
1758 case R.id.clearAndExit:
1759 // Get a handle for `sharedPreferences`. `this` references the current context.
1760 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1762 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
1765 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
1766 // The command to remove cookies changed slightly in API 21.
1767 if (Build.VERSION.SDK_INT >= 21) {
1768 cookieManager.removeAllCookies(null);
1770 cookieManager.removeAllCookie();
1773 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1775 // We have to use two commands because `Runtime.exec()` does not like `*`.
1776 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
1777 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
1778 } catch (IOException e) {
1779 // Do nothing if an error is thrown.
1783 // Clear DOM storage.
1784 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
1785 // Ask `WebStorage` to clear the DOM storage.
1786 WebStorage webStorage = WebStorage.getInstance();
1787 webStorage.deleteAllData();
1789 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1791 // We have to use a `String[]` because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1792 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1794 // We have to use multiple commands because `Runtime.exec()` does not like `*`.
1795 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1796 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1797 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1798 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1799 } catch (IOException e) {
1800 // Do nothing if an error is thrown.
1805 if (clearEverything || sharedPreferences.getBoolean("clear_form_data", true)) {
1806 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1807 webViewDatabase.clearFormData();
1809 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1811 // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1812 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
1813 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
1814 } catch (IOException e) {
1815 // Do nothing if an error is thrown.
1820 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
1821 // `true` includes disk files.
1822 mainWebView.clearCache(true);
1824 // Manually delete the cache directories.
1826 // Delete the main cache directory.
1827 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1829 // 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.
1830 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1831 } catch (IOException e) {
1832 // Do nothing if an error is thrown.
1836 // Clear SSL certificate preferences.
1837 mainWebView.clearSslPreferences();
1839 // Clear the back/forward history.
1840 mainWebView.clearHistory();
1842 // Clear `formattedUrlString`.
1843 formattedUrlString = null;
1845 // Clear `customHeaders`.
1846 customHeaders.clear();
1848 // Detach all views from `mainWebViewRelativeLayout`.
1849 mainWebViewRelativeLayout.removeAllViews();
1851 // Destroy the internal state of `mainWebView`.
1852 mainWebView.destroy();
1854 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
1855 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
1856 if (clearEverything) {
1858 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
1859 } catch (IOException e) {
1860 // Do nothing if an error is thrown.
1864 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
1865 if (Build.VERSION.SDK_INT >= 21) {
1866 finishAndRemoveTask();
1871 // Remove the terminated program from RAM. The status code is `0`.
1876 // Close the navigation drawer.
1877 drawerLayout.closeDrawer(GravityCompat.START);
1882 public void onPostCreate(Bundle savedInstanceState) {
1883 super.onPostCreate(savedInstanceState);
1885 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
1886 drawerToggle.syncState();
1890 public void onConfigurationChanged(Configuration newConfig) {
1891 super.onConfigurationChanged(newConfig);
1893 // Reload the ad for the free flavor if we are not in full screen mode.
1894 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
1896 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1898 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1899 adView = findViewById(R.id.adview);
1902 // `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
1903 // ActivityCompat.invalidateOptionsMenu(this);
1907 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
1908 // Store the `HitTestResult`.
1909 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
1912 final String imageUrl;
1913 final String linkUrl;
1915 // Get a handle for the `ClipboardManager`.
1916 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
1918 switch (hitTestResult.getType()) {
1919 // `SRC_ANCHOR_TYPE` is a link.
1920 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1921 // Get the target URL.
1922 linkUrl = hitTestResult.getExtra();
1924 // Set the target URL as the title of the `ContextMenu`.
1925 menu.setHeaderTitle(linkUrl);
1927 // Add a `Load URL` entry.
1928 menu.add(R.string.load_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1930 public boolean onMenuItemClick(MenuItem item) {
1936 // Add a `Copy URL` entry.
1937 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1939 public boolean onMenuItemClick(MenuItem item) {
1940 // Save the link URL in a `ClipData`.
1941 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
1943 // Set the `ClipData` as the clipboard's primary clip.
1944 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
1949 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1950 menu.add(R.string.cancel);
1953 case WebView.HitTestResult.EMAIL_TYPE:
1954 // Get the target URL.
1955 linkUrl = hitTestResult.getExtra();
1957 // Set the target URL as the title of the `ContextMenu`.
1958 menu.setHeaderTitle(linkUrl);
1960 // Add a `Write Email` entry.
1961 menu.add(R.string.write_email).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1963 public boolean onMenuItemClick(MenuItem item) {
1964 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1965 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1967 // Parse the url and set it as the data for the `Intent`.
1968 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
1970 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
1971 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1974 startActivity(emailIntent);
1979 // Add a `Copy Email Address` entry.
1980 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1982 public boolean onMenuItemClick(MenuItem item) {
1983 // Save the email address in a `ClipData`.
1984 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
1986 // Set the `ClipData` as the clipboard's primary clip.
1987 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
1992 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1993 menu.add(R.string.cancel);
1996 // `IMAGE_TYPE` is an image.
1997 case WebView.HitTestResult.IMAGE_TYPE:
1998 // Get the image URL.
1999 imageUrl = hitTestResult.getExtra();
2001 // Set the image URL as the title of the `ContextMenu`.
2002 menu.setHeaderTitle(imageUrl);
2004 // Add a `View Image` entry.
2005 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2007 public boolean onMenuItemClick(MenuItem item) {
2013 // Add a `Download Image` entry.
2014 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2016 public boolean onMenuItemClick(MenuItem item) {
2017 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
2018 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2019 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2024 // Add a `Copy URL` entry.
2025 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2027 public boolean onMenuItemClick(MenuItem item) {
2028 // Save the image URL in a `ClipData`.
2029 ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2031 // Set the `ClipData` as the clipboard's primary clip.
2032 clipboardManager.setPrimaryClip(srcImageTypeClipData);
2037 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2038 menu.add(R.string.cancel);
2042 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2043 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2044 // Get the image URL.
2045 imageUrl = hitTestResult.getExtra();
2047 // Set the image URL as the title of the `ContextMenu`.
2048 menu.setHeaderTitle(imageUrl);
2050 // Add a `View Image` entry.
2051 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2053 public boolean onMenuItemClick(MenuItem item) {
2059 // Add a `Download Image` entry.
2060 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2062 public boolean onMenuItemClick(MenuItem item) {
2063 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
2064 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2065 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2070 // Add a `Copy URL` entry.
2071 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2073 public boolean onMenuItemClick(MenuItem item) {
2074 // Save the image URL in a `ClipData`.
2075 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2077 // Set the `ClipData` as the clipboard's primary clip.
2078 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2083 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2084 menu.add(R.string.cancel);
2090 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
2091 // Get shortcutNameEditText from the alert dialog.
2092 EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
2094 // Create the bookmark shortcut based on formattedUrlString.
2095 Intent bookmarkShortcut = new Intent();
2096 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
2097 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
2099 // Place the bookmark shortcut on the home screen.
2100 Intent placeBookmarkShortcut = new Intent();
2101 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
2102 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
2103 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIconBitmap);
2104 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
2105 sendBroadcast(placeBookmarkShortcut);
2109 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
2110 // Download the image if it has an HTTP or HTTPS URI.
2111 if (imageUrl.startsWith("http")) {
2112 // Get a handle for the system `DOWNLOAD_SERVICE`.
2113 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2115 // Parse `imageUrl`.
2116 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
2118 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
2119 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2120 if (firstPartyCookiesEnabled) {
2121 // Get the cookies for `imageUrl`.
2122 String cookies = cookieManager.getCookie(imageUrl);
2124 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2125 downloadRequest.addRequestHeader("Cookie", cookies);
2128 // Get the file name from `dialogFragment`.
2129 EditText downloadImageNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_image_name);
2130 String imageName = downloadImageNameEditText.getText().toString();
2132 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
2133 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `imageName`.
2134 downloadRequest.setDestinationInExternalFilesDir(this, "/", imageName);
2135 } else { // Only set the title using `imageName`.
2136 downloadRequest.setTitle(imageName);
2139 // Allow `MediaScanner` to index the download if it is a media file.
2140 downloadRequest.allowScanningByMediaScanner();
2142 // Add the URL as the description for the download.
2143 downloadRequest.setDescription(imageUrl);
2145 // Show the download notification after the download is completed.
2146 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2148 // Initiate the download.
2149 downloadManager.enqueue(downloadRequest);
2150 } else { // The image is not an HTTP or HTTPS URI.
2151 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
2156 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
2157 // Download the file if it has an HTTP or HTTPS URI.
2158 if (downloadUrl.startsWith("http")) {
2160 // Get a handle for the system `DOWNLOAD_SERVICE`.
2161 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2163 // Parse `downloadUrl`.
2164 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
2166 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
2167 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2168 if (firstPartyCookiesEnabled) {
2169 // Get the cookies for `downloadUrl`.
2170 String cookies = cookieManager.getCookie(downloadUrl);
2172 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2173 downloadRequest.addRequestHeader("Cookie", cookies);
2176 // Get the file name from `dialogFragment`.
2177 EditText downloadFileNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_file_name);
2178 String fileName = downloadFileNameEditText.getText().toString();
2180 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
2181 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download location to `/sdcard/Android/data/com.stoutner.privacybrowser.standard/files` named `fileName`.
2182 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
2183 } else { // Only set the title using `fileName`.
2184 downloadRequest.setTitle(fileName);
2187 // Allow `MediaScanner` to index the download if it is a media file.
2188 downloadRequest.allowScanningByMediaScanner();
2190 // Add the URL as the description for the download.
2191 downloadRequest.setDescription(downloadUrl);
2193 // Show the download notification after the download is completed.
2194 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2196 // Initiate the download.
2197 downloadManager.enqueue(downloadRequest);
2198 } else { // The download is not an HTTP or HTTPS URI.
2199 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
2204 public void onHttpAuthenticationCancel() {
2205 // Cancel the `HttpAuthHandler`.
2206 httpAuthHandler.cancel();
2210 public void onHttpAuthenticationProceed(AppCompatDialogFragment dialogFragment) {
2211 // Get handles for the `EditTexts`.
2212 EditText usernameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.http_authentication_username);
2213 EditText passwordEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.http_authentication_password);
2215 // Proceed with the HTTP authentication.
2216 httpAuthHandler.proceed(usernameEditText.getText().toString(), passwordEditText.getText().toString());
2219 public void viewSslCertificate(View view) {
2220 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
2221 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
2222 viewSslCertificateDialogFragment.show(getFragmentManager(), getString(R.string.view_ssl_certificate));
2226 public void onSslErrorCancel() {
2227 sslErrorHandler.cancel();
2231 public void onSslErrorProceed() {
2232 sslErrorHandler.proceed();
2236 public void onSslMismatchBack() {
2237 if (mainWebView.canGoBack()) { // There is a back page in the history.
2238 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2239 navigatingHistory = true;
2242 mainWebView.goBack();
2243 } else { // There are no pages to go back to.
2244 // Load a blank page
2250 public void onSslMismatchProceed() {
2251 // Do not check the pinned SSL certificate for this domain again until the domain changes.
2252 ignorePinnedSslCertificate = true;
2256 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
2257 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2258 navigatingHistory = true;
2260 // Load the history entry.
2261 mainWebView.goBackOrForward(moveBackOrForwardSteps);
2265 public void onClearHistory() {
2266 // Clear the history.
2267 mainWebView.clearHistory();
2270 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
2272 public void onBackPressed() {
2273 // Close the navigation drawer if it is available. GravityCompat.START is the drawer on the left on Left-to-Right layout text.
2274 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
2275 drawerLayout.closeDrawer(GravityCompat.START);
2277 // Load the previous URL if available.
2278 if (mainWebView.canGoBack()) {
2279 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2280 navigatingHistory = true;
2283 mainWebView.goBack();
2285 // Pass `onBackPressed()` to the system.
2286 super.onBackPressed();
2291 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
2292 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
2293 String unformattedUrlString = urlTextBox.getText().toString().trim();
2295 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
2296 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
2297 // Add `http://` at the beginning if it is missing. Otherwise the app will segfault.
2298 if (!unformattedUrlString.startsWith("http")) {
2299 unformattedUrlString = "http://" + unformattedUrlString;
2302 // Initialize `unformattedUrl`.
2303 URL unformattedUrl = null;
2305 // 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.
2307 unformattedUrl = new URL(unformattedUrlString);
2308 } catch (MalformedURLException e) {
2309 e.printStackTrace();
2312 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2313 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2314 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2315 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2316 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2317 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2320 Uri.Builder formattedUri = new Uri.Builder();
2321 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2323 // Decode `formattedUri` as a `String` in `UTF-8`.
2324 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
2326 // Sanitize the search input and convert it to a search.
2327 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2329 // Add the base search URL.
2330 formattedUrlString = searchURL + encodedUrlString;
2333 loadUrl(formattedUrlString);
2335 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
2336 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2340 private void loadUrl(String url) {
2341 // Apply any custom domain settings.
2342 applyDomainSettings(url);
2345 mainWebView.loadUrl(url, customHeaders);
2347 // Set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
2348 urlIsLoading = true;
2351 public void findPreviousOnPage(View view) {
2352 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
2353 mainWebView.findNext(false);
2356 public void findNextOnPage(View view) {
2357 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2358 mainWebView.findNext(true);
2361 public void closeFindOnPage(View view) {
2362 // Delete the contents of `find_on_page_edittext`.
2363 findOnPageEditText.setText(null);
2365 // Clear the highlighted phrases.
2366 mainWebView.clearMatches();
2368 // Hide the Find on Page `RelativeLayout`.
2369 findOnPageLinearLayout.setVisibility(View.GONE);
2371 // Show the URL app bar.
2372 supportAppBar.setVisibility(View.VISIBLE);
2374 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
2375 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2378 private void applyAppSettings() {
2379 // Get a handle for `sharedPreferences`. `this` references the current context.
2380 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2382 // Store the values from `sharedPreferences` in variables.
2383 String homepageString = sharedPreferences.getString("homepage", "https://start.duckduckgo.com");
2384 String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
2385 String torSearchString = sharedPreferences.getString("tor_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
2386 String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
2387 String searchString = sharedPreferences.getString("search", "https://duckduckgo.com/html/?q=");
2388 String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
2389 adBlockerEnabled = sharedPreferences.getBoolean("block_ads", true);
2390 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
2391 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
2392 boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
2393 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
2394 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
2395 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
2396 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh", false);
2397 displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
2399 // Set the homepage, search, and proxy options.
2400 if (proxyThroughOrbot) { // Set the Tor options.
2401 // Set `torHomepageString` as `homepage`.
2402 homepage = torHomepageString;
2404 // If formattedUrlString is null assign the homepage to it.
2405 if (formattedUrlString == null) {
2406 formattedUrlString = homepage;
2409 // Set the search URL.
2410 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
2411 searchURL = torSearchCustomURLString;
2412 } else { // Use the string from the pre-built list.
2413 searchURL = torSearchString;
2416 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
2417 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
2419 // Set the `appBar` background to indicate proxying through Orbot is enabled. `this` refers to the context.
2421 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
2423 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
2426 // Display a message to the user if we are waiting on Orbot.
2427 if (!orbotStatus.equals("ON")) {
2428 // Set `waitingForOrbot`.
2429 waitingForOrbot = true;
2431 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
2432 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
2434 } else { // Set the non-Tor options.
2435 // Set `homepageString` as `homepage`.
2436 homepage = homepageString;
2438 // If formattedUrlString is null assign the homepage to it.
2439 if (formattedUrlString == null) {
2440 formattedUrlString = homepage;
2443 // Set the search URL.
2444 if (searchString.equals("Custom URL")) { // Get the custom URL string.
2445 searchURL = searchCustomURLString;
2446 } else { // Use the string from the pre-built list.
2447 searchURL = searchString;
2450 // Reset the proxy to default. The host is `""` and the port is `"0"`.
2451 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
2453 // Set the default `appBar` background. `this` refers to the context.
2455 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
2457 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
2460 // Reset `waitingForOrbot.
2461 waitingForOrbot = false;
2464 // Set swipe to refresh.
2465 swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
2467 // Set Do Not Track status.
2468 if (doNotTrackEnabled) {
2469 customHeaders.put("DNT", "1");
2471 customHeaders.remove("DNT");
2474 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
2475 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
2476 if (hideSystemBarsOnFullscreen) { // Hide everything.
2477 // Remove the translucent navigation setting if it is currently flagged.
2478 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2480 // Remove the translucent status bar overlay.
2481 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2483 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
2484 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
2486 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
2487 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
2488 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
2490 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
2491 } else { // Hide everything except the status and navigation bars.
2492 // Add the translucent status flag if it is unset.
2493 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2495 if (translucentNavigationBarOnFullscreen) {
2496 // Set the navigation bar to be translucent.
2497 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2499 // Set the navigation bar to be black.
2500 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2503 } else { // Switch to normal viewing mode.
2504 // Reset `inFullScreenBrowsingMode` to `false`.
2505 inFullScreenBrowsingMode = false;
2507 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
2508 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
2512 // Show the `BannerAd` in the free flavor.
2513 if (BuildConfig.FLAVOR.contentEquals("free")) {
2514 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
2515 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2517 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2518 adView = findViewById(R.id.adview);
2521 // Remove the translucent navigation bar flag if it is set.
2522 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2524 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
2525 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2527 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
2528 rootCoordinatorLayout.setSystemUiVisibility(0);
2530 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
2531 rootCoordinatorLayout.setFitsSystemWindows(true);
2535 // We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2536 @SuppressWarnings("deprecation")
2537 private void applyDomainSettings(String url) {
2538 // Reset `navigatingHistory`.
2539 navigatingHistory = false;
2541 // Parse the URL into a URI.
2542 Uri uri = Uri.parse(url);
2544 // Extract the domain from `uri`.
2545 String hostName = uri.getHost();
2547 // Initialize `loadingNewDomainName`.
2548 boolean loadingNewDomainName;
2550 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
2551 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
2552 //noinspection SimplifiableIfStatement
2553 if ((hostName == null) || (currentDomainName == null)) {
2554 loadingNewDomainName = true;
2555 } else { // Determine if `hostName` equals `currentDomainName`.
2556 loadingNewDomainName = !hostName.equals(currentDomainName);
2559 // 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.
2560 if (loadingNewDomainName) {
2561 // Set the new `hostname` as the `currentDomainName`.
2562 currentDomainName = hostName;
2564 // Reset `ignorePinnedSslCertificate`.
2565 ignorePinnedSslCertificate = false;
2567 // Reset `favoriteIconBitmap` and display it in the `appbar`.
2568 favoriteIconBitmap = favoriteIconDefaultBitmap;
2569 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
2571 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
2572 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2573 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2575 // Get a full cursor from `domainsDatabaseHelper`.
2576 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
2578 // Initialize `domainSettingsSet`.
2579 Set<String> domainSettingsSet = new HashSet<>();
2581 // Get the domain name column index.
2582 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
2584 // Populate `domainSettingsSet`.
2585 for (int i = 0; i < domainNameCursor.getCount(); i++) {
2586 // Move `domainsCursor` to the current row.
2587 domainNameCursor.moveToPosition(i);
2589 // Store the domain name in `domainSettingsSet`.
2590 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
2593 // Close `domainNameCursor.
2594 domainNameCursor.close();
2596 // Initialize variables to track if domain settings will be applied and, if so, under which name.
2597 domainSettingsApplied = false;
2598 String domainNameInDatabase = null;
2600 // Check the hostname.
2601 if (domainSettingsSet.contains(hostName)) {
2602 domainSettingsApplied = true;
2603 domainNameInDatabase = hostName;
2606 // If `hostName` is not `null`, check all the subdomains of `hostName` against wildcard domains in `domainCursor`.
2607 if (hostName != null) {
2608 while (hostName.contains(".") && !domainSettingsApplied) { // Stop checking if we run out of `.` or if we already know that `domainSettingsApplied` is `true`.
2609 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
2610 domainSettingsApplied = true;
2611 domainNameInDatabase = "*." + hostName;
2614 // Strip out the lowest subdomain of `host`.
2615 hostName = hostName.substring(hostName.indexOf(".") + 1);
2619 // Get a handle for the shared preference. `this` references the current context.
2620 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2622 // Store the default font size and user agent information.
2623 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
2624 String defaultUserAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
2625 String defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
2627 if (domainSettingsApplied) { // The url we are loading has custom domain settings.
2628 // Get a cursor for the current host and move it to the first position.
2629 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
2630 currentHostDomainSettingsCursor.moveToFirst();
2632 // Get the settings from the cursor.
2633 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
2634 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
2635 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
2636 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
2637 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
2638 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
2639 String userAgentString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
2640 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
2641 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
2642 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
2643 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
2644 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
2645 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
2646 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
2647 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
2648 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
2650 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
2651 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
2652 pinnedDomainSslStartDate = null;
2654 pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
2657 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
2658 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
2659 pinnedDomainSslEndDate = null;
2661 pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
2664 // Close `currentHostDomainSettingsCursor`.
2665 currentHostDomainSettingsCursor.close();
2667 // Apply the domain settings.
2668 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2669 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2670 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2671 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2673 // Apply the font size.
2674 if (fontSize == 0) { // Apply the default font size.
2675 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
2676 } else { // Apply the specified font size.
2677 mainWebView.getSettings().setTextZoom(fontSize);
2680 // Set third-party cookies status if API >= 21.
2681 if (Build.VERSION.SDK_INT >= 21) {
2682 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2685 // 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>
2686 if (!urlIsLoading) {
2687 switch (userAgentString) {
2688 case "System default user agent":
2689 // Set the user agent according to the system default.
2690 switch (defaultUserAgentString) {
2691 case "WebView default user agent":
2692 // Set the user agent to `""`, which uses the default value.
2693 mainWebView.getSettings().setUserAgentString("");
2696 case "Custom user agent":
2697 // Set the custom user agent.
2698 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
2702 // Use the selected user agent.
2703 mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
2707 case "WebView default user agent":
2708 // Set the user agent to `""`, which uses the default value.
2709 mainWebView.getSettings().setUserAgentString("");
2713 // Use the selected user agent.
2714 mainWebView.getSettings().setUserAgentString(userAgentString);
2718 // 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.
2720 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
2722 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
2724 } else { // The URL we are loading does not have custom domain settings. Load the defaults.
2725 // Store the values from `sharedPreferences` in variables.
2726 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
2727 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
2728 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
2729 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
2730 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
2732 // Apply the default settings.
2733 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2734 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2735 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2736 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2737 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
2739 // Reset the pinned SSL certificate information.
2740 domainSettingsDatabaseId = -1;
2741 pinnedDomainSslCertificate = false;
2742 pinnedDomainSslIssuedToCNameString = "";
2743 pinnedDomainSslIssuedToONameString = "";
2744 pinnedDomainSslIssuedToUNameString = "";
2745 pinnedDomainSslIssuedByCNameString = "";
2746 pinnedDomainSslIssuedByONameString = "";
2747 pinnedDomainSslIssuedByUNameString = "";
2748 pinnedDomainSslStartDate = null;
2749 pinnedDomainSslEndDate = null;
2751 // Set third-party cookies status if API >= 21.
2752 if (Build.VERSION.SDK_INT >= 21) {
2753 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2756 // 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>
2757 if (!urlIsLoading) {
2758 switch (defaultUserAgentString) {
2759 case "WebView default user agent":
2760 // Set the user agent to `""`, which uses the default value.
2761 mainWebView.getSettings().setUserAgentString("");
2764 case "Custom user agent":
2765 // Set the custom user agent.
2766 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
2770 // Use the selected user agent.
2771 mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
2775 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2776 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
2779 // Close `domainsDatabaseHelper`.
2780 domainsDatabaseHelper.close();
2782 // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode. `true` indicates that custom domain settings are applied.
2783 onTheFlyDisplayImagesSet = false;
2784 setDisplayWebpageImages();
2786 // Update the privacy icons, but only if `mainMenu` has already been populated.
2787 if (mainMenu != null) {
2788 updatePrivacyIcons(true);
2793 private void setDisplayWebpageImages() {
2794 if (!onTheFlyDisplayImagesSet) {
2795 if (domainSettingsApplied) { // Custom domain settings are applied.
2796 switch (displayWebpageImagesInt) {
2797 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
2798 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
2801 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
2802 mainWebView.getSettings().setLoadsImagesAutomatically(true);
2805 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
2806 mainWebView.getSettings().setLoadsImagesAutomatically(false);
2809 } else { // Default settings are applied.
2810 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
2815 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
2816 // Get handles for the icons.
2817 MenuItem privacyIconMenuItem = mainMenu.findItem(R.id.toggle_javascript);
2818 MenuItem firstPartyCookiesIconMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
2819 MenuItem domStorageIconMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
2820 MenuItem formDataIconMenuItem = mainMenu.findItem(R.id.toggle_save_form_data);
2822 // Update `privacyIcon`.
2823 if (javaScriptEnabled) { // JavaScript is enabled.
2824 privacyIconMenuItem.setIcon(R.drawable.javascript_enabled);
2825 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
2826 privacyIconMenuItem.setIcon(R.drawable.warning);
2827 } else { // All the dangerous features are disabled.
2828 privacyIconMenuItem.setIcon(R.drawable.privacy_mode);
2831 // Update `firstPartyCookiesIcon`.
2832 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
2833 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_enabled);
2834 } else { // First-party cookies are disabled.
2836 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_dark);
2838 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_light);
2842 // Update `domStorageIcon`.
2843 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
2844 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_enabled);
2845 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
2847 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
2849 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
2851 } else { // JavaScript is disabled, so DOM storage is ghosted.
2853 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
2855 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
2859 // Update `formDataIcon`.
2860 if (saveFormDataEnabled) { // Form data is enabled.
2861 formDataIconMenuItem.setIcon(R.drawable.form_data_enabled);
2862 } else { // Form data is disabled.
2864 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_dark);
2866 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_light);
2870 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`. `this` references the current activity.
2871 if (runInvalidateOptionsMenu) {
2872 ActivityCompat.invalidateOptionsMenu(this);
2876 private void highlightUrlText() {
2877 String urlString = urlTextBox.getText().toString();
2879 if (urlString.startsWith("http://")) { // Highlight connections that are not encrypted.
2880 urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
2881 } else if (urlString.startsWith("https://")) { // Highlight connections that are encrypted.
2882 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
2885 // Get the index of the `/` immediately after the domain name.
2886 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
2888 // De-emphasize the text after the domain name.
2889 if (endOfDomainName > 0) {
2890 urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);