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.SslErrorHandler;
78 import android.webkit.WebBackForwardList;
79 import android.webkit.WebChromeClient;
80 import android.webkit.WebResourceResponse;
81 import android.webkit.WebStorage;
82 import android.webkit.WebView;
83 import android.webkit.WebViewClient;
84 import android.webkit.WebViewDatabase;
85 import android.widget.EditText;
86 import android.widget.FrameLayout;
87 import android.widget.ImageView;
88 import android.widget.LinearLayout;
89 import android.widget.ProgressBar;
90 import android.widget.RelativeLayout;
91 import android.widget.TextView;
93 import com.stoutner.privacybrowser.BannerAd;
94 import com.stoutner.privacybrowser.BuildConfig;
95 import com.stoutner.privacybrowser.R;
96 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
97 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
98 import com.stoutner.privacybrowser.dialogs.PinnedSslCertificateMismatchDialog;
99 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
100 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
101 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
102 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
103 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
104 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
106 import java.io.BufferedReader;
107 import java.io.ByteArrayInputStream;
109 import java.io.IOException;
110 import java.io.InputStreamReader;
111 import java.io.UnsupportedEncodingException;
112 import java.net.MalformedURLException;
114 import java.net.URLDecoder;
115 import java.net.URLEncoder;
116 import java.util.Date;
117 import java.util.HashMap;
118 import java.util.HashSet;
119 import java.util.Map;
120 import java.util.Set;
122 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
123 public class MainWebViewActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, CreateHomeScreenShortcutDialog.CreateHomeScreenSchortcutListener,
124 PinnedSslCertificateMismatchDialog.PinnedSslCertificateMismatchListener, SslCertificateErrorDialog.SslCertificateErrorListener, DownloadFileDialog.DownloadFileListener, DownloadImageDialog.DownloadImageListener, UrlHistoryDialog.UrlHistoryListener {
126 // `darkTheme` is public static so it can be accessed from `AboutActivity`, `GuideActivity`, `AddDomainDialog`, `SettingsActivity`, `DomainsActivity`, `DomainsListFragment`, `BookmarksActivity`, `BookmarksDatabaseViewActivity`,
127 // `CreateBookmarkDialog`, `CreateBookmarkFolderDialog`, `DownloadFileDialog`, `DownloadImageDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`, `MoveToFolderDialog`, `SslCertificateErrorDialog`, `UrlHistoryDialog`, `ViewSslCertificateDialog`,
128 // `CreateHomeScreenShortcutDialog`, and `OrbotProxyHelper`. It is also used in `onCreate()`, `applyAppSettings()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
129 public static boolean darkTheme;
131 // `favoriteIconBitmap` is public static so it can be accessed from `CreateHomeScreenShortcutDialog`, `BookmarksActivity`, `CreateBookmarkDialog`, `CreateBookmarkFolderDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`,
132 // and `ViewSslCertificateDialog`. It is also used in `onCreate()`, `onCreateHomeScreenShortcutCreate()`, and `applyDomainSettings`.
133 public static Bitmap favoriteIconBitmap;
135 // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`, `CreateBookmarkDialog`, and `AddDomainDialog`.
136 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
137 public static String formattedUrlString;
139 // `sslCertificate` is public static so it can be accessed from `DomainsActivity`, `DomainsListFragment`, `DomainSettingsFragment`, `PinnedSslCertificateMismatchDialog`, and `ViewSslCertificateDialog`. It is also used in `onCreate()`.
140 public static SslCertificate sslCertificate;
142 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`.
143 public static String orbotStatus;
145 // `webViewTitle` is public static so it can be accessed from `CreateBookmarkDialog` and `CreateHomeScreenShortcutDialog`. It is also used in `onCreate()`.
146 public static String webViewTitle;
148 // `displayWebpageImagesBoolean` is public static so it can be accessed from `DomainSettingsFragment`. It is also used in `applyAppSettings()` and `applyDomainSettings()`.
149 public static boolean displayWebpageImagesBoolean;
151 // `reloadOnRestartBoolean` is public static so it can be accessed from `SettingsFragment`. It is also used in `onRestart()`
152 public static boolean reloadOnRestartBoolean;
154 // The pinned domain SSL Certificate variables are public static so they can be accessed from `PinnedSslCertificateMismatchDialog`. They are also used in `onCreate()` and `applyDomainSettings()`.
155 public static int domainSettingsDatabaseId;
156 public static boolean pinnedDomainSslCertificate;
157 public static String pinnedDomainSslIssuedToCNameString;
158 public static String pinnedDomainSslIssuedToONameString;
159 public static String pinnedDomainSslIssuedToUNameString;
160 public static String pinnedDomainSslIssuedByCNameString;
161 public static String pinnedDomainSslIssuedByONameString;
162 public static String pinnedDomainSslIssuedByUNameString;
163 public static Date pinnedDomainSslStartDate;
164 public static Date pinnedDomainSslEndDate;
167 // `appBar` is used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applyAppSettings()`.
168 private ActionBar appBar;
170 // `navigatingHistory` is used in `onCreate()`, `onNavigationItemSelected()`, `onSslMismatchBack()`, and `applyDomainSettings()`.
171 private boolean navigatingHistory;
173 // `favoriteIconDefaultBitmap` is used in `onCreate()` and `applyDomainSettings`.
174 private Bitmap favoriteIconDefaultBitmap;
176 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, and `onBackPressed()`.
177 private DrawerLayout drawerLayout;
179 // `rootCoordinatorLayout` is used in `onCreate()` and `applyAppSettings()`.
180 private CoordinatorLayout rootCoordinatorLayout;
182 // `mainWebView` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`, `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`
183 // `onSslMismatchBack()`, and `setDisplayWebpageImages()`.
184 private WebView mainWebView;
186 // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
187 private FrameLayout fullScreenVideoFrameLayout;
189 // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu`, and `onRestart()`.
190 private SwipeRefreshLayout swipeRefreshLayout;
192 // `urlAppBarRelativeLayout` is used in `onCreate()` and `applyDomainSettings()`.
193 private RelativeLayout urlAppBarRelativeLayout;
195 // `favoriteIconImageView` is used in `onCreate()` and `applyDomainSettings()`
196 private ImageView favoriteIconImageView;
198 // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `loadUrlFromTextBox()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
199 private CookieManager cookieManager;
201 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
202 private final Map<String, String> customHeaders = new HashMap<>();
204 // `javaScriptEnabled` is also used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `applyAppSettings()`.
205 // It is `Boolean` instead of `boolean` because `applyAppSettings()` needs to know if it is `null`.
206 private Boolean javaScriptEnabled;
208 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applyAppSettings()`.
209 private boolean firstPartyCookiesEnabled;
211 // `thirdPartyCookiesEnabled` used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
212 private boolean thirdPartyCookiesEnabled;
214 // `domStorageEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
215 private boolean domStorageEnabled;
217 // `saveFormDataEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
218 private boolean saveFormDataEnabled;
220 // `swipeToRefreshEnabled` is used in `onPrepareOptionsMenu()` and `applyAppSettings()`.
221 private boolean swipeToRefreshEnabled;
223 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applyAppSettings()`.
224 private String homepage;
226 // `searchURL` is used in `loadURLFromTextBox()` and `applyAppSettings()`.
227 private String searchURL;
229 // `adBlockerEnabled` is used in `onCreate()` and `applyAppSettings()`.
230 private boolean adBlockerEnabled;
232 // `privacyBrowserRuntime` is used in `onCreate()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
233 private Runtime privacyBrowserRuntime;
235 // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
236 private boolean incognitoModeEnabled;
238 // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
239 private boolean fullScreenBrowsingModeEnabled;
241 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
242 private boolean inFullScreenBrowsingMode;
244 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
245 private boolean hideSystemBarsOnFullscreen;
247 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
248 private boolean translucentNavigationBarOnFullscreen;
250 // `currentDomainName` is used in `onCreate()`, `onNavigationItemSelected()`, `onSslMismatchProceed()`, and `applyDomainSettings()`.
251 private String currentDomainName;
253 // `ignorePinnedSslCertificateForDomain` is used in `onCreate()`, `onSslMismatchProceed()`, and `applyDomainSettings()`.
254 private boolean ignorePinnedSslCertificate;
256 // `waitingForOrbot` is used in `onCreate()` and `applyAppSettings()`.
257 private boolean waitingForOrbot;
259 // `domainSettingsApplied` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
260 private boolean domainSettingsApplied;
262 // `displayWebpageImagesInt` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
263 private int displayWebpageImagesInt;
265 // `onTheFlyDisplayImagesSet` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
266 private boolean onTheFlyDisplayImagesSet;
268 // `waitingForOrbotData` is used in `onCreate()` and `applyAppSettings()`.
269 private String waitingForOrbotHTMLString;
271 // `privateDataDirectoryString` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
272 private String privateDataDirectoryString;
274 // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
275 private LinearLayout findOnPageLinearLayout;
277 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
278 private EditText findOnPageEditText;
280 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
281 private Menu mainMenu;
283 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
284 private ActionBarDrawerToggle drawerToggle;
286 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
287 private Toolbar supportAppBar;
289 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, `loadUrl()`, and `highlightUrlText()`.
290 private EditText urlTextBox;
292 // `redColorSpan` is used in `onCreate()` and `highlightUrlText()`.
293 private ForegroundColorSpan redColorSpan;
295 // `initialGrayColorSpan` is sued in `onCreate()` and `highlightUrlText()`.
296 private ForegroundColorSpan initialGrayColorSpan;
298 // `finalGrayColorSpam` is used in `onCreate()` and `highlightUrlText()`.
299 private ForegroundColorSpan finalGrayColorSpan;
301 // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
304 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
305 private SslErrorHandler sslErrorHandler;
307 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
308 private InputMethodManager inputMethodManager;
310 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
311 private RelativeLayout mainWebViewRelativeLayout;
313 // `urlIsLoading` is used in `onCreate()`, `loadUrl()`, and `applyDomainSettings()`.
314 private boolean urlIsLoading;
318 // 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.
319 @SuppressLint("SetJavaScriptEnabled")
320 // Remove Android Studio's warning about deprecations. We have to use the deprecated `getColor()` until API >= 23.
321 @SuppressWarnings("deprecation")
322 protected void onCreate(Bundle savedInstanceState) {
323 // Get a handle for `sharedPreferences`. `this` references the current context.
324 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
326 // Get the theme preference.
327 darkTheme = sharedPreferences.getBoolean("dark_theme", false);
329 // Set the activity theme.
331 setTheme(R.style.PrivacyBrowserDark);
333 setTheme(R.style.PrivacyBrowserLight);
336 // Run the default commands.
337 super.onCreate(savedInstanceState);
339 // Set the content view.
340 setContentView(R.layout.main_drawerlayout);
342 // Get a handle for `inputMethodManager`.
343 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
345 // We need to use the `SupportActionBar` from `android.support.v7.app.ActionBar` until the minimum API is >= 21.
346 supportAppBar = (Toolbar) findViewById(R.id.app_bar);
347 setSupportActionBar(supportAppBar);
348 appBar = getSupportActionBar();
350 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
351 assert appBar != null;
353 // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
354 appBar.setCustomView(R.layout.url_app_bar);
355 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
357 // Initialize the `ForegroundColorSpans` and `StyleSpan` for highlighting `urlTextBox`. We have to use the deprecated `getColor()` until API >= 23.
358 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
359 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
360 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
362 // Get a handle for `urlTextBox`.
363 urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.url_edittext);
365 // Remove the formatting from `urlTextBar` when the user is editing the text.
366 urlTextBox.setOnFocusChangeListener(new View.OnFocusChangeListener() {
368 public void onFocusChange(View v, boolean hasFocus) {
369 if (hasFocus) { // The user is editing `urlTextBox`.
370 // Remove the highlighting.
371 urlTextBox.getText().removeSpan(redColorSpan);
372 urlTextBox.getText().removeSpan(initialGrayColorSpan);
373 urlTextBox.getText().removeSpan(finalGrayColorSpan);
374 } else { // The user has stopped editing `urlTextBox`.
375 // Reapply the highlighting.
381 // Set the `Go` button on the keyboard to load the URL in `urlTextBox`.
382 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
384 public boolean onKey(View v, int keyCode, KeyEvent event) {
385 // If the event is a key-down event on the `enter` button, load the URL.
386 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
387 // Load the URL into the mainWebView and consume the event.
389 loadUrlFromTextBox();
390 } catch (UnsupportedEncodingException e) {
393 // If the enter key was pressed, consume the event.
396 // If any other key was pressed, do not consume the event.
402 // Set `waitingForOrbotHTMLString`.
403 waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
405 // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
406 currentDomainName = "";
407 orbotStatus = "unknown";
408 waitingForOrbot = false;
410 // Create an Orbot status `BroadcastReceiver`.
411 BroadcastReceiver orbotStatusBroadcastReceiver = new BroadcastReceiver() {
413 public void onReceive(Context context, Intent intent) {
414 // Store the content of the status message in `orbotStatus`.
415 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
417 // If we are waiting on Orbot, load the website now that Orbot is connected.
418 if (orbotStatus.equals("ON") && waitingForOrbot) {
419 // Reset `waitingForOrbot`.
420 waitingForOrbot = false;
422 // Load `formattedUrlString
423 loadUrl(formattedUrlString);
428 // Register `orbotStatusBroadcastReceiver` on `this` context.
429 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
431 // Get handles for views that need to be accessed.
432 drawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout);
433 rootCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.root_coordinatorlayout);
434 mainWebViewRelativeLayout = (RelativeLayout) findViewById(R.id.main_webview_relativelayout);
435 mainWebView = (WebView) findViewById(R.id.main_webview);
436 findOnPageLinearLayout = (LinearLayout) findViewById(R.id.find_on_page_linearlayout);
437 findOnPageEditText = (EditText) findViewById(R.id.find_on_page_edittext);
438 fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.full_screen_video_framelayout);
439 urlAppBarRelativeLayout = (RelativeLayout) findViewById(R.id.url_app_bar_relativelayout);
440 favoriteIconImageView = (ImageView) findViewById(R.id.favorite_icon);
442 // Create a double-tap listener to toggle full-screen mode.
443 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
444 // Override `onDoubleTap()`. All other events are handled using the default settings.
446 public boolean onDoubleTap(MotionEvent event) {
447 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
448 // Toggle `inFullScreenBrowsingMode`.
449 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
451 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
452 // Hide the `appBar`.
455 // Hide the `BannerAd` in the free flavor.
456 if (BuildConfig.FLAVOR.contentEquals("free")) {
457 BannerAd.hideAd(adView);
460 // Modify the system bars.
461 if (hideSystemBarsOnFullscreen) { // Hide everything.
462 // Remove the translucent overlays.
463 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
465 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
466 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
468 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
469 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
470 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
472 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
474 // Set `rootCoordinatorLayout` to fill the whole screen.
475 rootCoordinatorLayout.setFitsSystemWindows(false);
476 } else { // Hide everything except the status and navigation bars.
477 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
478 rootCoordinatorLayout.setFitsSystemWindows(false);
480 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.
481 // Set the navigation bar to be translucent.
482 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
485 } else { // Switch to normal viewing mode.
486 // Show the `appBar`.
489 // Show the `BannerAd` in the free flavor.
490 if (BuildConfig.FLAVOR.contentEquals("free")) {
491 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
492 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
494 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
495 adView = findViewById(R.id.adview);
498 // Remove the translucent navigation bar flag if it is set.
499 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
501 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
502 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
504 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
505 rootCoordinatorLayout.setSystemUiVisibility(0);
507 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
508 rootCoordinatorLayout.setFitsSystemWindows(true);
511 // Consume the double-tap.
513 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
519 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
520 mainWebView.setOnTouchListener(new View.OnTouchListener() {
522 public boolean onTouch(View v, MotionEvent event) {
523 // Send the `event` to `gestureDetector`.
524 return gestureDetector.onTouchEvent(event);
528 // Update `findOnPageCountTextView`.
529 mainWebView.setFindListener(new WebView.FindListener() {
530 // Get a handle for `findOnPageCountTextView`.
531 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
534 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
535 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
536 // Set `findOnPageCountTextView` to `0/0`.
537 findOnPageCountTextView.setText(R.string.zero_of_zero);
538 } else if (isDoneCounting) { // There are matches.
539 // `activeMatchOrdinal` is zero-based.
540 int activeMatch = activeMatchOrdinal + 1;
542 // Set `findOnPageCountTextView`.
543 findOnPageCountTextView.setText(activeMatch + "/" + numberOfMatches);
548 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
549 findOnPageEditText.addTextChangedListener(new TextWatcher() {
551 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
556 public void onTextChanged(CharSequence s, int start, int before, int count) {
561 public void afterTextChanged(Editable s) {
562 // Search for the text in `mainWebView`.
563 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
567 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
568 findOnPageEditText.setOnKeyListener(new View.OnKeyListener() {
570 public boolean onKey(View v, int keyCode, KeyEvent event) {
571 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
572 // Hide the soft keyboard. `0` indicates no additional flags.
573 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
575 // Consume the event.
577 } else { // A different key was pressed.
578 // Do not consume the event.
584 // Implement swipe to refresh
585 swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refreshlayout);
586 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
587 swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
589 public void onRefresh() {
590 mainWebView.reload();
594 // `DrawerTitle` identifies the `DrawerLayout` in accessibility mode.
595 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
597 // Listen for touches on the navigation menu.
598 final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationview);
599 navigationView.setNavigationItemSelectedListener(this);
601 // 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.
602 final Menu navigationMenu = navigationView.getMenu();
603 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
604 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
605 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
607 // The `DrawerListener` allows us to update the Navigation Menu.
608 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
610 public void onDrawerSlide(View drawerView, float slideOffset) {
614 public void onDrawerOpened(View drawerView) {
618 public void onDrawerClosed(View drawerView) {
622 public void onDrawerStateChanged(int newState) {
623 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // The drawer is opening or closing.
624 // Update the `Back`, `Forward`, and `History` menu items.
625 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
626 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
627 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
629 // Hide the keyboard (if displayed) so we can see the navigation menu. `0` indicates no additional flags.
630 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
632 // Clear the focus from `urlTextBox` if it has it.
633 urlTextBox.clearFocus();
638 // drawerToggle creates the hamburger icon at the start of the AppBar.
639 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
641 // Initialize `adServerSet`.
642 final Set<String> adServersSet = new HashSet<>();
644 // Load the list of ad servers into memory.
646 // Load `pgl.yoyo.org_adservers.txt` into a `BufferedReader`.
647 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(getAssets().open("pgl.yoyo.org_adservers.txt")));
649 // Create a string for storing each ad server.
652 // Populate `adServersSet`.
653 while ((adServer = bufferedReader.readLine()) != null) {
654 adServersSet.add(adServer);
657 // Close `bufferedReader`.
658 bufferedReader.close();
659 } catch (IOException ioException) {
660 // We're pretty sure the asset exists, so we don't need to worry about the `IOException` ever being thrown.
663 mainWebView.setWebViewClient(new WebViewClient() {
664 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
665 // We have to use the deprecated `shouldOverrideUrlLoading` until API >= 24.
666 @SuppressWarnings("deprecation")
668 public boolean shouldOverrideUrlLoading(WebView view, String url) {
669 if (url.startsWith("mailto:")) { // Load the URL in an external email program because it begins with `mailto:`.
670 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
671 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
673 // Parse the url and set it as the data for the `Intent`.
674 emailIntent.setData(Uri.parse(url));
676 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
677 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
680 startActivity(emailIntent);
682 // Returning `true` indicates the application is handling the URL.
684 } else { // Load the URL in Privacy Browser.
685 // Apply the domain settings for the new URL.
686 applyDomainSettings(url);
688 // Returning `false` causes the current `WebView` to handle the URL and prevents it from adding redirects to the history list.
693 // Block ads. We have to use the deprecated `shouldInterceptRequest` until minimum API >= 21.
694 @SuppressWarnings("deprecation")
696 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
697 if (adBlockerEnabled) { // Block ads.
698 // Extract the host from `url`.
699 Uri requestUri = Uri.parse(url);
700 String requestHost = requestUri.getHost();
702 // Initialize a variable to track if this is an ad server.
703 boolean requestHostIsAdServer = false;
705 // Check all the subdomains of `requestHost` if it is not `null` against the ad server database.
706 if (requestHost != null) {
707 while (requestHost.contains(".") && !requestHostIsAdServer) { // Stop checking if we run out of `.` or if we already know that `requestHostIsAdServer` is `true`.
708 if (adServersSet.contains(requestHost)) {
709 requestHostIsAdServer = true;
712 // Strip out the lowest subdomain of `requestHost`.
713 requestHost = requestHost.substring(requestHost.indexOf(".") + 1);
717 if (requestHostIsAdServer) { // It is an ad server.
718 // Return an empty `WebResourceResponse`.
719 return new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
720 } else { // It is not an ad server.
721 // `return null` loads the requested resource.
724 } else { // Ad blocking is disabled.
725 // `return null` loads the requested resource.
730 // Update the URL in urlTextBox when the page starts to load.
732 public void onPageStarted(WebView view, String url, Bitmap favicon) {
733 // Check to see if we are waiting on Orbot.
734 if (!waitingForOrbot) { // We are not waiting on Orbot, so we need to process the URL.
735 // 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.
736 formattedUrlString = url;
738 // Display the formatted URL text.
739 urlTextBox.setText(formattedUrlString);
741 // Apply text highlighting to `urlTextBox`.
744 // Apply any custom domain settings if the URL was loaded by navigating history.
745 if (navigatingHistory) {
746 applyDomainSettings(url);
749 // 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.
754 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
756 public void onPageFinished(WebView view, String url) {
757 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
758 urlIsLoading = false;
760 // Clear the cache and history if Incognito Mode is enabled.
761 if (incognitoModeEnabled) {
762 // Clear the cache. `true` includes disk files.
763 mainWebView.clearCache(true);
765 // Clear the back/forward history.
766 mainWebView.clearHistory();
768 // Manually delete cache folders.
770 // Delete the main `cache` folder.
771 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
773 // 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`.
774 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
775 } catch (IOException e) {
776 // Do nothing if an error is thrown.
780 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
781 if (!waitingForOrbot) {
782 // Check to see if `WebView` has set `url` to be `about:blank`.
783 if (url.equals("about:blank")) { // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
784 // Set `formattedUrlString` to `""`.
785 formattedUrlString = "";
787 urlTextBox.setText(formattedUrlString);
789 // Request focus for `urlTextBox`.
790 urlTextBox.requestFocus();
792 // Display the keyboard.
793 inputMethodManager.showSoftInput(urlTextBox, 0);
795 // Apply the domain settings. This clears any settings from the previous domain.
796 applyDomainSettings(formattedUrlString);
797 } else { // `WebView` has loaded a webpage.
798 // Set `formattedUrlString`.
799 formattedUrlString = url;
801 // Only update `urlTextBox` if the user is not typing in it.
802 if (!urlTextBox.hasFocus()) {
803 // Display the formatted URL text.
804 urlTextBox.setText(formattedUrlString);
806 // Apply text highlighting to `urlTextBox`.
811 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
812 sslCertificate = mainWebView.getCertificate();
814 // 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.
815 if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate) {
816 // Initialize the current SSL certificate variables.
817 String currentWebsiteIssuedToCName = "";
818 String currentWebsiteIssuedToOName = "";
819 String currentWebsiteIssuedToUName = "";
820 String currentWebsiteIssuedByCName = "";
821 String currentWebsiteIssuedByOName = "";
822 String currentWebsiteIssuedByUName = "";
823 Date currentWebsiteSslStartDate = null;
824 Date currentWebsiteSslEndDate = null;
827 // Extract the individual pieces of information from the current website SSL certificate if it is not null.
828 if (sslCertificate != null) {
829 currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
830 currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
831 currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
832 currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
833 currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
834 currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
835 currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
836 currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
839 // 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`.
840 String currentWebsiteSslStartDateString = "";
841 String currentWebsiteSslEndDateString = "";
842 String pinnedDomainSslStartDateString = "";
843 String pinnedDomainSslEndDateString = "";
845 // Convert the `Dates` to `Strings` if they are not `null`.
846 if (currentWebsiteSslStartDate != null) {
847 currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
850 if (currentWebsiteSslEndDate != null) {
851 currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
854 if (pinnedDomainSslStartDate != null) {
855 pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
858 if (pinnedDomainSslEndDate != null) {
859 pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
862 // Check to see if the pinned SSL certificate matches the current website certificate.
863 if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) || !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) ||
864 !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) || !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
865 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) { // The pinned SSL certificate doesn't match the current domain certificate.
866 //Display the pinned SSL certificate mismatch `AlertDialog`.
867 AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
868 pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.ssl_certificate_mismatch));
874 // Handle SSL Certificate errors.
876 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
877 // Get the current website SSL certificate.
878 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
880 // Extract the individual pieces of information from the current website SSL certificate.
881 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
882 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
883 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
884 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
885 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
886 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
887 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
888 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
890 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
891 if (pinnedDomainSslCertificate &&
892 currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) && currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) &&
893 currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) && currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
894 currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) { // An SSL certificate is pinned and matches the current domain certificate.
895 // Proceed to the website without displaying an error.
897 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
898 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
899 sslErrorHandler = handler;
901 // Display the SSL error `AlertDialog`.
902 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
903 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.ssl_certificate_error));
908 // Get a handle for the progress bar.
909 final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress_bar);
911 mainWebView.setWebChromeClient(new WebChromeClient() {
912 // Update the progress bar when a page is loading.
914 public void onProgressChanged(WebView view, int progress) {
915 progressBar.setProgress(progress);
916 if (progress < 100) {
917 progressBar.setVisibility(View.VISIBLE);
919 progressBar.setVisibility(View.GONE);
921 //Stop the `SwipeToRefresh` indicator if it is running
922 swipeRefreshLayout.setRefreshing(false);
926 // Set the favorite icon when it changes.
928 public void onReceivedIcon(WebView view, Bitmap icon) {
929 // Only update the favorite icon if the website has finished loading.
930 if (progressBar.getVisibility() == View.GONE) {
931 // Save a copy of the favorite icon.
932 favoriteIconBitmap = icon;
934 // Place the favorite icon in the appBar.
935 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
939 // Save a copy of the title when it changes.
941 public void onReceivedTitle(WebView view, String title) {
942 // Save a copy of the title.
943 webViewTitle = title;
946 // Enter full screen video
948 public void onShowCustomView(View view, CustomViewCallback callback) {
949 // Pause the ad if this is the free flavor.
950 if (BuildConfig.FLAVOR.contentEquals("free")) {
951 BannerAd.pauseAd(adView);
954 // Remove the translucent overlays.
955 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
957 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
958 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
960 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
961 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
962 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
964 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
966 // Set `rootCoordinatorLayout` to fill the entire screen.
967 rootCoordinatorLayout.setFitsSystemWindows(false);
969 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
970 fullScreenVideoFrameLayout.addView(view);
971 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
974 // Exit full screen video
975 public void onHideCustomView() {
976 // Hide `fullScreenVideoFrameLayout`.
977 fullScreenVideoFrameLayout.removeAllViews();
978 fullScreenVideoFrameLayout.setVisibility(View.GONE);
980 // Add the translucent status flag. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
981 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
983 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars. This also clears the `SYSTEM_UI` flags.
984 rootCoordinatorLayout.setFitsSystemWindows(true);
986 // Show the ad if this is the free flavor.
987 if (BuildConfig.FLAVOR.contentEquals("free")) {
988 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
989 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
991 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
992 adView = findViewById(R.id.adview);
997 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
998 registerForContextMenu(mainWebView);
1000 // Allow the downloading of files.
1001 mainWebView.setDownloadListener(new DownloadListener() {
1003 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
1004 // Show the `DownloadFileDialog` `AlertDialog` and name this instance `@string/download`.
1005 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
1006 downloadFileDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1010 // Allow pinch to zoom.
1011 mainWebView.getSettings().setBuiltInZoomControls(true);
1013 // Hide zoom controls.
1014 mainWebView.getSettings().setDisplayZoomControls(false);
1016 // Set `mainWebView` to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
1017 mainWebView.getSettings().setUseWideViewPort(true);
1019 // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
1020 mainWebView.getSettings().setLoadWithOverviewMode(true);
1022 // Initialize cookieManager.
1023 cookieManager = CookieManager.getInstance();
1025 // 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).
1026 customHeaders.put("X-Requested-With", "");
1028 // 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.
1029 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
1031 // Get the intent that started the app.
1032 final Intent launchingIntent = getIntent();
1034 // Extract the launching intent data as `launchingIntentUriData`.
1035 final Uri launchingIntentUriData = launchingIntent.getData();
1037 // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
1038 if (launchingIntentUriData != null) {
1039 formattedUrlString = launchingIntentUriData.toString();
1042 // Get a handle for the `Runtime`.
1043 privacyBrowserRuntime = Runtime.getRuntime();
1045 // Store the application's private data directory.
1046 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`.
1048 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
1049 inFullScreenBrowsingMode = false;
1051 // Initialize AdView for the free flavor.
1052 adView = findViewById(R.id.adview);
1054 // Initialize the privacy settings variables.
1055 javaScriptEnabled = false;
1056 firstPartyCookiesEnabled = false;
1057 thirdPartyCookiesEnabled = false;
1058 domStorageEnabled = false;
1059 saveFormDataEnabled = false;
1061 // Initialize `webViewTitle`.
1062 webViewTitle = getString(R.string.no_title);
1064 // Initialize `favoriteIconBitmap`. We have to use `ContextCompat` until API >= 21.
1065 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
1066 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
1067 favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
1069 // If the favorite icon is null, load the default.
1070 if (favoriteIconBitmap == null) {
1071 favoriteIconBitmap = favoriteIconDefaultBitmap;
1074 // Apply the app settings from the shared preferences.
1077 // Load `formattedUrlString` if we are not waiting for Orbot to connect.
1078 if (!waitingForOrbot) {
1079 loadUrl(formattedUrlString);
1084 protected void onNewIntent(Intent intent) {
1085 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1088 if (intent.getData() != null) {
1089 // Get the intent data and convert it to a string.
1090 final Uri intentUriData = intent.getData();
1091 formattedUrlString = intentUriData.toString();
1094 // Close the navigation drawer if it is open.
1095 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1096 drawerLayout.closeDrawer(GravityCompat.START);
1099 // Load the website.
1100 loadUrl(formattedUrlString);
1102 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1103 mainWebView.requestFocus();
1107 public void onRestart() {
1110 // Apply the app settings, which may have been changed in `SettingsActivity`.
1113 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1114 updatePrivacyIcons(true);
1116 // Set the display webpage images mode.
1117 setDisplayWebpageImages();
1119 // Reload the webpage if displaying of images has been disabled in `SettingsFragment`.
1120 if (reloadOnRestartBoolean) {
1121 // Reload `mainWebView`.
1122 mainWebView.reload();
1124 // Reset `reloadOnRestartBoolean`.
1125 reloadOnRestartBoolean = false;
1129 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1131 public void onResume() {
1134 // Resume JavaScript (if enabled).
1135 mainWebView.resumeTimers();
1137 // Resume `mainWebView`.
1138 mainWebView.onResume();
1140 // Resume the adView for the free flavor.
1141 if (BuildConfig.FLAVOR.contentEquals("free")) {
1142 BannerAd.resumeAd(adView);
1147 public void onPause() {
1148 // Pause `mainWebView`.
1149 mainWebView.onPause();
1151 // Stop all JavaScript.
1152 mainWebView.pauseTimers();
1154 // Pause the adView or it will continue to consume resources in the background on the free flavor.
1155 if (BuildConfig.FLAVOR.contentEquals("free")) {
1156 BannerAd.pauseAd(adView);
1163 public boolean onCreateOptionsMenu(Menu menu) {
1164 // Inflate the menu; this adds items to the action bar if it is present.
1165 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1167 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1170 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1171 updatePrivacyIcons(false);
1173 // Get handles for the menu items.
1174 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1175 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1176 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1177 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1179 // Only display third-party cookies if SDK >= 21
1180 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1182 // Get the shared preference values. `this` references the current context.
1183 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1185 // Set the status of the additional app bar icons. The default is `false`.
1186 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
1187 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1188 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1189 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1190 } else { //Do not display the additional icons.
1191 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1192 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1193 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1200 public boolean onPrepareOptionsMenu(Menu menu) {
1201 // Get handles for the menu items.
1202 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1203 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1204 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1205 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1206 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1207 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1208 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);
1209 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1210 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1211 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1213 // Set the status of the menu item checkboxes.
1214 toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1215 toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1216 toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1217 toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);
1218 displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1220 // Enable third-party cookies if first-party cookies are enabled.
1221 toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1223 // Enable `DOM Storage` if JavaScript is enabled.
1224 toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
1226 // Enable `Clear Cookies` if there are any.
1227 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1229 // Get a count of the number of files in the `Local Storage` directory.
1230 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1231 int localStorageDirectoryNumberOfFiles = 0;
1232 if (localStorageDirectory.exists()) {
1233 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1236 // Get a count of the number of files in the `IndexedDB` directory.
1237 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1238 int indexedDBDirectoryNumberOfFiles = 0;
1239 if (indexedDBDirectory.exists()) {
1240 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1243 // Enable `Clear DOM Storage` if there is any.
1244 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1246 // Enable `Clear Form Data` is there is any.
1247 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1248 clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
1250 // Initialize font size variables.
1251 int fontSize = mainWebView.getSettings().getTextZoom();
1252 String fontSizeTitle;
1253 MenuItem selectedFontSizeMenuItem;
1255 // Prepare the font size title and current size menu item.
1258 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.twenty_five_percent);
1259 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1263 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.fifty_percent);
1264 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1268 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.seventy_five_percent);
1269 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1273 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
1274 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1278 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_twenty_five_percent);
1279 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1283 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_fifty_percent);
1284 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1288 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_seventy_five_percent);
1289 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1293 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.two_hundred_percent);
1294 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1298 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
1299 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1303 // Set the font size title and select the current size menu item.
1304 fontSizeMenuItem.setTitle(fontSizeTitle);
1305 selectedFontSizeMenuItem.setChecked(true);
1307 // Only show `Refresh` if `swipeToRefresh` is disabled.
1308 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
1310 // Run all the other default commands.
1311 super.onPrepareOptionsMenu(menu);
1313 // `return true` displays the menu.
1318 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1319 @SuppressLint("SetJavaScriptEnabled")
1320 // removeAllCookies is deprecated, but it is required for API < 21.
1321 @SuppressWarnings("deprecation")
1322 public boolean onOptionsItemSelected(MenuItem menuItem) {
1323 int menuItemId = menuItem.getItemId();
1325 // Set the commands that relate to the menu entries.
1326 switch (menuItemId) {
1327 case R.id.toggle_javascript:
1328 // Switch the status of javaScriptEnabled.
1329 javaScriptEnabled = !javaScriptEnabled;
1331 // Apply the new JavaScript status.
1332 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1334 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1335 updatePrivacyIcons(true);
1337 // Display a `Snackbar`.
1338 if (javaScriptEnabled) { // JavaScrip is enabled.
1339 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1340 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
1341 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1342 } else { // Privacy mode.
1343 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1346 // Reload the WebView.
1347 mainWebView.reload();
1350 case R.id.toggle_first_party_cookies:
1351 // Switch the status of firstPartyCookiesEnabled.
1352 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1354 // Update the menu checkbox.
1355 menuItem.setChecked(firstPartyCookiesEnabled);
1357 // Apply the new cookie status.
1358 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1360 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1361 updatePrivacyIcons(true);
1363 // Display a `Snackbar`.
1364 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1365 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1366 } else if (javaScriptEnabled){ // JavaScript is still enabled.
1367 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1368 } else { // Privacy mode.
1369 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1372 // Reload the WebView.
1373 mainWebView.reload();
1376 case R.id.toggle_third_party_cookies:
1377 if (Build.VERSION.SDK_INT >= 21) {
1378 // Switch the status of thirdPartyCookiesEnabled.
1379 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1381 // Update the menu checkbox.
1382 menuItem.setChecked(thirdPartyCookiesEnabled);
1384 // Apply the new cookie status.
1385 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1387 // Display a `Snackbar`.
1388 if (thirdPartyCookiesEnabled) {
1389 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1391 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1394 // Reload the WebView.
1395 mainWebView.reload();
1396 } // Else do nothing because SDK < 21.
1399 case R.id.toggle_dom_storage:
1400 // Switch the status of domStorageEnabled.
1401 domStorageEnabled = !domStorageEnabled;
1403 // Update the menu checkbox.
1404 menuItem.setChecked(domStorageEnabled);
1406 // Apply the new DOM Storage status.
1407 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1409 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1410 updatePrivacyIcons(true);
1412 // Display a `Snackbar`.
1413 if (domStorageEnabled) {
1414 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1416 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1419 // Reload the WebView.
1420 mainWebView.reload();
1423 case R.id.toggle_save_form_data:
1424 // Switch the status of saveFormDataEnabled.
1425 saveFormDataEnabled = !saveFormDataEnabled;
1427 // Update the menu checkbox.
1428 menuItem.setChecked(saveFormDataEnabled);
1430 // Apply the new form data status.
1431 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1433 // Display a `Snackbar`.
1434 if (saveFormDataEnabled) {
1435 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1437 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1440 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1441 updatePrivacyIcons(true);
1443 // Reload the WebView.
1444 mainWebView.reload();
1447 case R.id.clear_cookies:
1448 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1449 .setAction(R.string.undo, new View.OnClickListener() {
1451 public void onClick(View v) {
1452 // Do nothing because everything will be handled by `onDismissed()` below.
1455 .addCallback(new Snackbar.Callback() {
1457 public void onDismissed(Snackbar snackbar, int event) {
1459 // The user pushed the `Undo` button.
1460 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1464 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1466 // `cookieManager.removeAllCookie()` varies by SDK.
1467 if (Build.VERSION.SDK_INT < 21) {
1468 cookieManager.removeAllCookie();
1470 // `null` indicates no callback.
1471 cookieManager.removeAllCookies(null);
1479 case R.id.clear_dom_storage:
1480 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1481 .setAction(R.string.undo, new View.OnClickListener() {
1483 public void onClick(View v) {
1484 // Do nothing because everything will be handled by `onDismissed()` below.
1487 .addCallback(new Snackbar.Callback() {
1489 public void onDismissed(Snackbar snackbar, int event) {
1491 // The user pushed the `Undo` button.
1492 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1496 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1498 // Delete the DOM Storage.
1499 WebStorage webStorage = WebStorage.getInstance();
1500 webStorage.deleteAllData();
1502 // Manually remove `IndexedDB` if it exists.
1504 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1505 } catch (IOException e) {
1506 // Do nothing if an error is thrown.
1514 case R.id.clear_form_data:
1515 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1516 .setAction(R.string.undo, new View.OnClickListener() {
1518 public void onClick(View v) {
1519 // Do nothing because everything will be handled by `onDismissed()` below.
1522 .addCallback(new Snackbar.Callback() {
1524 public void onDismissed(Snackbar snackbar, int event) {
1526 // The user pushed the `Undo` button.
1527 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1531 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1533 // Delete the form data.
1534 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1535 mainWebViewDatabase.clearFormData();
1542 case R.id.font_size_twenty_five_percent:
1543 mainWebView.getSettings().setTextZoom(25);
1546 case R.id.font_size_fifty_percent:
1547 mainWebView.getSettings().setTextZoom(50);
1550 case R.id.font_size_seventy_five_percent:
1551 mainWebView.getSettings().setTextZoom(75);
1554 case R.id.font_size_one_hundred_percent:
1555 mainWebView.getSettings().setTextZoom(100);
1558 case R.id.font_size_one_hundred_twenty_five_percent:
1559 mainWebView.getSettings().setTextZoom(125);
1562 case R.id.font_size_one_hundred_fifty_percent:
1563 mainWebView.getSettings().setTextZoom(150);
1566 case R.id.font_size_one_hundred_seventy_five_percent:
1567 mainWebView.getSettings().setTextZoom(175);
1570 case R.id.font_size_two_hundred_percent:
1571 mainWebView.getSettings().setTextZoom(200);
1574 case R.id.display_images:
1575 if (mainWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1576 mainWebView.getSettings().setLoadsImagesAutomatically(false);
1577 mainWebView.reload();
1578 } else { // Images are not currently loaded automatically.
1579 mainWebView.getSettings().setLoadsImagesAutomatically(true);
1582 // Set `onTheFlyDisplayImagesSet`.
1583 onTheFlyDisplayImagesSet = true;
1587 // Setup the share string.
1588 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
1590 // Create the share intent.
1591 Intent shareIntent = new Intent();
1592 shareIntent.setAction(Intent.ACTION_SEND);
1593 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1594 shareIntent.setType("text/plain");
1597 startActivity(Intent.createChooser(shareIntent, "Share URL"));
1600 case R.id.find_on_page:
1601 // Hide the URL app bar.
1602 supportAppBar.setVisibility(View.GONE);
1604 // Show the Find on Page `RelativeLayout`.
1605 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1607 // 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
1608 findOnPageEditText.postDelayed(new Runnable() {
1612 // Set the focus on `findOnPageEditText`.
1613 findOnPageEditText.requestFocus();
1615 // Display the keyboard. `0` sets no input flags.
1616 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1622 // Get a `PrintManager` instance.
1623 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1625 // Convert `mainWebView` to `printDocumentAdapter`.
1626 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
1628 // Print the document. The print attributes are `null`.
1629 printManager.print(getResources().getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1632 case R.id.add_to_homescreen:
1633 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
1634 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
1635 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.create_shortcut));
1637 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
1641 mainWebView.reload();
1645 // Don't consume the event.
1646 return super.onOptionsItemSelected(menuItem);
1650 // removeAllCookies is deprecated, but it is required for API < 21.
1651 @SuppressWarnings("deprecation")
1653 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1654 int menuItemId = menuItem.getItemId();
1656 switch (menuItemId) {
1662 if (mainWebView.canGoBack()) {
1663 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1664 navigatingHistory = true;
1666 // Load the previous website in the history.
1667 mainWebView.goBack();
1672 if (mainWebView.canGoForward()) {
1673 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1674 navigatingHistory = true;
1676 // Load the next website in the history.
1677 mainWebView.goForward();
1682 // Get the `WebBackForwardList`.
1683 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
1685 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
1686 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
1687 urlHistoryDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.history));
1690 case R.id.bookmarks:
1691 // Launch BookmarksActivity.
1692 Intent bookmarksIntent = new Intent(this, BookmarksActivity.class);
1693 startActivity(bookmarksIntent);
1696 case R.id.downloads:
1697 // Launch the system Download Manager.
1698 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1700 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1701 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1703 startActivity(downloadManagerIntent);
1707 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1708 currentDomainName = "";
1710 // Launch `SettingsActivity`.
1711 Intent settingsIntent = new Intent(this, SettingsActivity.class);
1712 startActivity(settingsIntent);
1716 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1717 currentDomainName = "";
1719 // Launch `DomainsActivity`.
1720 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1721 startActivity(domainsIntent);
1725 // Launch `GuideActivity`.
1726 Intent guideIntent = new Intent(this, GuideActivity.class);
1727 startActivity(guideIntent);
1731 // Launch `AboutActivity`.
1732 Intent aboutIntent = new Intent(this, AboutActivity.class);
1733 startActivity(aboutIntent);
1736 case R.id.clearAndExit:
1737 // Get a handle for `sharedPreferences`. `this` references the current context.
1738 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1740 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
1743 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
1744 // The command to remove cookies changed slightly in API 21.
1745 if (Build.VERSION.SDK_INT >= 21) {
1746 cookieManager.removeAllCookies(null);
1748 cookieManager.removeAllCookie();
1751 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1753 // We have to use two commands because `Runtime.exec()` does not like `*`.
1754 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
1755 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
1756 } catch (IOException e) {
1757 // Do nothing if an error is thrown.
1761 // Clear DOM storage.
1762 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
1763 // Ask `WebStorage` to clear the DOM storage.
1764 WebStorage webStorage = WebStorage.getInstance();
1765 webStorage.deleteAllData();
1767 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1769 // We have to use a `String[]` because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1770 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1772 // We have to use multiple commands because `Runtime.exec()` does not like `*`.
1773 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1774 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1775 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1776 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1777 } catch (IOException e) {
1778 // Do nothing if an error is thrown.
1783 if (clearEverything || sharedPreferences.getBoolean("clear_form_data", true)) {
1784 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1785 webViewDatabase.clearFormData();
1787 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1789 // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1790 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
1791 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
1792 } catch (IOException e) {
1793 // Do nothing if an error is thrown.
1798 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
1799 // `true` includes disk files.
1800 mainWebView.clearCache(true);
1802 // Manually delete the cache directories.
1804 // Delete the main cache directory.
1805 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1807 // 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.
1808 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1809 } catch (IOException e) {
1810 // Do nothing if an error is thrown.
1814 // Clear SSL certificate preferences.
1815 mainWebView.clearSslPreferences();
1817 // Clear the back/forward history.
1818 mainWebView.clearHistory();
1820 // Clear `formattedUrlString`.
1821 formattedUrlString = null;
1823 // Clear `customHeaders`.
1824 customHeaders.clear();
1826 // Detach all views from `mainWebViewRelativeLayout`.
1827 mainWebViewRelativeLayout.removeAllViews();
1829 // Destroy the internal state of `mainWebView`.
1830 mainWebView.destroy();
1832 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
1833 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
1834 if (clearEverything) {
1836 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
1837 } catch (IOException e) {
1838 // Do nothing if an error is thrown.
1842 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
1843 if (Build.VERSION.SDK_INT >= 21) {
1844 finishAndRemoveTask();
1849 // Remove the terminated program from RAM. The status code is `0`.
1854 // Close the navigation drawer.
1855 drawerLayout.closeDrawer(GravityCompat.START);
1860 public void onPostCreate(Bundle savedInstanceState) {
1861 super.onPostCreate(savedInstanceState);
1863 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
1864 drawerToggle.syncState();
1868 public void onConfigurationChanged(Configuration newConfig) {
1869 super.onConfigurationChanged(newConfig);
1871 // Reload the ad for the free flavor if we are not in full screen mode.
1872 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
1874 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1876 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1877 adView = findViewById(R.id.adview);
1880 // `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
1881 // ActivityCompat.invalidateOptionsMenu(this);
1885 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
1886 // Store the `HitTestResult`.
1887 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
1890 final String imageUrl;
1891 final String linkUrl;
1893 // Get a handle for the `ClipboardManager`.
1894 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
1896 switch (hitTestResult.getType()) {
1897 // `SRC_ANCHOR_TYPE` is a link.
1898 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1899 // Get the target URL.
1900 linkUrl = hitTestResult.getExtra();
1902 // Set the target URL as the title of the `ContextMenu`.
1903 menu.setHeaderTitle(linkUrl);
1905 // Add a `Load URL` entry.
1906 menu.add(R.string.load_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1908 public boolean onMenuItemClick(MenuItem item) {
1914 // Add a `Copy URL` entry.
1915 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1917 public boolean onMenuItemClick(MenuItem item) {
1918 // Save the link URL in a `ClipData`.
1919 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), linkUrl);
1921 // Set the `ClipData` as the clipboard's primary clip.
1922 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
1927 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1928 menu.add(R.string.cancel);
1931 case WebView.HitTestResult.EMAIL_TYPE:
1932 // Get the target URL.
1933 linkUrl = hitTestResult.getExtra();
1935 // Set the target URL as the title of the `ContextMenu`.
1936 menu.setHeaderTitle(linkUrl);
1938 // Add a `Write Email` entry.
1939 menu.add(R.string.write_email).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1941 public boolean onMenuItemClick(MenuItem item) {
1942 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1943 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1945 // Parse the url and set it as the data for the `Intent`.
1946 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
1948 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
1949 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1952 startActivity(emailIntent);
1957 // Add a `Copy Email Address` entry.
1958 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1960 public boolean onMenuItemClick(MenuItem item) {
1961 // Save the email address in a `ClipData`.
1962 ClipData srcEmailTypeClipData = ClipData.newPlainText(getResources().getString(R.string.email_address), linkUrl);
1964 // Set the `ClipData` as the clipboard's primary clip.
1965 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
1970 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1971 menu.add(R.string.cancel);
1974 // `IMAGE_TYPE` is an image.
1975 case WebView.HitTestResult.IMAGE_TYPE:
1976 // Get the image URL.
1977 imageUrl = hitTestResult.getExtra();
1979 // Set the image URL as the title of the `ContextMenu`.
1980 menu.setHeaderTitle(imageUrl);
1982 // Add a `View Image` entry.
1983 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1985 public boolean onMenuItemClick(MenuItem item) {
1991 // Add a `Download Image` entry.
1992 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1994 public boolean onMenuItemClick(MenuItem item) {
1995 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
1996 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
1997 downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
2002 // Add a `Copy URL` entry.
2003 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2005 public boolean onMenuItemClick(MenuItem item) {
2006 // Save the image URL in a `ClipData`.
2007 ClipData srcImageTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
2009 // Set the `ClipData` as the clipboard's primary clip.
2010 clipboardManager.setPrimaryClip(srcImageTypeClipData);
2015 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2016 menu.add(R.string.cancel);
2020 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2021 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2022 // Get the image URL.
2023 imageUrl = hitTestResult.getExtra();
2025 // Set the image URL as the title of the `ContextMenu`.
2026 menu.setHeaderTitle(imageUrl);
2028 // Add a `View Image` entry.
2029 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2031 public boolean onMenuItemClick(MenuItem item) {
2037 // Add a `Download Image` entry.
2038 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2040 public boolean onMenuItemClick(MenuItem item) {
2041 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
2042 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2043 downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
2048 // Add a `Copy URL` entry.
2049 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2051 public boolean onMenuItemClick(MenuItem item) {
2052 // Save the image URL in a `ClipData`.
2053 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
2055 // Set the `ClipData` as the clipboard's primary clip.
2056 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2061 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2062 menu.add(R.string.cancel);
2068 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
2069 // Get shortcutNameEditText from the alert dialog.
2070 EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
2072 // Create the bookmark shortcut based on formattedUrlString.
2073 Intent bookmarkShortcut = new Intent();
2074 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
2075 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
2077 // Place the bookmark shortcut on the home screen.
2078 Intent placeBookmarkShortcut = new Intent();
2079 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
2080 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
2081 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIconBitmap);
2082 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
2083 sendBroadcast(placeBookmarkShortcut);
2087 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
2088 // Download the image if it has an HTTP or HTTPS URI.
2089 if (imageUrl.startsWith("http")) {
2090 // Get a handle for the system `DOWNLOAD_SERVICE`.
2091 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2093 // Parse `imageUrl`.
2094 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
2096 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
2097 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2098 if (firstPartyCookiesEnabled) {
2099 // Get the cookies for `imageUrl`.
2100 String cookies = cookieManager.getCookie(imageUrl);
2102 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2103 downloadRequest.addRequestHeader("Cookie", cookies);
2106 // Get the file name from `dialogFragment`.
2107 EditText downloadImageNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_image_name);
2108 String imageName = downloadImageNameEditText.getText().toString();
2110 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
2111 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `imageName`.
2112 downloadRequest.setDestinationInExternalFilesDir(this, "/", imageName);
2113 } else { // Only set the title using `imageName`.
2114 downloadRequest.setTitle(imageName);
2117 // Allow `MediaScanner` to index the download if it is a media file.
2118 downloadRequest.allowScanningByMediaScanner();
2120 // Add the URL as the description for the download.
2121 downloadRequest.setDescription(imageUrl);
2123 // Show the download notification after the download is completed.
2124 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2126 // Initiate the download.
2127 downloadManager.enqueue(downloadRequest);
2128 } else { // The image is not an HTTP or HTTPS URI.
2129 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
2134 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
2135 // Download the file if it has an HTTP or HTTPS URI.
2136 if (downloadUrl.startsWith("http")) {
2138 // Get a handle for the system `DOWNLOAD_SERVICE`.
2139 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2141 // Parse `downloadUrl`.
2142 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
2144 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
2145 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2146 if (firstPartyCookiesEnabled) {
2147 // Get the cookies for `downloadUrl`.
2148 String cookies = cookieManager.getCookie(downloadUrl);
2150 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2151 downloadRequest.addRequestHeader("Cookie", cookies);
2154 // Get the file name from `dialogFragment`.
2155 EditText downloadFileNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_file_name);
2156 String fileName = downloadFileNameEditText.getText().toString();
2158 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
2159 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download location to `/sdcard/Android/data/com.stoutner.privacybrowser.standard/files` named `fileName`.
2160 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
2161 } else { // Only set the title using `fileName`.
2162 downloadRequest.setTitle(fileName);
2165 // Allow `MediaScanner` to index the download if it is a media file.
2166 downloadRequest.allowScanningByMediaScanner();
2168 // Add the URL as the description for the download.
2169 downloadRequest.setDescription(downloadUrl);
2171 // Show the download notification after the download is completed.
2172 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2174 // Initiate the download.
2175 downloadManager.enqueue(downloadRequest);
2176 } else { // The download is not an HTTP or HTTPS URI.
2177 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
2181 public void viewSslCertificate(View view) {
2182 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
2183 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
2184 viewSslCertificateDialogFragment.show(getFragmentManager(), getResources().getString(R.string.view_ssl_certificate));
2188 public void onSslErrorCancel() {
2189 sslErrorHandler.cancel();
2193 public void onSslErrorProceed() {
2194 sslErrorHandler.proceed();
2198 public void onSslMismatchBack() {
2199 if (mainWebView.canGoBack()) { // There is a back page in the history.
2200 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2201 navigatingHistory = true;
2204 mainWebView.goBack();
2205 } else { // There are no pages to go back to.
2206 // Load a blank page
2212 public void onSslMismatchProceed() {
2213 // Do not check the pinned SSL certificate for this domain again until the domain changes.
2214 ignorePinnedSslCertificate = true;
2218 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
2219 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2220 navigatingHistory = true;
2222 // Load the history entry.
2223 mainWebView.goBackOrForward(moveBackOrForwardSteps);
2227 public void onClearHistory() {
2228 // Clear the history.
2229 mainWebView.clearHistory();
2232 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
2234 public void onBackPressed() {
2235 // Close the navigation drawer if it is available. GravityCompat.START is the drawer on the left on Left-to-Right layout text.
2236 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
2237 drawerLayout.closeDrawer(GravityCompat.START);
2239 // Load the previous URL if available.
2240 if (mainWebView.canGoBack()) {
2241 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2242 navigatingHistory = true;
2245 mainWebView.goBack();
2247 // Pass `onBackPressed()` to the system.
2248 super.onBackPressed();
2253 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
2254 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
2255 String unformattedUrlString = urlTextBox.getText().toString().trim();
2257 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
2258 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
2259 // Add `http://` at the beginning if it is missing. Otherwise the app will segfault.
2260 if (!unformattedUrlString.startsWith("http")) {
2261 unformattedUrlString = "http://" + unformattedUrlString;
2264 // Initialize `unformattedUrl`.
2265 URL unformattedUrl = null;
2267 // 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.
2269 unformattedUrl = new URL(unformattedUrlString);
2270 } catch (MalformedURLException e) {
2271 e.printStackTrace();
2274 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2275 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2276 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2277 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2278 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2279 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2282 Uri.Builder formattedUri = new Uri.Builder();
2283 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2285 // Decode `formattedUri` as a `String` in `UTF-8`.
2286 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
2288 // Sanitize the search input and convert it to a search.
2289 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2291 // Add the base search URL.
2292 formattedUrlString = searchURL + encodedUrlString;
2295 loadUrl(formattedUrlString);
2297 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
2298 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2302 private void loadUrl(String url) {
2303 // Apply any custom domain settings.
2304 applyDomainSettings(url);
2307 mainWebView.loadUrl(url, customHeaders);
2309 // Set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
2310 urlIsLoading = true;
2313 public void findPreviousOnPage(View view) {
2314 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
2315 mainWebView.findNext(false);
2318 public void findNextOnPage(View view) {
2319 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2320 mainWebView.findNext(true);
2323 public void closeFindOnPage(View view) {
2324 // Delete the contents of `find_on_page_edittext`.
2325 findOnPageEditText.setText(null);
2327 // Clear the highlighted phrases.
2328 mainWebView.clearMatches();
2330 // Hide the Find on Page `RelativeLayout`.
2331 findOnPageLinearLayout.setVisibility(View.GONE);
2333 // Show the URL app bar.
2334 supportAppBar.setVisibility(View.VISIBLE);
2336 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
2337 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2340 private void applyAppSettings() {
2341 // Get a handle for `sharedPreferences`. `this` references the current context.
2342 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2344 // Store the values from `sharedPreferences` in variables.
2345 String homepageString = sharedPreferences.getString("homepage", "https://start.duckduckgo.com");
2346 String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
2347 String torSearchString = sharedPreferences.getString("tor_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
2348 String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
2349 String searchString = sharedPreferences.getString("search", "https://duckduckgo.com/html/?q=");
2350 String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
2351 adBlockerEnabled = sharedPreferences.getBoolean("block_ads", true);
2352 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
2353 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
2354 boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
2355 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
2356 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
2357 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
2358 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh", false);
2359 displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
2361 // Set the homepage, search, and proxy options.
2362 if (proxyThroughOrbot) { // Set the Tor options.
2363 // Set `torHomepageString` as `homepage`.
2364 homepage = torHomepageString;
2366 // If formattedUrlString is null assign the homepage to it.
2367 if (formattedUrlString == null) {
2368 formattedUrlString = homepage;
2371 // Set the search URL.
2372 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
2373 searchURL = torSearchCustomURLString;
2374 } else { // Use the string from the pre-built list.
2375 searchURL = torSearchString;
2378 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
2379 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
2381 // Set the `appBar` background to indicate proxying through Orbot is enabled. `this` refers to the context.
2383 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
2385 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
2388 // Display a message to the user if we are waiting on Orbot.
2389 if (!orbotStatus.equals("ON")) {
2390 // Set `waitingForOrbot`.
2391 waitingForOrbot = true;
2393 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
2394 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
2396 } else { // Set the non-Tor options.
2397 // Set `homepageString` as `homepage`.
2398 homepage = homepageString;
2400 // If formattedUrlString is null assign the homepage to it.
2401 if (formattedUrlString == null) {
2402 formattedUrlString = homepage;
2405 // Set the search URL.
2406 if (searchString.equals("Custom URL")) { // Get the custom URL string.
2407 searchURL = searchCustomURLString;
2408 } else { // Use the string from the pre-built list.
2409 searchURL = searchString;
2412 // Reset the proxy to default. The host is `""` and the port is `"0"`.
2413 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
2415 // Set the default `appBar` background. `this` refers to the context.
2417 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
2419 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
2422 // Reset `waitingForOrbot.
2423 waitingForOrbot = false;
2426 // Set swipe to refresh.
2427 swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
2429 // Set Do Not Track status.
2430 if (doNotTrackEnabled) {
2431 customHeaders.put("DNT", "1");
2433 customHeaders.remove("DNT");
2436 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
2437 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
2438 if (hideSystemBarsOnFullscreen) { // Hide everything.
2439 // Remove the translucent navigation setting if it is currently flagged.
2440 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2442 // Remove the translucent status bar overlay.
2443 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2445 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
2446 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
2448 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
2449 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
2450 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
2452 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
2453 } else { // Hide everything except the status and navigation bars.
2454 // Add the translucent status flag if it is unset.
2455 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2457 if (translucentNavigationBarOnFullscreen) {
2458 // Set the navigation bar to be translucent.
2459 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2461 // Set the navigation bar to be black.
2462 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2465 } else { // Switch to normal viewing mode.
2466 // Reset `inFullScreenBrowsingMode` to `false`.
2467 inFullScreenBrowsingMode = false;
2469 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
2470 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
2474 // Show the `BannerAd` in the free flavor.
2475 if (BuildConfig.FLAVOR.contentEquals("free")) {
2476 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
2477 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2479 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2480 adView = findViewById(R.id.adview);
2483 // Remove the translucent navigation bar flag if it is set.
2484 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2486 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
2487 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2489 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
2490 rootCoordinatorLayout.setSystemUiVisibility(0);
2492 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
2493 rootCoordinatorLayout.setFitsSystemWindows(true);
2497 // We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2498 @SuppressWarnings("deprecation")
2499 private void applyDomainSettings(String url) {
2500 // Reset `navigatingHistory`.
2501 navigatingHistory = false;
2503 // Parse the URL into a URI.
2504 Uri uri = Uri.parse(url);
2506 // Extract the domain from `uri`.
2507 String hostName = uri.getHost();
2509 // Initialize `loadingNewDomainName`.
2510 boolean loadingNewDomainName;
2512 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
2513 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
2514 //noinspection SimplifiableIfStatement
2515 if ((hostName == null) || (currentDomainName == null)) {
2516 loadingNewDomainName = true;
2517 } else { // Determine if `hostName` equals `currentDomainName`.
2518 loadingNewDomainName = !hostName.equals(currentDomainName);
2521 // 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.
2522 if (loadingNewDomainName) {
2523 // Set the new `hostname` as the `currentDomainName`.
2524 currentDomainName = hostName;
2526 // Reset `ignorePinnedSslCertificate`.
2527 ignorePinnedSslCertificate = false;
2529 // Reset `favoriteIconBitmap` and display it in the `appbar`.
2530 favoriteIconBitmap = favoriteIconDefaultBitmap;
2531 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
2533 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
2534 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2535 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2537 // Get a full cursor from `domainsDatabaseHelper`.
2538 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
2540 // Initialize `domainSettingsSet`.
2541 Set<String> domainSettingsSet = new HashSet<>();
2543 // Get the domain name column index.
2544 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
2546 // Populate `domainSettingsSet`.
2547 for (int i = 0; i < domainNameCursor.getCount(); i++) {
2548 // Move `domainsCursor` to the current row.
2549 domainNameCursor.moveToPosition(i);
2551 // Store the domain name in `domainSettingsSet`.
2552 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
2555 // Close `domainNameCursor.
2556 domainNameCursor.close();
2558 // Initialize variables to track if domain settings will be applied and, if so, under which name.
2559 domainSettingsApplied = false;
2560 String domainNameInDatabase = null;
2562 // Check the hostname.
2563 if (domainSettingsSet.contains(hostName)) {
2564 domainSettingsApplied = true;
2565 domainNameInDatabase = hostName;
2568 // If `hostName` is not `null`, check all the subdomains of `hostName` against wildcard domains in `domainCursor`.
2569 if (hostName != null) {
2570 while (hostName.contains(".") && !domainSettingsApplied) { // Stop checking if we run out of `.` or if we already know that `domainSettingsApplied` is `true`.
2571 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
2572 domainSettingsApplied = true;
2573 domainNameInDatabase = "*." + hostName;
2576 // Strip out the lowest subdomain of `host`.
2577 hostName = hostName.substring(hostName.indexOf(".") + 1);
2581 // Get a handle for the shared preference. `this` references the current context.
2582 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2584 // Store the default font size and user agent information.
2585 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
2586 String defaultUserAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
2587 String defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
2589 if (domainSettingsApplied) { // The url we are loading has custom domain settings.
2590 // Get a cursor for the current host and move it to the first position.
2591 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
2592 currentHostDomainSettingsCursor.moveToFirst();
2594 // Get the settings from the cursor.
2595 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
2596 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
2597 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
2598 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
2599 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
2600 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
2601 String userAgentString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
2602 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
2603 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
2604 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
2605 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
2606 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
2607 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
2608 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
2609 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
2610 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
2612 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
2613 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
2614 pinnedDomainSslStartDate = null;
2616 pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
2619 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
2620 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
2621 pinnedDomainSslEndDate = null;
2623 pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
2626 // Close `currentHostDomainSettingsCursor`.
2627 currentHostDomainSettingsCursor.close();
2629 // Apply the domain settings.
2630 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2631 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2632 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2633 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2635 // Apply the font size.
2636 if (fontSize == 0) { // Apply the default font size.
2637 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
2638 } else { // Apply the specified font size.
2639 mainWebView.getSettings().setTextZoom(fontSize);
2642 // Set third-party cookies status if API >= 21.
2643 if (Build.VERSION.SDK_INT >= 21) {
2644 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2647 // 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>
2648 if (!urlIsLoading) {
2649 switch (userAgentString) {
2650 case "System default user agent":
2651 // Set the user agent according to the system default.
2652 switch (defaultUserAgentString) {
2653 case "WebView default user agent":
2654 // Set the user agent to `""`, which uses the default value.
2655 mainWebView.getSettings().setUserAgentString("");
2658 case "Custom user agent":
2659 // Set the custom user agent.
2660 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
2664 // Use the selected user agent.
2665 mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
2669 case "WebView default user agent":
2670 // Set the user agent to `""`, which uses the default value.
2671 mainWebView.getSettings().setUserAgentString("");
2675 // Use the selected user agent.
2676 mainWebView.getSettings().setUserAgentString(userAgentString);
2680 // 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.
2682 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
2684 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
2686 } else { // The URL we are loading does not have custom domain settings. Load the defaults.
2687 // Store the values from `sharedPreferences` in variables.
2688 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
2689 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
2690 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
2691 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
2692 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
2694 // Apply the default settings.
2695 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2696 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2697 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2698 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2699 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
2701 // Reset the pinned SSL certificate information.
2702 domainSettingsDatabaseId = -1;
2703 pinnedDomainSslCertificate = false;
2704 pinnedDomainSslIssuedToCNameString = "";
2705 pinnedDomainSslIssuedToONameString = "";
2706 pinnedDomainSslIssuedToUNameString = "";
2707 pinnedDomainSslIssuedByCNameString = "";
2708 pinnedDomainSslIssuedByONameString = "";
2709 pinnedDomainSslIssuedByUNameString = "";
2710 pinnedDomainSslStartDate = null;
2711 pinnedDomainSslEndDate = null;
2713 // Set third-party cookies status if API >= 21.
2714 if (Build.VERSION.SDK_INT >= 21) {
2715 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2718 // 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>
2719 if (!urlIsLoading) {
2720 switch (defaultUserAgentString) {
2721 case "WebView default user agent":
2722 // Set the user agent to `""`, which uses the default value.
2723 mainWebView.getSettings().setUserAgentString("");
2726 case "Custom user agent":
2727 // Set the custom user agent.
2728 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
2732 // Use the selected user agent.
2733 mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
2737 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2738 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
2741 // Close `domainsDatabaseHelper`.
2742 domainsDatabaseHelper.close();
2744 // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode. `true` indicates that custom domain settings are applied.
2745 onTheFlyDisplayImagesSet = false;
2746 setDisplayWebpageImages();
2748 // Update the privacy icons, but only if `mainMenu` has already been populated.
2749 if (mainMenu != null) {
2750 updatePrivacyIcons(true);
2755 private void setDisplayWebpageImages() {
2756 if (!onTheFlyDisplayImagesSet) {
2757 if (domainSettingsApplied) { // Custom domain settings are applied.
2758 switch (displayWebpageImagesInt) {
2759 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
2760 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
2763 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
2764 mainWebView.getSettings().setLoadsImagesAutomatically(true);
2767 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
2768 mainWebView.getSettings().setLoadsImagesAutomatically(false);
2771 } else { // Default settings are applied.
2772 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
2777 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
2778 // Get handles for the icons.
2779 MenuItem privacyIconMenuItem = mainMenu.findItem(R.id.toggle_javascript);
2780 MenuItem firstPartyCookiesIconMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
2781 MenuItem domStorageIconMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
2782 MenuItem formDataIconMenuItem = mainMenu.findItem(R.id.toggle_save_form_data);
2784 // Update `privacyIcon`.
2785 if (javaScriptEnabled) { // JavaScript is enabled.
2786 privacyIconMenuItem.setIcon(R.drawable.javascript_enabled);
2787 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
2788 privacyIconMenuItem.setIcon(R.drawable.warning);
2789 } else { // All the dangerous features are disabled.
2790 privacyIconMenuItem.setIcon(R.drawable.privacy_mode);
2793 // Update `firstPartyCookiesIcon`.
2794 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
2795 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_enabled);
2796 } else { // First-party cookies are disabled.
2798 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_dark);
2800 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_light);
2804 // Update `domStorageIcon`.
2805 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
2806 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_enabled);
2807 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
2809 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
2811 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
2813 } else { // JavaScript is disabled, so DOM storage is ghosted.
2815 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
2817 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
2821 // Update `formDataIcon`.
2822 if (saveFormDataEnabled) { // Form data is enabled.
2823 formDataIconMenuItem.setIcon(R.drawable.form_data_enabled);
2824 } else { // Form data is disabled.
2826 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_dark);
2828 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_light);
2832 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`. `this` references the current activity.
2833 if (runInvalidateOptionsMenu) {
2834 ActivityCompat.invalidateOptionsMenu(this);
2838 private void highlightUrlText() {
2839 String urlString = urlTextBox.getText().toString();
2841 if (urlString.startsWith("http://")) { // Highlight connections that are not encrypted.
2842 urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
2843 } else if (urlString.startsWith("https://")) { // Highlight connections that are encrypted.
2844 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
2847 // Get the index of the `/` immediately after the domain name.
2848 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
2850 // De-emphasize the text after the domain name.
2851 if (endOfDomainName > 0) {
2852 urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);