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 String pinnedDomainSslIssuedToCNameString;
157 public static String pinnedDomainSslIssuedToONameString;
158 public static String pinnedDomainSslIssuedToUNameString;
159 public static String pinnedDomainSslIssuedByCNameString;
160 public static String pinnedDomainSslIssuedByONameString;
161 public static String pinnedDomainSslIssuedByUNameString;
162 public static Date pinnedDomainSslStartDate;
163 public static Date pinnedDomainSslEndDate;
166 // `appBar` is used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applyAppSettings()`.
167 private ActionBar appBar;
169 // `navigatingHistory` is used in `onCreate()`, `onNavigationItemSelected()`, `onSslMismatchBack()`, and `applyDomainSettings()`.
170 private boolean navigatingHistory;
172 // `favoriteIconDefaultBitmap` is used in `onCreate()` and `applyDomainSettings`.
173 private Bitmap favoriteIconDefaultBitmap;
175 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, and `onBackPressed()`.
176 private DrawerLayout drawerLayout;
178 // `rootCoordinatorLayout` is used in `onCreate()` and `applyAppSettings()`.
179 private CoordinatorLayout rootCoordinatorLayout;
181 // `mainWebView` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`, `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`
182 // `onSslMismatchBack()`, and `setDisplayWebpageImages()`.
183 private WebView mainWebView;
185 // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
186 private FrameLayout fullScreenVideoFrameLayout;
188 // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu`, and `onRestart()`.
189 private SwipeRefreshLayout swipeRefreshLayout;
191 // `urlAppBarRelativeLayout` is used in `onCreate()` and `applyDomainSettings()`.
192 private RelativeLayout urlAppBarRelativeLayout;
194 // `favoriteIconImageView` is used in `onCreate()` and `applyDomainSettings()`
195 private ImageView favoriteIconImageView;
197 // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `loadUrlFromTextBox()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
198 private CookieManager cookieManager;
200 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
201 private final Map<String, String> customHeaders = new HashMap<>();
203 // `javaScriptEnabled` is also used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `applyAppSettings()`.
204 // It is `Boolean` instead of `boolean` because `applyAppSettings()` needs to know if it is `null`.
205 private Boolean javaScriptEnabled;
207 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applyAppSettings()`.
208 private boolean firstPartyCookiesEnabled;
210 // `thirdPartyCookiesEnabled` used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
211 private boolean thirdPartyCookiesEnabled;
213 // `domStorageEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
214 private boolean domStorageEnabled;
216 // `saveFormDataEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
217 private boolean saveFormDataEnabled;
219 // `swipeToRefreshEnabled` is used in `onPrepareOptionsMenu()` and `applyAppSettings()`.
220 private boolean swipeToRefreshEnabled;
222 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applyAppSettings()`.
223 private String homepage;
225 // `searchURL` is used in `loadURLFromTextBox()` and `applyAppSettings()`.
226 private String searchURL;
228 // `adBlockerEnabled` is used in `onCreate()` and `applyAppSettings()`.
229 private boolean adBlockerEnabled;
231 // `privacyBrowserRuntime` is used in `onCreate()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
232 private Runtime privacyBrowserRuntime;
234 // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
235 private boolean incognitoModeEnabled;
237 // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
238 private boolean fullScreenBrowsingModeEnabled;
240 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
241 private boolean inFullScreenBrowsingMode;
243 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
244 private boolean hideSystemBarsOnFullscreen;
246 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
247 private boolean translucentNavigationBarOnFullscreen;
249 // `currentDomainName` is used in `onCreate()`, `onNavigationItemSelected()`, `onSslMismatchProceed()`, and `applyDomainSettings()`.
250 private String currentDomainName;
252 // `ignorePinnedSslCertificateForDomain` is used in `onCreate()`, `onSslMismatchProceed()`, and `applyDomainSettings()`.
253 private boolean ignorePinnedSslCertificate;
255 // `waitingForOrbot` is used in `onCreate()` and `applyAppSettings()`.
256 private boolean waitingForOrbot;
258 // `domainSettingsApplied` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
259 private boolean domainSettingsApplied;
261 // `displayWebpageImagesInt` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
262 private int displayWebpageImagesInt;
264 // `onTheFlyDisplayImagesSet` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
265 private boolean onTheFlyDisplayImagesSet;
267 // `waitingForOrbotData` is used in `onCreate()` and `applyAppSettings()`.
268 private String waitingForOrbotHTMLString;
270 // `privateDataDirectoryString` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
271 private String privateDataDirectoryString;
273 // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
274 private LinearLayout findOnPageLinearLayout;
276 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
277 private EditText findOnPageEditText;
279 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
280 private Menu mainMenu;
282 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
283 private ActionBarDrawerToggle drawerToggle;
285 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
286 private Toolbar supportAppBar;
288 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, `loadUrl()`, and `highlightUrlText()`.
289 private EditText urlTextBox;
291 // `redColorSpan` is used in `onCreate()` and `highlightUrlText()`.
292 private ForegroundColorSpan redColorSpan;
294 // `initialGrayColorSpan` is sued in `onCreate()` and `highlightUrlText()`.
295 private ForegroundColorSpan initialGrayColorSpan;
297 // `finalGrayColorSpam` is used in `onCreate()` and `highlightUrlText()`.
298 private ForegroundColorSpan finalGrayColorSpan;
300 // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
303 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
304 private SslErrorHandler sslErrorHandler;
306 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
307 private InputMethodManager inputMethodManager;
309 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
310 private RelativeLayout mainWebViewRelativeLayout;
312 // `urlIsLoading` is used in `onCreate()`, `loadUrl()`, and `applyDomainSettings()`.
313 private boolean urlIsLoading;
315 // `pinnedDomainSslCertificate` is used in `onCreate()` and `applyDomainSettings()`.
316 private boolean pinnedDomainSslCertificate;
320 // 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.
321 @SuppressLint("SetJavaScriptEnabled")
322 // Remove Android Studio's warning about deprecations. We have to use the deprecated `getColor()` until API >= 23.
323 @SuppressWarnings("deprecation")
324 protected void onCreate(Bundle savedInstanceState) {
325 // Get a handle for `sharedPreferences`. `this` references the current context.
326 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
328 // Get the theme preference.
329 darkTheme = sharedPreferences.getBoolean("dark_theme", false);
331 // Set the activity theme.
333 setTheme(R.style.PrivacyBrowserDark);
335 setTheme(R.style.PrivacyBrowserLight);
338 // Run the default commands.
339 super.onCreate(savedInstanceState);
341 // Set the content view.
342 setContentView(R.layout.main_drawerlayout);
344 // Get a handle for `inputMethodManager`.
345 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
347 // We need to use the `SupportActionBar` from `android.support.v7.app.ActionBar` until the minimum API is >= 21.
348 supportAppBar = (Toolbar) findViewById(R.id.app_bar);
349 setSupportActionBar(supportAppBar);
350 appBar = getSupportActionBar();
352 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
353 assert appBar != null;
355 // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
356 appBar.setCustomView(R.layout.url_app_bar);
357 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
359 // Initialize the `ForegroundColorSpans` and `StyleSpan` for highlighting `urlTextBox`. We have to use the deprecated `getColor()` until API >= 23.
360 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
361 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
362 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
364 // Get a handle for `urlTextBox`.
365 urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.url_edittext);
367 // Remove the formatting from `urlTextBar` when the user is editing the text.
368 urlTextBox.setOnFocusChangeListener(new View.OnFocusChangeListener() {
370 public void onFocusChange(View v, boolean hasFocus) {
371 if (hasFocus) { // The user is editing `urlTextBox`.
372 // Remove the highlighting.
373 urlTextBox.getText().removeSpan(redColorSpan);
374 urlTextBox.getText().removeSpan(initialGrayColorSpan);
375 urlTextBox.getText().removeSpan(finalGrayColorSpan);
376 } else { // The user has stopped editing `urlTextBox`.
377 // Reapply the highlighting.
383 // Set the `Go` button on the keyboard to load the URL in `urlTextBox`.
384 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
386 public boolean onKey(View v, int keyCode, KeyEvent event) {
387 // If the event is a key-down event on the `enter` button, load the URL.
388 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
389 // Load the URL into the mainWebView and consume the event.
391 loadUrlFromTextBox();
392 } catch (UnsupportedEncodingException e) {
395 // If the enter key was pressed, consume the event.
398 // If any other key was pressed, do not consume the event.
404 // Set `waitingForOrbotHTMLString`.
405 waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
407 // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
408 currentDomainName = "";
409 orbotStatus = "unknown";
410 waitingForOrbot = false;
412 // Create an Orbot status `BroadcastReceiver`.
413 BroadcastReceiver orbotStatusBroadcastReceiver = new BroadcastReceiver() {
415 public void onReceive(Context context, Intent intent) {
416 // Store the content of the status message in `orbotStatus`.
417 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
419 // If we are waiting on Orbot, load the website now that Orbot is connected.
420 if (orbotStatus.equals("ON") && waitingForOrbot) {
421 // Reset `waitingForOrbot`.
422 waitingForOrbot = false;
424 // Load `formattedUrlString
425 loadUrl(formattedUrlString);
430 // Register `orbotStatusBroadcastReceiver` on `this` context.
431 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
433 // Get handles for views that need to be accessed.
434 drawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout);
435 rootCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.root_coordinatorlayout);
436 mainWebViewRelativeLayout = (RelativeLayout) findViewById(R.id.main_webview_relativelayout);
437 mainWebView = (WebView) findViewById(R.id.main_webview);
438 findOnPageLinearLayout = (LinearLayout) findViewById(R.id.find_on_page_linearlayout);
439 findOnPageEditText = (EditText) findViewById(R.id.find_on_page_edittext);
440 fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.full_screen_video_framelayout);
441 urlAppBarRelativeLayout = (RelativeLayout) findViewById(R.id.url_app_bar_relativelayout);
442 favoriteIconImageView = (ImageView) findViewById(R.id.favorite_icon);
444 // Create a double-tap listener to toggle full-screen mode.
445 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
446 // Override `onDoubleTap()`. All other events are handled using the default settings.
448 public boolean onDoubleTap(MotionEvent event) {
449 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
450 // Toggle `inFullScreenBrowsingMode`.
451 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
453 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
454 // Hide the `appBar`.
457 // Hide the `BannerAd` in the free flavor.
458 if (BuildConfig.FLAVOR.contentEquals("free")) {
459 BannerAd.hideAd(adView);
462 // Modify the system bars.
463 if (hideSystemBarsOnFullscreen) { // Hide everything.
464 // Remove the translucent overlays.
465 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
467 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
468 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
470 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
471 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
472 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
474 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
476 // Set `rootCoordinatorLayout` to fill the whole screen.
477 rootCoordinatorLayout.setFitsSystemWindows(false);
478 } else { // Hide everything except the status and navigation bars.
479 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
480 rootCoordinatorLayout.setFitsSystemWindows(false);
482 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.
483 // Set the navigation bar to be translucent.
484 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
487 } else { // Switch to normal viewing mode.
488 // Show the `appBar`.
491 // Show the `BannerAd` in the free flavor.
492 if (BuildConfig.FLAVOR.contentEquals("free")) {
493 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
494 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
496 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
497 adView = findViewById(R.id.adview);
500 // Remove the translucent navigation bar flag if it is set.
501 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
503 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
504 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
506 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
507 rootCoordinatorLayout.setSystemUiVisibility(0);
509 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
510 rootCoordinatorLayout.setFitsSystemWindows(true);
513 // Consume the double-tap.
515 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
521 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
522 mainWebView.setOnTouchListener(new View.OnTouchListener() {
524 public boolean onTouch(View v, MotionEvent event) {
525 // Send the `event` to `gestureDetector`.
526 return gestureDetector.onTouchEvent(event);
530 // Update `findOnPageCountTextView`.
531 mainWebView.setFindListener(new WebView.FindListener() {
532 // Get a handle for `findOnPageCountTextView`.
533 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
536 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
537 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
538 // Set `findOnPageCountTextView` to `0/0`.
539 findOnPageCountTextView.setText(R.string.zero_of_zero);
540 } else if (isDoneCounting) { // There are matches.
541 // `activeMatchOrdinal` is zero-based.
542 int activeMatch = activeMatchOrdinal + 1;
544 // Set `findOnPageCountTextView`.
545 findOnPageCountTextView.setText(activeMatch + "/" + numberOfMatches);
550 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
551 findOnPageEditText.addTextChangedListener(new TextWatcher() {
553 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
558 public void onTextChanged(CharSequence s, int start, int before, int count) {
563 public void afterTextChanged(Editable s) {
564 // Search for the text in `mainWebView`.
565 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
569 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
570 findOnPageEditText.setOnKeyListener(new View.OnKeyListener() {
572 public boolean onKey(View v, int keyCode, KeyEvent event) {
573 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
574 // Hide the soft keyboard. `0` indicates no additional flags.
575 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
577 // Consume the event.
579 } else { // A different key was pressed.
580 // Do not consume the event.
586 // Implement swipe to refresh
587 swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refreshlayout);
588 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
589 swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
591 public void onRefresh() {
592 mainWebView.reload();
596 // `DrawerTitle` identifies the `DrawerLayout` in accessibility mode.
597 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
599 // Listen for touches on the navigation menu.
600 final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationview);
601 navigationView.setNavigationItemSelectedListener(this);
603 // 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.
604 final Menu navigationMenu = navigationView.getMenu();
605 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
606 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
607 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
609 // The `DrawerListener` allows us to update the Navigation Menu.
610 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
612 public void onDrawerSlide(View drawerView, float slideOffset) {
616 public void onDrawerOpened(View drawerView) {
620 public void onDrawerClosed(View drawerView) {
624 public void onDrawerStateChanged(int newState) {
625 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // The drawer is opening or closing.
626 // Update the `Back`, `Forward`, and `History` menu items.
627 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
628 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
629 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
631 // Hide the keyboard (if displayed) so we can see the navigation menu. `0` indicates no additional flags.
632 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
634 // Clear the focus from `urlTextBox` if it has it.
635 urlTextBox.clearFocus();
640 // drawerToggle creates the hamburger icon at the start of the AppBar.
641 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
643 // Initialize `adServerSet`.
644 final Set<String> adServersSet = new HashSet<>();
646 // Load the list of ad servers into memory.
648 // Load `pgl.yoyo.org_adservers.txt` into a `BufferedReader`.
649 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(getAssets().open("pgl.yoyo.org_adservers.txt")));
651 // Create a string for storing each ad server.
654 // Populate `adServersSet`.
655 while ((adServer = bufferedReader.readLine()) != null) {
656 adServersSet.add(adServer);
659 // Close `bufferedReader`.
660 bufferedReader.close();
661 } catch (IOException ioException) {
662 // We're pretty sure the asset exists, so we don't need to worry about the `IOException` ever being thrown.
665 mainWebView.setWebViewClient(new WebViewClient() {
666 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
667 // We have to use the deprecated `shouldOverrideUrlLoading` until API >= 24.
668 @SuppressWarnings("deprecation")
670 public boolean shouldOverrideUrlLoading(WebView view, String url) {
671 if (url.startsWith("mailto:")) { // Load the URL in an external email program because it begins with `mailto:`.
672 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
673 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
675 // Parse the url and set it as the data for the `Intent`.
676 emailIntent.setData(Uri.parse(url));
678 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
679 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
682 startActivity(emailIntent);
684 // Returning `true` indicates the application is handling the URL.
686 } else { // Load the URL in Privacy Browser.
687 // Apply the domain settings for the new URL.
688 applyDomainSettings(url);
690 // Returning `false` causes the current `WebView` to handle the URL and prevents it from adding redirects to the history list.
695 // Block ads. We have to use the deprecated `shouldInterceptRequest` until minimum API >= 21.
696 @SuppressWarnings("deprecation")
698 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
699 if (adBlockerEnabled) { // Block ads.
700 // Extract the host from `url`.
701 Uri requestUri = Uri.parse(url);
702 String requestHost = requestUri.getHost();
704 // Initialize a variable to track if this is an ad server.
705 boolean requestHostIsAdServer = false;
707 // Check all the subdomains of `requestHost` if it is not `null` against the ad server database.
708 if (requestHost != null) {
709 while (requestHost.contains(".") && !requestHostIsAdServer) { // Stop checking if we run out of `.` or if we already know that `requestHostIsAdServer` is `true`.
710 if (adServersSet.contains(requestHost)) {
711 requestHostIsAdServer = true;
714 // Strip out the lowest subdomain of `requestHost`.
715 requestHost = requestHost.substring(requestHost.indexOf(".") + 1);
719 if (requestHostIsAdServer) { // It is an ad server.
720 // Return an empty `WebResourceResponse`.
721 return new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
722 } else { // It is not an ad server.
723 // `return null` loads the requested resource.
726 } else { // Ad blocking is disabled.
727 // `return null` loads the requested resource.
732 // Update the URL in urlTextBox when the page starts to load.
734 public void onPageStarted(WebView view, String url, Bitmap favicon) {
735 // Check to see if we are waiting on Orbot.
736 if (!waitingForOrbot) { // We are not waiting on Orbot, so we need to process the URL.
737 // 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.
738 formattedUrlString = url;
740 // Display the formatted URL text.
741 urlTextBox.setText(formattedUrlString);
743 // Apply text highlighting to `urlTextBox`.
746 // Apply any custom domain settings if the URL was loaded by navigating history.
747 if (navigatingHistory) {
748 applyDomainSettings(url);
751 // 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.
756 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
758 public void onPageFinished(WebView view, String url) {
759 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
760 urlIsLoading = false;
762 // Clear the cache and history if Incognito Mode is enabled.
763 if (incognitoModeEnabled) {
764 // Clear the cache. `true` includes disk files.
765 mainWebView.clearCache(true);
767 // Clear the back/forward history.
768 mainWebView.clearHistory();
770 // Manually delete cache folders.
772 // Delete the main `cache` folder.
773 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
775 // 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`.
776 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
777 } catch (IOException e) {
778 // Do nothing if an error is thrown.
782 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
783 if (!waitingForOrbot) {
784 // Check to see if `WebView` has set `url` to be `about:blank`.
785 if (url.equals("about:blank")) { // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
786 // Set `formattedUrlString` to `""`.
787 formattedUrlString = "";
789 urlTextBox.setText(formattedUrlString);
791 // Request focus for `urlTextBox`.
792 urlTextBox.requestFocus();
794 // Display the keyboard.
795 inputMethodManager.showSoftInput(urlTextBox, 0);
797 // Apply the domain settings. This clears any settings from the previous domain.
798 applyDomainSettings(formattedUrlString);
799 } else { // `WebView` has loaded a webpage.
800 // Set `formattedUrlString`.
801 formattedUrlString = url;
803 // Only update `urlTextBox` if the user is not typing in it.
804 if (!urlTextBox.hasFocus()) {
805 // Display the formatted URL text.
806 urlTextBox.setText(formattedUrlString);
808 // Apply text highlighting to `urlTextBox`.
813 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
814 sslCertificate = mainWebView.getCertificate();
816 // 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.
817 if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate) {
818 // Initialize the current SSL certificate variables.
819 String currentWebsiteIssuedToCName = "";
820 String currentWebsiteIssuedToOName = "";
821 String currentWebsiteIssuedToUName = "";
822 String currentWebsiteIssuedByCName = "";
823 String currentWebsiteIssuedByOName = "";
824 String currentWebsiteIssuedByUName = "";
825 Date currentWebsiteSslStartDate = null;
826 Date currentWebsiteSslEndDate = null;
829 // Extract the individual pieces of information from the current website SSL certificate if it is not null.
830 if (sslCertificate != null) {
831 currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
832 currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
833 currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
834 currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
835 currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
836 currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
837 currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
838 currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
841 // 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`.
842 String currentWebsiteSslStartDateString = "";
843 String currentWebsiteSslEndDateString = "";
844 String pinnedDomainSslStartDateString = "";
845 String pinnedDomainSslEndDateString = "";
847 // Convert the `Dates` to `Strings` if they are not `null`.
848 if (currentWebsiteSslStartDate != null) {
849 currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
852 if (currentWebsiteSslEndDate != null) {
853 currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
856 if (pinnedDomainSslStartDate != null) {
857 pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
860 if (pinnedDomainSslEndDate != null) {
861 pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
864 // Check to see if the pinned SSL certificate matches the current website certificate.
865 if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) || !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) ||
866 !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) || !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
867 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) { // The pinned SSL certificate doesn't match the current domain certificate.
868 //Display the pinned SSL certificate mismatch `AlertDialog`.
869 AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
870 pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.ssl_certificate_mismatch));
876 // Handle SSL Certificate errors.
878 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
879 // Get the current website SSL certificate.
880 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
882 // Extract the individual pieces of information from the current website SSL certificate.
883 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
884 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
885 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
886 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
887 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
888 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
889 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
890 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
892 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
893 if (pinnedDomainSslCertificate &&
894 currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) && currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) &&
895 currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) && currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
896 currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) { // An SSL certificate is pinned and matches the current domain certificate.
897 // Proceed to the website without displaying an error.
899 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
900 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
901 sslErrorHandler = handler;
903 // Display the SSL error `AlertDialog`.
904 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
905 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.ssl_certificate_error));
910 // Get a handle for the progress bar.
911 final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress_bar);
913 mainWebView.setWebChromeClient(new WebChromeClient() {
914 // Update the progress bar when a page is loading.
916 public void onProgressChanged(WebView view, int progress) {
917 progressBar.setProgress(progress);
918 if (progress < 100) {
919 progressBar.setVisibility(View.VISIBLE);
921 progressBar.setVisibility(View.GONE);
923 //Stop the `SwipeToRefresh` indicator if it is running
924 swipeRefreshLayout.setRefreshing(false);
928 // Set the favorite icon when it changes.
930 public void onReceivedIcon(WebView view, Bitmap icon) {
931 // Only update the favorite icon if the website has finished loading.
932 if (progressBar.getVisibility() == View.GONE) {
933 // Save a copy of the favorite icon.
934 favoriteIconBitmap = icon;
936 // Place the favorite icon in the appBar.
937 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
941 // Save a copy of the title when it changes.
943 public void onReceivedTitle(WebView view, String title) {
944 // Save a copy of the title.
945 webViewTitle = title;
948 // Enter full screen video
950 public void onShowCustomView(View view, CustomViewCallback callback) {
951 // Pause the ad if this is the free flavor.
952 if (BuildConfig.FLAVOR.contentEquals("free")) {
953 BannerAd.pauseAd(adView);
956 // Remove the translucent overlays.
957 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
959 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
960 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
962 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
963 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
964 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
966 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
968 // Set `rootCoordinatorLayout` to fill the entire screen.
969 rootCoordinatorLayout.setFitsSystemWindows(false);
971 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
972 fullScreenVideoFrameLayout.addView(view);
973 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
976 // Exit full screen video
977 public void onHideCustomView() {
978 // Hide `fullScreenVideoFrameLayout`.
979 fullScreenVideoFrameLayout.removeAllViews();
980 fullScreenVideoFrameLayout.setVisibility(View.GONE);
982 // Add the translucent status flag. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
983 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
985 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars. This also clears the `SYSTEM_UI` flags.
986 rootCoordinatorLayout.setFitsSystemWindows(true);
988 // Show the ad if this is the free flavor.
989 if (BuildConfig.FLAVOR.contentEquals("free")) {
990 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
991 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
993 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
994 adView = findViewById(R.id.adview);
999 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
1000 registerForContextMenu(mainWebView);
1002 // Allow the downloading of files.
1003 mainWebView.setDownloadListener(new DownloadListener() {
1005 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
1006 // Show the `DownloadFileDialog` `AlertDialog` and name this instance `@string/download`.
1007 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
1008 downloadFileDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1012 // Allow pinch to zoom.
1013 mainWebView.getSettings().setBuiltInZoomControls(true);
1015 // Hide zoom controls.
1016 mainWebView.getSettings().setDisplayZoomControls(false);
1018 // Set `mainWebView` to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
1019 mainWebView.getSettings().setUseWideViewPort(true);
1021 // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
1022 mainWebView.getSettings().setLoadWithOverviewMode(true);
1024 // Explicitly disable geolocation.
1025 mainWebView.getSettings().setGeolocationEnabled(false);
1027 // Initialize cookieManager.
1028 cookieManager = CookieManager.getInstance();
1030 // 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).
1031 customHeaders.put("X-Requested-With", "");
1033 // 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.
1034 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
1036 // Get the intent that started the app.
1037 final Intent launchingIntent = getIntent();
1039 // Extract the launching intent data as `launchingIntentUriData`.
1040 final Uri launchingIntentUriData = launchingIntent.getData();
1042 // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
1043 if (launchingIntentUriData != null) {
1044 formattedUrlString = launchingIntentUriData.toString();
1047 // Get a handle for the `Runtime`.
1048 privacyBrowserRuntime = Runtime.getRuntime();
1050 // Store the application's private data directory.
1051 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`.
1053 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
1054 inFullScreenBrowsingMode = false;
1056 // Initialize AdView for the free flavor.
1057 adView = findViewById(R.id.adview);
1059 // Initialize the privacy settings variables.
1060 javaScriptEnabled = false;
1061 firstPartyCookiesEnabled = false;
1062 thirdPartyCookiesEnabled = false;
1063 domStorageEnabled = false;
1064 saveFormDataEnabled = false;
1066 // Initialize `webViewTitle`.
1067 webViewTitle = getString(R.string.no_title);
1069 // Initialize `favoriteIconBitmap`. We have to use `ContextCompat` until API >= 21.
1070 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
1071 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
1072 favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
1074 // If the favorite icon is null, load the default.
1075 if (favoriteIconBitmap == null) {
1076 favoriteIconBitmap = favoriteIconDefaultBitmap;
1079 // Apply the app settings from the shared preferences.
1082 // Load `formattedUrlString` if we are not waiting for Orbot to connect.
1083 if (!waitingForOrbot) {
1084 loadUrl(formattedUrlString);
1089 protected void onNewIntent(Intent intent) {
1090 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1093 if (intent.getData() != null) {
1094 // Get the intent data and convert it to a string.
1095 final Uri intentUriData = intent.getData();
1096 formattedUrlString = intentUriData.toString();
1099 // Close the navigation drawer if it is open.
1100 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1101 drawerLayout.closeDrawer(GravityCompat.START);
1104 // Load the website.
1105 loadUrl(formattedUrlString);
1107 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1108 mainWebView.requestFocus();
1112 public void onRestart() {
1115 // Apply the app settings, which may have been changed in `SettingsActivity`.
1118 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1119 updatePrivacyIcons(true);
1121 // Set the display webpage images mode.
1122 setDisplayWebpageImages();
1124 // Reload the webpage if displaying of images has been disabled in `SettingsFragment`.
1125 if (reloadOnRestartBoolean) {
1126 // Reload `mainWebView`.
1127 mainWebView.reload();
1129 // Reset `reloadOnRestartBoolean`.
1130 reloadOnRestartBoolean = false;
1134 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1136 public void onResume() {
1139 // Resume JavaScript (if enabled).
1140 mainWebView.resumeTimers();
1142 // Resume `mainWebView`.
1143 mainWebView.onResume();
1145 // Resume the adView for the free flavor.
1146 if (BuildConfig.FLAVOR.contentEquals("free")) {
1147 BannerAd.resumeAd(adView);
1152 public void onPause() {
1153 // Pause `mainWebView`.
1154 mainWebView.onPause();
1156 // Stop all JavaScript.
1157 mainWebView.pauseTimers();
1159 // Pause the adView or it will continue to consume resources in the background on the free flavor.
1160 if (BuildConfig.FLAVOR.contentEquals("free")) {
1161 BannerAd.pauseAd(adView);
1168 public boolean onCreateOptionsMenu(Menu menu) {
1169 // Inflate the menu; this adds items to the action bar if it is present.
1170 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1172 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1175 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1176 updatePrivacyIcons(false);
1178 // Get handles for the menu items.
1179 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1180 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1181 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1182 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1184 // Only display third-party cookies if SDK >= 21
1185 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1187 // Get the shared preference values. `this` references the current context.
1188 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1190 // Set the status of the additional app bar icons. The default is `false`.
1191 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
1192 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1193 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1194 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1195 } else { //Do not display the additional icons.
1196 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1197 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1198 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1205 public boolean onPrepareOptionsMenu(Menu menu) {
1206 // Get handles for the menu items.
1207 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1208 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1209 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1210 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1211 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1212 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1213 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);
1214 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1215 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1216 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1218 // Set the status of the menu item checkboxes.
1219 toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1220 toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1221 toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1222 toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);
1223 displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1225 // Enable third-party cookies if first-party cookies are enabled.
1226 toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1228 // Enable `DOM Storage` if JavaScript is enabled.
1229 toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
1231 // Enable `Clear Cookies` if there are any.
1232 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1234 // Get a count of the number of files in the `Local Storage` directory.
1235 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1236 int localStorageDirectoryNumberOfFiles = 0;
1237 if (localStorageDirectory.exists()) {
1238 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1241 // Get a count of the number of files in the `IndexedDB` directory.
1242 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1243 int indexedDBDirectoryNumberOfFiles = 0;
1244 if (indexedDBDirectory.exists()) {
1245 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1248 // Enable `Clear DOM Storage` if there is any.
1249 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1251 // Enable `Clear Form Data` is there is any.
1252 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1253 clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
1255 // Initialize font size variables.
1256 int fontSize = mainWebView.getSettings().getTextZoom();
1257 String fontSizeTitle;
1258 MenuItem selectedFontSizeMenuItem;
1260 // Prepare the font size title and current size menu item.
1263 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.twenty_five_percent);
1264 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1268 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.fifty_percent);
1269 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1273 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.seventy_five_percent);
1274 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1278 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
1279 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1283 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_twenty_five_percent);
1284 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1288 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_fifty_percent);
1289 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1293 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_seventy_five_percent);
1294 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1298 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.two_hundred_percent);
1299 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1303 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
1304 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1308 // Set the font size title and select the current size menu item.
1309 fontSizeMenuItem.setTitle(fontSizeTitle);
1310 selectedFontSizeMenuItem.setChecked(true);
1312 // Only show `Refresh` if `swipeToRefresh` is disabled.
1313 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
1315 // Run all the other default commands.
1316 super.onPrepareOptionsMenu(menu);
1318 // `return true` displays the menu.
1323 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1324 @SuppressLint("SetJavaScriptEnabled")
1325 // removeAllCookies is deprecated, but it is required for API < 21.
1326 @SuppressWarnings("deprecation")
1327 public boolean onOptionsItemSelected(MenuItem menuItem) {
1328 int menuItemId = menuItem.getItemId();
1330 // Set the commands that relate to the menu entries.
1331 switch (menuItemId) {
1332 case R.id.toggle_javascript:
1333 // Switch the status of javaScriptEnabled.
1334 javaScriptEnabled = !javaScriptEnabled;
1336 // Apply the new JavaScript status.
1337 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1339 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1340 updatePrivacyIcons(true);
1342 // Display a `Snackbar`.
1343 if (javaScriptEnabled) { // JavaScrip is enabled.
1344 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1345 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
1346 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1347 } else { // Privacy mode.
1348 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1351 // Reload the WebView.
1352 mainWebView.reload();
1355 case R.id.toggle_first_party_cookies:
1356 // Switch the status of firstPartyCookiesEnabled.
1357 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1359 // Update the menu checkbox.
1360 menuItem.setChecked(firstPartyCookiesEnabled);
1362 // Apply the new cookie status.
1363 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1365 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1366 updatePrivacyIcons(true);
1368 // Display a `Snackbar`.
1369 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1370 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1371 } else if (javaScriptEnabled){ // JavaScript is still enabled.
1372 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1373 } else { // Privacy mode.
1374 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1377 // Reload the WebView.
1378 mainWebView.reload();
1381 case R.id.toggle_third_party_cookies:
1382 if (Build.VERSION.SDK_INT >= 21) {
1383 // Switch the status of thirdPartyCookiesEnabled.
1384 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1386 // Update the menu checkbox.
1387 menuItem.setChecked(thirdPartyCookiesEnabled);
1389 // Apply the new cookie status.
1390 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1392 // Display a `Snackbar`.
1393 if (thirdPartyCookiesEnabled) {
1394 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1396 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1399 // Reload the WebView.
1400 mainWebView.reload();
1401 } // Else do nothing because SDK < 21.
1404 case R.id.toggle_dom_storage:
1405 // Switch the status of domStorageEnabled.
1406 domStorageEnabled = !domStorageEnabled;
1408 // Update the menu checkbox.
1409 menuItem.setChecked(domStorageEnabled);
1411 // Apply the new DOM Storage status.
1412 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1414 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1415 updatePrivacyIcons(true);
1417 // Display a `Snackbar`.
1418 if (domStorageEnabled) {
1419 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1421 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1424 // Reload the WebView.
1425 mainWebView.reload();
1428 case R.id.toggle_save_form_data:
1429 // Switch the status of saveFormDataEnabled.
1430 saveFormDataEnabled = !saveFormDataEnabled;
1432 // Update the menu checkbox.
1433 menuItem.setChecked(saveFormDataEnabled);
1435 // Apply the new form data status.
1436 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1438 // Display a `Snackbar`.
1439 if (saveFormDataEnabled) {
1440 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1442 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1445 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1446 updatePrivacyIcons(true);
1448 // Reload the WebView.
1449 mainWebView.reload();
1452 case R.id.clear_cookies:
1453 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1454 .setAction(R.string.undo, new View.OnClickListener() {
1456 public void onClick(View v) {
1457 // Do nothing because everything will be handled by `onDismissed()` below.
1460 .addCallback(new Snackbar.Callback() {
1462 public void onDismissed(Snackbar snackbar, int event) {
1464 // The user pushed the `Undo` button.
1465 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1469 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1471 // `cookieManager.removeAllCookie()` varies by SDK.
1472 if (Build.VERSION.SDK_INT < 21) {
1473 cookieManager.removeAllCookie();
1475 // `null` indicates no callback.
1476 cookieManager.removeAllCookies(null);
1484 case R.id.clear_dom_storage:
1485 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1486 .setAction(R.string.undo, new View.OnClickListener() {
1488 public void onClick(View v) {
1489 // Do nothing because everything will be handled by `onDismissed()` below.
1492 .addCallback(new Snackbar.Callback() {
1494 public void onDismissed(Snackbar snackbar, int event) {
1496 // The user pushed the `Undo` button.
1497 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1501 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1503 // Delete the DOM Storage.
1504 WebStorage webStorage = WebStorage.getInstance();
1505 webStorage.deleteAllData();
1507 // Manually remove `IndexedDB` if it exists.
1509 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1510 } catch (IOException e) {
1511 // Do nothing if an error is thrown.
1519 case R.id.clear_form_data:
1520 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1521 .setAction(R.string.undo, new View.OnClickListener() {
1523 public void onClick(View v) {
1524 // Do nothing because everything will be handled by `onDismissed()` below.
1527 .addCallback(new Snackbar.Callback() {
1529 public void onDismissed(Snackbar snackbar, int event) {
1531 // The user pushed the `Undo` button.
1532 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1536 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1538 // Delete the form data.
1539 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1540 mainWebViewDatabase.clearFormData();
1547 case R.id.font_size_twenty_five_percent:
1548 mainWebView.getSettings().setTextZoom(25);
1551 case R.id.font_size_fifty_percent:
1552 mainWebView.getSettings().setTextZoom(50);
1555 case R.id.font_size_seventy_five_percent:
1556 mainWebView.getSettings().setTextZoom(75);
1559 case R.id.font_size_one_hundred_percent:
1560 mainWebView.getSettings().setTextZoom(100);
1563 case R.id.font_size_one_hundred_twenty_five_percent:
1564 mainWebView.getSettings().setTextZoom(125);
1567 case R.id.font_size_one_hundred_fifty_percent:
1568 mainWebView.getSettings().setTextZoom(150);
1571 case R.id.font_size_one_hundred_seventy_five_percent:
1572 mainWebView.getSettings().setTextZoom(175);
1575 case R.id.font_size_two_hundred_percent:
1576 mainWebView.getSettings().setTextZoom(200);
1579 case R.id.display_images:
1580 if (mainWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1581 mainWebView.getSettings().setLoadsImagesAutomatically(false);
1582 mainWebView.reload();
1583 } else { // Images are not currently loaded automatically.
1584 mainWebView.getSettings().setLoadsImagesAutomatically(true);
1587 // Set `onTheFlyDisplayImagesSet`.
1588 onTheFlyDisplayImagesSet = true;
1592 // Setup the share string.
1593 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
1595 // Create the share intent.
1596 Intent shareIntent = new Intent();
1597 shareIntent.setAction(Intent.ACTION_SEND);
1598 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1599 shareIntent.setType("text/plain");
1602 startActivity(Intent.createChooser(shareIntent, "Share URL"));
1605 case R.id.find_on_page:
1606 // Hide the URL app bar.
1607 supportAppBar.setVisibility(View.GONE);
1609 // Show the Find on Page `RelativeLayout`.
1610 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1612 // 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
1613 findOnPageEditText.postDelayed(new Runnable() {
1617 // Set the focus on `findOnPageEditText`.
1618 findOnPageEditText.requestFocus();
1620 // Display the keyboard. `0` sets no input flags.
1621 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1627 // Get a `PrintManager` instance.
1628 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1630 // Convert `mainWebView` to `printDocumentAdapter`.
1631 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
1633 // Print the document. The print attributes are `null`.
1634 printManager.print(getResources().getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1637 case R.id.add_to_homescreen:
1638 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
1639 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
1640 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.create_shortcut));
1642 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
1646 mainWebView.reload();
1650 // Don't consume the event.
1651 return super.onOptionsItemSelected(menuItem);
1655 // removeAllCookies is deprecated, but it is required for API < 21.
1656 @SuppressWarnings("deprecation")
1658 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1659 int menuItemId = menuItem.getItemId();
1661 switch (menuItemId) {
1667 if (mainWebView.canGoBack()) {
1668 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1669 navigatingHistory = true;
1671 // Load the previous website in the history.
1672 mainWebView.goBack();
1677 if (mainWebView.canGoForward()) {
1678 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1679 navigatingHistory = true;
1681 // Load the next website in the history.
1682 mainWebView.goForward();
1687 // Get the `WebBackForwardList`.
1688 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
1690 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
1691 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
1692 urlHistoryDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.history));
1695 case R.id.bookmarks:
1696 // Launch BookmarksActivity.
1697 Intent bookmarksIntent = new Intent(this, BookmarksActivity.class);
1698 startActivity(bookmarksIntent);
1701 case R.id.downloads:
1702 // Launch the system Download Manager.
1703 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1705 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1706 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1708 startActivity(downloadManagerIntent);
1712 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1713 currentDomainName = "";
1715 // Launch `SettingsActivity`.
1716 Intent settingsIntent = new Intent(this, SettingsActivity.class);
1717 startActivity(settingsIntent);
1721 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1722 currentDomainName = "";
1724 // Launch `DomainsActivity`.
1725 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1726 startActivity(domainsIntent);
1730 // Launch `GuideActivity`.
1731 Intent guideIntent = new Intent(this, GuideActivity.class);
1732 startActivity(guideIntent);
1736 // Launch `AboutActivity`.
1737 Intent aboutIntent = new Intent(this, AboutActivity.class);
1738 startActivity(aboutIntent);
1741 case R.id.clearAndExit:
1742 // Get a handle for `sharedPreferences`. `this` references the current context.
1743 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1745 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
1748 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
1749 // The command to remove cookies changed slightly in API 21.
1750 if (Build.VERSION.SDK_INT >= 21) {
1751 cookieManager.removeAllCookies(null);
1753 cookieManager.removeAllCookie();
1756 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1758 // We have to use two commands because `Runtime.exec()` does not like `*`.
1759 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
1760 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
1761 } catch (IOException e) {
1762 // Do nothing if an error is thrown.
1766 // Clear DOM storage.
1767 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
1768 // Ask `WebStorage` to clear the DOM storage.
1769 WebStorage webStorage = WebStorage.getInstance();
1770 webStorage.deleteAllData();
1772 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1774 // We have to use a `String[]` because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1775 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1777 // We have to use multiple commands because `Runtime.exec()` does not like `*`.
1778 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1779 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1780 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1781 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1782 } catch (IOException e) {
1783 // Do nothing if an error is thrown.
1788 if (clearEverything || sharedPreferences.getBoolean("clear_form_data", true)) {
1789 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1790 webViewDatabase.clearFormData();
1792 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1794 // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1795 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
1796 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
1797 } catch (IOException e) {
1798 // Do nothing if an error is thrown.
1803 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
1804 // `true` includes disk files.
1805 mainWebView.clearCache(true);
1807 // Manually delete the cache directories.
1809 // Delete the main cache directory.
1810 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1812 // 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.
1813 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1814 } catch (IOException e) {
1815 // Do nothing if an error is thrown.
1819 // Clear SSL certificate preferences.
1820 mainWebView.clearSslPreferences();
1822 // Clear the back/forward history.
1823 mainWebView.clearHistory();
1825 // Clear `formattedUrlString`.
1826 formattedUrlString = null;
1828 // Clear `customHeaders`.
1829 customHeaders.clear();
1831 // Detach all views from `mainWebViewRelativeLayout`.
1832 mainWebViewRelativeLayout.removeAllViews();
1834 // Destroy the internal state of `mainWebView`.
1835 mainWebView.destroy();
1837 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
1838 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
1839 if (clearEverything) {
1841 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
1842 } catch (IOException e) {
1843 // Do nothing if an error is thrown.
1847 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
1848 if (Build.VERSION.SDK_INT >= 21) {
1849 finishAndRemoveTask();
1854 // Remove the terminated program from RAM. The status code is `0`.
1859 // Close the navigation drawer.
1860 drawerLayout.closeDrawer(GravityCompat.START);
1865 public void onPostCreate(Bundle savedInstanceState) {
1866 super.onPostCreate(savedInstanceState);
1868 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
1869 drawerToggle.syncState();
1873 public void onConfigurationChanged(Configuration newConfig) {
1874 super.onConfigurationChanged(newConfig);
1876 // Reload the ad for the free flavor if we are not in full screen mode.
1877 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
1879 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1881 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1882 adView = findViewById(R.id.adview);
1885 // `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
1886 // ActivityCompat.invalidateOptionsMenu(this);
1890 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
1891 // Store the `HitTestResult`.
1892 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
1895 final String imageUrl;
1896 final String linkUrl;
1898 // Get a handle for the `ClipboardManager`.
1899 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
1901 switch (hitTestResult.getType()) {
1902 // `SRC_ANCHOR_TYPE` is a link.
1903 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1904 // Get the target URL.
1905 linkUrl = hitTestResult.getExtra();
1907 // Set the target URL as the title of the `ContextMenu`.
1908 menu.setHeaderTitle(linkUrl);
1910 // Add a `Load URL` entry.
1911 menu.add(R.string.load_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1913 public boolean onMenuItemClick(MenuItem item) {
1919 // Add a `Copy URL` entry.
1920 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1922 public boolean onMenuItemClick(MenuItem item) {
1923 // Save the link URL in a `ClipData`.
1924 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), linkUrl);
1926 // Set the `ClipData` as the clipboard's primary clip.
1927 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
1932 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1933 menu.add(R.string.cancel);
1936 case WebView.HitTestResult.EMAIL_TYPE:
1937 // Get the target URL.
1938 linkUrl = hitTestResult.getExtra();
1940 // Set the target URL as the title of the `ContextMenu`.
1941 menu.setHeaderTitle(linkUrl);
1943 // Add a `Write Email` entry.
1944 menu.add(R.string.write_email).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1946 public boolean onMenuItemClick(MenuItem item) {
1947 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1948 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1950 // Parse the url and set it as the data for the `Intent`.
1951 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
1953 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
1954 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1957 startActivity(emailIntent);
1962 // Add a `Copy Email Address` entry.
1963 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1965 public boolean onMenuItemClick(MenuItem item) {
1966 // Save the email address in a `ClipData`.
1967 ClipData srcEmailTypeClipData = ClipData.newPlainText(getResources().getString(R.string.email_address), linkUrl);
1969 // Set the `ClipData` as the clipboard's primary clip.
1970 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
1975 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1976 menu.add(R.string.cancel);
1979 // `IMAGE_TYPE` is an image.
1980 case WebView.HitTestResult.IMAGE_TYPE:
1981 // Get the image URL.
1982 imageUrl = hitTestResult.getExtra();
1984 // Set the image URL as the title of the `ContextMenu`.
1985 menu.setHeaderTitle(imageUrl);
1987 // Add a `View Image` entry.
1988 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1990 public boolean onMenuItemClick(MenuItem item) {
1996 // Add a `Download Image` entry.
1997 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1999 public boolean onMenuItemClick(MenuItem item) {
2000 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
2001 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2002 downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
2007 // Add a `Copy URL` entry.
2008 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2010 public boolean onMenuItemClick(MenuItem item) {
2011 // Save the image URL in a `ClipData`.
2012 ClipData srcImageTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
2014 // Set the `ClipData` as the clipboard's primary clip.
2015 clipboardManager.setPrimaryClip(srcImageTypeClipData);
2020 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2021 menu.add(R.string.cancel);
2025 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2026 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2027 // Get the image URL.
2028 imageUrl = hitTestResult.getExtra();
2030 // Set the image URL as the title of the `ContextMenu`.
2031 menu.setHeaderTitle(imageUrl);
2033 // Add a `View Image` entry.
2034 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2036 public boolean onMenuItemClick(MenuItem item) {
2042 // Add a `Download Image` entry.
2043 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2045 public boolean onMenuItemClick(MenuItem item) {
2046 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
2047 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2048 downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
2053 // Add a `Copy URL` entry.
2054 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2056 public boolean onMenuItemClick(MenuItem item) {
2057 // Save the image URL in a `ClipData`.
2058 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
2060 // Set the `ClipData` as the clipboard's primary clip.
2061 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2066 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2067 menu.add(R.string.cancel);
2073 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
2074 // Get shortcutNameEditText from the alert dialog.
2075 EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
2077 // Create the bookmark shortcut based on formattedUrlString.
2078 Intent bookmarkShortcut = new Intent();
2079 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
2080 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
2082 // Place the bookmark shortcut on the home screen.
2083 Intent placeBookmarkShortcut = new Intent();
2084 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
2085 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
2086 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIconBitmap);
2087 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
2088 sendBroadcast(placeBookmarkShortcut);
2092 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
2093 // Download the image if it has an HTTP or HTTPS URI.
2094 if (imageUrl.startsWith("http")) {
2095 // Get a handle for the system `DOWNLOAD_SERVICE`.
2096 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2098 // Parse `imageUrl`.
2099 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
2101 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
2102 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2103 if (firstPartyCookiesEnabled) {
2104 // Get the cookies for `imageUrl`.
2105 String cookies = cookieManager.getCookie(imageUrl);
2107 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2108 downloadRequest.addRequestHeader("Cookie", cookies);
2111 // Get the file name from `dialogFragment`.
2112 EditText downloadImageNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_image_name);
2113 String imageName = downloadImageNameEditText.getText().toString();
2115 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
2116 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `imageName`.
2117 downloadRequest.setDestinationInExternalFilesDir(this, "/", imageName);
2118 } else { // Only set the title using `imageName`.
2119 downloadRequest.setTitle(imageName);
2122 // Allow `MediaScanner` to index the download if it is a media file.
2123 downloadRequest.allowScanningByMediaScanner();
2125 // Add the URL as the description for the download.
2126 downloadRequest.setDescription(imageUrl);
2128 // Show the download notification after the download is completed.
2129 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2131 // Initiate the download.
2132 downloadManager.enqueue(downloadRequest);
2133 } else { // The image is not an HTTP or HTTPS URI.
2134 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
2139 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
2140 // Download the file if it has an HTTP or HTTPS URI.
2141 if (downloadUrl.startsWith("http")) {
2143 // Get a handle for the system `DOWNLOAD_SERVICE`.
2144 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2146 // Parse `downloadUrl`.
2147 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
2149 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
2150 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2151 if (firstPartyCookiesEnabled) {
2152 // Get the cookies for `downloadUrl`.
2153 String cookies = cookieManager.getCookie(downloadUrl);
2155 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2156 downloadRequest.addRequestHeader("Cookie", cookies);
2159 // Get the file name from `dialogFragment`.
2160 EditText downloadFileNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_file_name);
2161 String fileName = downloadFileNameEditText.getText().toString();
2163 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
2164 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download location to `/sdcard/Android/data/com.stoutner.privacybrowser.standard/files` named `fileName`.
2165 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
2166 } else { // Only set the title using `fileName`.
2167 downloadRequest.setTitle(fileName);
2170 // Allow `MediaScanner` to index the download if it is a media file.
2171 downloadRequest.allowScanningByMediaScanner();
2173 // Add the URL as the description for the download.
2174 downloadRequest.setDescription(downloadUrl);
2176 // Show the download notification after the download is completed.
2177 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2179 // Initiate the download.
2180 downloadManager.enqueue(downloadRequest);
2181 } else { // The download is not an HTTP or HTTPS URI.
2182 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
2186 public void viewSslCertificate(View view) {
2187 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
2188 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
2189 viewSslCertificateDialogFragment.show(getFragmentManager(), getResources().getString(R.string.view_ssl_certificate));
2193 public void onSslErrorCancel() {
2194 sslErrorHandler.cancel();
2198 public void onSslErrorProceed() {
2199 sslErrorHandler.proceed();
2203 public void onSslMismatchBack() {
2204 if (mainWebView.canGoBack()) { // There is a back page in the history.
2205 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2206 navigatingHistory = true;
2209 mainWebView.goBack();
2210 } else { // There are no pages to go back to.
2211 // Load a blank page
2217 public void onSslMismatchProceed() {
2218 // Do not check the pinned SSL certificate for this domain again until the domain changes.
2219 ignorePinnedSslCertificate = true;
2223 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
2224 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2225 navigatingHistory = true;
2227 // Load the history entry.
2228 mainWebView.goBackOrForward(moveBackOrForwardSteps);
2232 public void onClearHistory() {
2233 // Clear the history.
2234 mainWebView.clearHistory();
2237 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
2239 public void onBackPressed() {
2240 // Close the navigation drawer if it is available. GravityCompat.START is the drawer on the left on Left-to-Right layout text.
2241 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
2242 drawerLayout.closeDrawer(GravityCompat.START);
2244 // Load the previous URL if available.
2245 if (mainWebView.canGoBack()) {
2246 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2247 navigatingHistory = true;
2250 mainWebView.goBack();
2252 // Pass `onBackPressed()` to the system.
2253 super.onBackPressed();
2258 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
2259 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
2260 String unformattedUrlString = urlTextBox.getText().toString().trim();
2262 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
2263 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
2264 // Add `http://` at the beginning if it is missing. Otherwise the app will segfault.
2265 if (!unformattedUrlString.startsWith("http")) {
2266 unformattedUrlString = "http://" + unformattedUrlString;
2269 // Initialize `unformattedUrl`.
2270 URL unformattedUrl = null;
2272 // 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.
2274 unformattedUrl = new URL(unformattedUrlString);
2275 } catch (MalformedURLException e) {
2276 e.printStackTrace();
2279 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2280 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2281 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2282 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2283 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2284 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2287 Uri.Builder formattedUri = new Uri.Builder();
2288 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2290 // Decode `formattedUri` as a `String` in `UTF-8`.
2291 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
2293 // Sanitize the search input and convert it to a search.
2294 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2296 // Add the base search URL.
2297 formattedUrlString = searchURL + encodedUrlString;
2300 loadUrl(formattedUrlString);
2302 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
2303 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2307 private void loadUrl(String url) {
2308 // Apply any custom domain settings.
2309 applyDomainSettings(url);
2312 mainWebView.loadUrl(url, customHeaders);
2314 // Set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
2315 urlIsLoading = true;
2318 public void findPreviousOnPage(View view) {
2319 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
2320 mainWebView.findNext(false);
2323 public void findNextOnPage(View view) {
2324 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2325 mainWebView.findNext(true);
2328 public void closeFindOnPage(View view) {
2329 // Delete the contents of `find_on_page_edittext`.
2330 findOnPageEditText.setText(null);
2332 // Clear the highlighted phrases.
2333 mainWebView.clearMatches();
2335 // Hide the Find on Page `RelativeLayout`.
2336 findOnPageLinearLayout.setVisibility(View.GONE);
2338 // Show the URL app bar.
2339 supportAppBar.setVisibility(View.VISIBLE);
2341 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
2342 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2345 private void applyAppSettings() {
2346 // Get a handle for `sharedPreferences`. `this` references the current context.
2347 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2349 // Store the values from `sharedPreferences` in variables.
2350 String homepageString = sharedPreferences.getString("homepage", "https://start.duckduckgo.com");
2351 String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
2352 String torSearchString = sharedPreferences.getString("tor_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
2353 String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
2354 String searchString = sharedPreferences.getString("search", "https://duckduckgo.com/html/?q=");
2355 String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
2356 adBlockerEnabled = sharedPreferences.getBoolean("block_ads", true);
2357 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
2358 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
2359 boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
2360 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
2361 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
2362 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
2363 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh", false);
2364 displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
2366 // Set the homepage, search, and proxy options.
2367 if (proxyThroughOrbot) { // Set the Tor options.
2368 // Set `torHomepageString` as `homepage`.
2369 homepage = torHomepageString;
2371 // If formattedUrlString is null assign the homepage to it.
2372 if (formattedUrlString == null) {
2373 formattedUrlString = homepage;
2376 // Set the search URL.
2377 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
2378 searchURL = torSearchCustomURLString;
2379 } else { // Use the string from the pre-built list.
2380 searchURL = torSearchString;
2383 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
2384 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
2386 // Set the `appBar` background to indicate proxying through Orbot is enabled. `this` refers to the context.
2388 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
2390 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
2393 // Display a message to the user if we are waiting on Orbot.
2394 if (!orbotStatus.equals("ON")) {
2395 // Set `waitingForOrbot`.
2396 waitingForOrbot = true;
2398 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
2399 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
2401 } else { // Set the non-Tor options.
2402 // Set `homepageString` as `homepage`.
2403 homepage = homepageString;
2405 // If formattedUrlString is null assign the homepage to it.
2406 if (formattedUrlString == null) {
2407 formattedUrlString = homepage;
2410 // Set the search URL.
2411 if (searchString.equals("Custom URL")) { // Get the custom URL string.
2412 searchURL = searchCustomURLString;
2413 } else { // Use the string from the pre-built list.
2414 searchURL = searchString;
2417 // Reset the proxy to default. The host is `""` and the port is `"0"`.
2418 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
2420 // Set the default `appBar` background. `this` refers to the context.
2422 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
2424 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
2427 // Reset `waitingForOrbot.
2428 waitingForOrbot = false;
2431 // Set swipe to refresh.
2432 swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
2434 // Set Do Not Track status.
2435 if (doNotTrackEnabled) {
2436 customHeaders.put("DNT", "1");
2438 customHeaders.remove("DNT");
2441 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
2442 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
2443 if (hideSystemBarsOnFullscreen) { // Hide everything.
2444 // Remove the translucent navigation setting if it is currently flagged.
2445 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2447 // Remove the translucent status bar overlay.
2448 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2450 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
2451 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
2453 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
2454 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
2455 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
2457 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
2458 } else { // Hide everything except the status and navigation bars.
2459 // Add the translucent status flag if it is unset.
2460 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2462 if (translucentNavigationBarOnFullscreen) {
2463 // Set the navigation bar to be translucent.
2464 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2466 // Set the navigation bar to be black.
2467 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2470 } else { // Switch to normal viewing mode.
2471 // Reset `inFullScreenBrowsingMode` to `false`.
2472 inFullScreenBrowsingMode = false;
2474 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
2475 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
2479 // Show the `BannerAd` in the free flavor.
2480 if (BuildConfig.FLAVOR.contentEquals("free")) {
2481 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
2482 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2484 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2485 adView = findViewById(R.id.adview);
2488 // Remove the translucent navigation bar flag if it is set.
2489 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2491 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
2492 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2494 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
2495 rootCoordinatorLayout.setSystemUiVisibility(0);
2497 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
2498 rootCoordinatorLayout.setFitsSystemWindows(true);
2502 // We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2503 @SuppressWarnings("deprecation")
2504 private void applyDomainSettings(String url) {
2505 // Reset `navigatingHistory`.
2506 navigatingHistory = false;
2508 // Parse the URL into a URI.
2509 Uri uri = Uri.parse(url);
2511 // Extract the domain from `uri`.
2512 String hostName = uri.getHost();
2514 // Initialize `loadingNewDomainName`.
2515 boolean loadingNewDomainName;
2517 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
2518 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
2519 //noinspection SimplifiableIfStatement
2520 if ((hostName == null) || (currentDomainName == null)) {
2521 loadingNewDomainName = true;
2522 } else { // Determine if `hostName` equals `currentDomainName`.
2523 loadingNewDomainName = !hostName.equals(currentDomainName);
2526 // 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.
2527 if (loadingNewDomainName) {
2528 // Set the new `hostname` as the `currentDomainName`.
2529 currentDomainName = hostName;
2531 // Reset `ignorePinnedSslCertificate`.
2532 ignorePinnedSslCertificate = false;
2534 // Reset `favoriteIconBitmap` and display it in the `appbar`.
2535 favoriteIconBitmap = favoriteIconDefaultBitmap;
2536 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
2538 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
2539 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2540 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2542 // Get a full cursor from `domainsDatabaseHelper`.
2543 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
2545 // Initialize `domainSettingsSet`.
2546 Set<String> domainSettingsSet = new HashSet<>();
2548 // Get the domain name column index.
2549 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
2551 // Populate `domainSettingsSet`.
2552 for (int i = 0; i < domainNameCursor.getCount(); i++) {
2553 // Move `domainsCursor` to the current row.
2554 domainNameCursor.moveToPosition(i);
2556 // Store the domain name in `domainSettingsSet`.
2557 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
2560 // Close `domainNameCursor.
2561 domainNameCursor.close();
2563 // Initialize variables to track if domain settings will be applied and, if so, under which name.
2564 domainSettingsApplied = false;
2565 String domainNameInDatabase = null;
2567 // Check the hostname.
2568 if (domainSettingsSet.contains(hostName)) {
2569 domainSettingsApplied = true;
2570 domainNameInDatabase = hostName;
2573 // If `hostName` is not `null`, check all the subdomains of `hostName` against wildcard domains in `domainCursor`.
2574 if (hostName != null) {
2575 while (hostName.contains(".") && !domainSettingsApplied) { // Stop checking if we run out of `.` or if we already know that `domainSettingsApplied` is `true`.
2576 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
2577 domainSettingsApplied = true;
2578 domainNameInDatabase = "*." + hostName;
2581 // Strip out the lowest subdomain of `host`.
2582 hostName = hostName.substring(hostName.indexOf(".") + 1);
2586 // Get a handle for the shared preference. `this` references the current context.
2587 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2589 // Store the default font size and user agent information.
2590 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
2591 String defaultUserAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
2592 String defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
2594 if (domainSettingsApplied) { // The url we are loading has custom domain settings.
2595 // Get a cursor for the current host and move it to the first position.
2596 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
2597 currentHostDomainSettingsCursor.moveToFirst();
2599 // Get the settings from the cursor.
2600 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
2601 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
2602 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
2603 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
2604 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
2605 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
2606 String userAgentString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
2607 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
2608 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
2609 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
2610 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
2611 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
2612 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
2613 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
2614 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
2615 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
2617 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
2618 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
2619 pinnedDomainSslStartDate = null;
2621 pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
2624 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
2625 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
2626 pinnedDomainSslEndDate = null;
2628 pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
2631 // Close `currentHostDomainSettingsCursor`.
2632 currentHostDomainSettingsCursor.close();
2634 // Apply the domain settings.
2635 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2636 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2637 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2638 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2640 // Apply the font size.
2641 if (fontSize == 0) { // Apply the default font size.
2642 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
2643 } else { // Apply the specified font size.
2644 mainWebView.getSettings().setTextZoom(fontSize);
2647 // Set third-party cookies status if API >= 21.
2648 if (Build.VERSION.SDK_INT >= 21) {
2649 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2652 // 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>
2653 if (!urlIsLoading) {
2654 switch (userAgentString) {
2655 case "System default user agent":
2656 // Set the user agent according to the system default.
2657 switch (defaultUserAgentString) {
2658 case "WebView default user agent":
2659 // Set the user agent to `""`, which uses the default value.
2660 mainWebView.getSettings().setUserAgentString("");
2663 case "Custom user agent":
2664 // Set the custom user agent.
2665 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
2669 // Use the selected user agent.
2670 mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
2674 case "WebView default user agent":
2675 // Set the user agent to `""`, which uses the default value.
2676 mainWebView.getSettings().setUserAgentString("");
2680 // Use the selected user agent.
2681 mainWebView.getSettings().setUserAgentString(userAgentString);
2685 // 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.
2687 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
2689 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
2691 } else { // The URL we are loading does not have custom domain settings. Load the defaults.
2692 // Store the values from `sharedPreferences` in variables.
2693 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
2694 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
2695 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
2696 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
2697 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
2699 // Apply the default settings.
2700 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2701 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2702 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2703 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2704 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
2706 // Reset the pinned SSL certificate information.
2707 domainSettingsDatabaseId = -1;
2708 pinnedDomainSslCertificate = false;
2709 pinnedDomainSslIssuedToCNameString = "";
2710 pinnedDomainSslIssuedToONameString = "";
2711 pinnedDomainSslIssuedToUNameString = "";
2712 pinnedDomainSslIssuedByCNameString = "";
2713 pinnedDomainSslIssuedByONameString = "";
2714 pinnedDomainSslIssuedByUNameString = "";
2715 pinnedDomainSslStartDate = null;
2716 pinnedDomainSslEndDate = null;
2718 // Set third-party cookies status if API >= 21.
2719 if (Build.VERSION.SDK_INT >= 21) {
2720 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2723 // 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>
2724 if (!urlIsLoading) {
2725 switch (defaultUserAgentString) {
2726 case "WebView default user agent":
2727 // Set the user agent to `""`, which uses the default value.
2728 mainWebView.getSettings().setUserAgentString("");
2731 case "Custom user agent":
2732 // Set the custom user agent.
2733 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
2737 // Use the selected user agent.
2738 mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
2742 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2743 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
2746 // Close `domainsDatabaseHelper`.
2747 domainsDatabaseHelper.close();
2749 // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode. `true` indicates that custom domain settings are applied.
2750 onTheFlyDisplayImagesSet = false;
2751 setDisplayWebpageImages();
2753 // Update the privacy icons, but only if `mainMenu` has already been populated.
2754 if (mainMenu != null) {
2755 updatePrivacyIcons(true);
2760 private void setDisplayWebpageImages() {
2761 if (!onTheFlyDisplayImagesSet) {
2762 if (domainSettingsApplied) { // Custom domain settings are applied.
2763 switch (displayWebpageImagesInt) {
2764 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
2765 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
2768 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
2769 mainWebView.getSettings().setLoadsImagesAutomatically(true);
2772 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
2773 mainWebView.getSettings().setLoadsImagesAutomatically(false);
2776 } else { // Default settings are applied.
2777 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
2782 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
2783 // Get handles for the icons.
2784 MenuItem privacyIconMenuItem = mainMenu.findItem(R.id.toggle_javascript);
2785 MenuItem firstPartyCookiesIconMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
2786 MenuItem domStorageIconMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
2787 MenuItem formDataIconMenuItem = mainMenu.findItem(R.id.toggle_save_form_data);
2789 // Update `privacyIcon`.
2790 if (javaScriptEnabled) { // JavaScript is enabled.
2791 privacyIconMenuItem.setIcon(R.drawable.javascript_enabled);
2792 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
2793 privacyIconMenuItem.setIcon(R.drawable.warning);
2794 } else { // All the dangerous features are disabled.
2795 privacyIconMenuItem.setIcon(R.drawable.privacy_mode);
2798 // Update `firstPartyCookiesIcon`.
2799 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
2800 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_enabled);
2801 } else { // First-party cookies are disabled.
2803 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_dark);
2805 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_light);
2809 // Update `domStorageIcon`.
2810 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
2811 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_enabled);
2812 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
2814 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
2816 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
2818 } else { // JavaScript is disabled, so DOM storage is ghosted.
2820 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
2822 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
2826 // Update `formDataIcon`.
2827 if (saveFormDataEnabled) { // Form data is enabled.
2828 formDataIconMenuItem.setIcon(R.drawable.form_data_enabled);
2829 } else { // Form data is disabled.
2831 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_dark);
2833 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_light);
2837 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`. `this` references the current activity.
2838 if (runInvalidateOptionsMenu) {
2839 ActivityCompat.invalidateOptionsMenu(this);
2843 private void highlightUrlText() {
2844 String urlString = urlTextBox.getText().toString();
2846 if (urlString.startsWith("http://")) { // Highlight connections that are not encrypted.
2847 urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
2848 } else if (urlString.startsWith("https://")) { // Highlight connections that are encrypted.
2849 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
2852 // Get the index of the `/` immediately after the domain name.
2853 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
2855 // De-emphasize the text after the domain name.
2856 if (endOfDomainName > 0) {
2857 urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);