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 // Initialize cookieManager.
1025 cookieManager = CookieManager.getInstance();
1027 // 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).
1028 customHeaders.put("X-Requested-With", "");
1030 // 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.
1031 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
1033 // Get the intent that started the app.
1034 final Intent launchingIntent = getIntent();
1036 // Extract the launching intent data as `launchingIntentUriData`.
1037 final Uri launchingIntentUriData = launchingIntent.getData();
1039 // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
1040 if (launchingIntentUriData != null) {
1041 formattedUrlString = launchingIntentUriData.toString();
1044 // Get a handle for the `Runtime`.
1045 privacyBrowserRuntime = Runtime.getRuntime();
1047 // Store the application's private data directory.
1048 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`.
1050 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
1051 inFullScreenBrowsingMode = false;
1053 // Initialize AdView for the free flavor.
1054 adView = findViewById(R.id.adview);
1056 // Initialize the privacy settings variables.
1057 javaScriptEnabled = false;
1058 firstPartyCookiesEnabled = false;
1059 thirdPartyCookiesEnabled = false;
1060 domStorageEnabled = false;
1061 saveFormDataEnabled = false;
1063 // Initialize `webViewTitle`.
1064 webViewTitle = getString(R.string.no_title);
1066 // Initialize `favoriteIconBitmap`. We have to use `ContextCompat` until API >= 21.
1067 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
1068 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
1069 favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
1071 // If the favorite icon is null, load the default.
1072 if (favoriteIconBitmap == null) {
1073 favoriteIconBitmap = favoriteIconDefaultBitmap;
1076 // Apply the app settings from the shared preferences.
1079 // Load `formattedUrlString` if we are not waiting for Orbot to connect.
1080 if (!waitingForOrbot) {
1081 loadUrl(formattedUrlString);
1086 protected void onNewIntent(Intent intent) {
1087 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1090 if (intent.getData() != null) {
1091 // Get the intent data and convert it to a string.
1092 final Uri intentUriData = intent.getData();
1093 formattedUrlString = intentUriData.toString();
1096 // Close the navigation drawer if it is open.
1097 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1098 drawerLayout.closeDrawer(GravityCompat.START);
1101 // Load the website.
1102 loadUrl(formattedUrlString);
1104 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1105 mainWebView.requestFocus();
1109 public void onRestart() {
1112 // Apply the app settings, which may have been changed in `SettingsActivity`.
1115 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1116 updatePrivacyIcons(true);
1118 // Set the display webpage images mode.
1119 setDisplayWebpageImages();
1121 // Reload the webpage if displaying of images has been disabled in `SettingsFragment`.
1122 if (reloadOnRestartBoolean) {
1123 // Reload `mainWebView`.
1124 mainWebView.reload();
1126 // Reset `reloadOnRestartBoolean`.
1127 reloadOnRestartBoolean = false;
1131 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1133 public void onResume() {
1136 // Resume JavaScript (if enabled).
1137 mainWebView.resumeTimers();
1139 // Resume `mainWebView`.
1140 mainWebView.onResume();
1142 // Resume the adView for the free flavor.
1143 if (BuildConfig.FLAVOR.contentEquals("free")) {
1144 BannerAd.resumeAd(adView);
1149 public void onPause() {
1150 // Pause `mainWebView`.
1151 mainWebView.onPause();
1153 // Stop all JavaScript.
1154 mainWebView.pauseTimers();
1156 // Pause the adView or it will continue to consume resources in the background on the free flavor.
1157 if (BuildConfig.FLAVOR.contentEquals("free")) {
1158 BannerAd.pauseAd(adView);
1165 public boolean onCreateOptionsMenu(Menu menu) {
1166 // Inflate the menu; this adds items to the action bar if it is present.
1167 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1169 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1172 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1173 updatePrivacyIcons(false);
1175 // Get handles for the menu items.
1176 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1177 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1178 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1179 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1181 // Only display third-party cookies if SDK >= 21
1182 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1184 // Get the shared preference values. `this` references the current context.
1185 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1187 // Set the status of the additional app bar icons. The default is `false`.
1188 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
1189 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1190 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1191 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1192 } else { //Do not display the additional icons.
1193 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1194 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1195 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1202 public boolean onPrepareOptionsMenu(Menu menu) {
1203 // Get handles for the menu items.
1204 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1205 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1206 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1207 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1208 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1209 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1210 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);
1211 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1212 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1213 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1215 // Set the status of the menu item checkboxes.
1216 toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1217 toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1218 toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1219 toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);
1220 displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1222 // Enable third-party cookies if first-party cookies are enabled.
1223 toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1225 // Enable `DOM Storage` if JavaScript is enabled.
1226 toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
1228 // Enable `Clear Cookies` if there are any.
1229 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1231 // Get a count of the number of files in the `Local Storage` directory.
1232 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1233 int localStorageDirectoryNumberOfFiles = 0;
1234 if (localStorageDirectory.exists()) {
1235 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1238 // Get a count of the number of files in the `IndexedDB` directory.
1239 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1240 int indexedDBDirectoryNumberOfFiles = 0;
1241 if (indexedDBDirectory.exists()) {
1242 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1245 // Enable `Clear DOM Storage` if there is any.
1246 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1248 // Enable `Clear Form Data` is there is any.
1249 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1250 clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
1252 // Initialize font size variables.
1253 int fontSize = mainWebView.getSettings().getTextZoom();
1254 String fontSizeTitle;
1255 MenuItem selectedFontSizeMenuItem;
1257 // Prepare the font size title and current size menu item.
1260 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.twenty_five_percent);
1261 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1265 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.fifty_percent);
1266 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1270 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.seventy_five_percent);
1271 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1275 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
1276 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1280 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_twenty_five_percent);
1281 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1285 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_fifty_percent);
1286 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1290 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_seventy_five_percent);
1291 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1295 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.two_hundred_percent);
1296 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1300 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
1301 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1305 // Set the font size title and select the current size menu item.
1306 fontSizeMenuItem.setTitle(fontSizeTitle);
1307 selectedFontSizeMenuItem.setChecked(true);
1309 // Only show `Refresh` if `swipeToRefresh` is disabled.
1310 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
1312 // Run all the other default commands.
1313 super.onPrepareOptionsMenu(menu);
1315 // `return true` displays the menu.
1320 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1321 @SuppressLint("SetJavaScriptEnabled")
1322 // removeAllCookies is deprecated, but it is required for API < 21.
1323 @SuppressWarnings("deprecation")
1324 public boolean onOptionsItemSelected(MenuItem menuItem) {
1325 int menuItemId = menuItem.getItemId();
1327 // Set the commands that relate to the menu entries.
1328 switch (menuItemId) {
1329 case R.id.toggle_javascript:
1330 // Switch the status of javaScriptEnabled.
1331 javaScriptEnabled = !javaScriptEnabled;
1333 // Apply the new JavaScript status.
1334 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1336 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1337 updatePrivacyIcons(true);
1339 // Display a `Snackbar`.
1340 if (javaScriptEnabled) { // JavaScrip is enabled.
1341 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1342 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
1343 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1344 } else { // Privacy mode.
1345 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1348 // Reload the WebView.
1349 mainWebView.reload();
1352 case R.id.toggle_first_party_cookies:
1353 // Switch the status of firstPartyCookiesEnabled.
1354 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1356 // Update the menu checkbox.
1357 menuItem.setChecked(firstPartyCookiesEnabled);
1359 // Apply the new cookie status.
1360 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1362 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1363 updatePrivacyIcons(true);
1365 // Display a `Snackbar`.
1366 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1367 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1368 } else if (javaScriptEnabled){ // JavaScript is still enabled.
1369 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1370 } else { // Privacy mode.
1371 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1374 // Reload the WebView.
1375 mainWebView.reload();
1378 case R.id.toggle_third_party_cookies:
1379 if (Build.VERSION.SDK_INT >= 21) {
1380 // Switch the status of thirdPartyCookiesEnabled.
1381 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1383 // Update the menu checkbox.
1384 menuItem.setChecked(thirdPartyCookiesEnabled);
1386 // Apply the new cookie status.
1387 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1389 // Display a `Snackbar`.
1390 if (thirdPartyCookiesEnabled) {
1391 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1393 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1396 // Reload the WebView.
1397 mainWebView.reload();
1398 } // Else do nothing because SDK < 21.
1401 case R.id.toggle_dom_storage:
1402 // Switch the status of domStorageEnabled.
1403 domStorageEnabled = !domStorageEnabled;
1405 // Update the menu checkbox.
1406 menuItem.setChecked(domStorageEnabled);
1408 // Apply the new DOM Storage status.
1409 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1411 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1412 updatePrivacyIcons(true);
1414 // Display a `Snackbar`.
1415 if (domStorageEnabled) {
1416 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1418 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1421 // Reload the WebView.
1422 mainWebView.reload();
1425 case R.id.toggle_save_form_data:
1426 // Switch the status of saveFormDataEnabled.
1427 saveFormDataEnabled = !saveFormDataEnabled;
1429 // Update the menu checkbox.
1430 menuItem.setChecked(saveFormDataEnabled);
1432 // Apply the new form data status.
1433 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1435 // Display a `Snackbar`.
1436 if (saveFormDataEnabled) {
1437 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1439 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1442 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1443 updatePrivacyIcons(true);
1445 // Reload the WebView.
1446 mainWebView.reload();
1449 case R.id.clear_cookies:
1450 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1451 .setAction(R.string.undo, new View.OnClickListener() {
1453 public void onClick(View v) {
1454 // Do nothing because everything will be handled by `onDismissed()` below.
1457 .addCallback(new Snackbar.Callback() {
1459 public void onDismissed(Snackbar snackbar, int event) {
1461 // The user pushed the `Undo` button.
1462 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1466 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1468 // `cookieManager.removeAllCookie()` varies by SDK.
1469 if (Build.VERSION.SDK_INT < 21) {
1470 cookieManager.removeAllCookie();
1472 // `null` indicates no callback.
1473 cookieManager.removeAllCookies(null);
1481 case R.id.clear_dom_storage:
1482 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1483 .setAction(R.string.undo, new View.OnClickListener() {
1485 public void onClick(View v) {
1486 // Do nothing because everything will be handled by `onDismissed()` below.
1489 .addCallback(new Snackbar.Callback() {
1491 public void onDismissed(Snackbar snackbar, int event) {
1493 // The user pushed the `Undo` button.
1494 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1498 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1500 // Delete the DOM Storage.
1501 WebStorage webStorage = WebStorage.getInstance();
1502 webStorage.deleteAllData();
1504 // Manually remove `IndexedDB` if it exists.
1506 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1507 } catch (IOException e) {
1508 // Do nothing if an error is thrown.
1516 case R.id.clear_form_data:
1517 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1518 .setAction(R.string.undo, new View.OnClickListener() {
1520 public void onClick(View v) {
1521 // Do nothing because everything will be handled by `onDismissed()` below.
1524 .addCallback(new Snackbar.Callback() {
1526 public void onDismissed(Snackbar snackbar, int event) {
1528 // The user pushed the `Undo` button.
1529 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1533 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1535 // Delete the form data.
1536 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1537 mainWebViewDatabase.clearFormData();
1544 case R.id.font_size_twenty_five_percent:
1545 mainWebView.getSettings().setTextZoom(25);
1548 case R.id.font_size_fifty_percent:
1549 mainWebView.getSettings().setTextZoom(50);
1552 case R.id.font_size_seventy_five_percent:
1553 mainWebView.getSettings().setTextZoom(75);
1556 case R.id.font_size_one_hundred_percent:
1557 mainWebView.getSettings().setTextZoom(100);
1560 case R.id.font_size_one_hundred_twenty_five_percent:
1561 mainWebView.getSettings().setTextZoom(125);
1564 case R.id.font_size_one_hundred_fifty_percent:
1565 mainWebView.getSettings().setTextZoom(150);
1568 case R.id.font_size_one_hundred_seventy_five_percent:
1569 mainWebView.getSettings().setTextZoom(175);
1572 case R.id.font_size_two_hundred_percent:
1573 mainWebView.getSettings().setTextZoom(200);
1576 case R.id.display_images:
1577 if (mainWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1578 mainWebView.getSettings().setLoadsImagesAutomatically(false);
1579 mainWebView.reload();
1580 } else { // Images are not currently loaded automatically.
1581 mainWebView.getSettings().setLoadsImagesAutomatically(true);
1584 // Set `onTheFlyDisplayImagesSet`.
1585 onTheFlyDisplayImagesSet = true;
1589 // Setup the share string.
1590 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
1592 // Create the share intent.
1593 Intent shareIntent = new Intent();
1594 shareIntent.setAction(Intent.ACTION_SEND);
1595 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1596 shareIntent.setType("text/plain");
1599 startActivity(Intent.createChooser(shareIntent, "Share URL"));
1602 case R.id.find_on_page:
1603 // Hide the URL app bar.
1604 supportAppBar.setVisibility(View.GONE);
1606 // Show the Find on Page `RelativeLayout`.
1607 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1609 // 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
1610 findOnPageEditText.postDelayed(new Runnable() {
1614 // Set the focus on `findOnPageEditText`.
1615 findOnPageEditText.requestFocus();
1617 // Display the keyboard. `0` sets no input flags.
1618 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1624 // Get a `PrintManager` instance.
1625 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1627 // Convert `mainWebView` to `printDocumentAdapter`.
1628 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
1630 // Print the document. The print attributes are `null`.
1631 printManager.print(getResources().getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1634 case R.id.add_to_homescreen:
1635 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
1636 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
1637 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.create_shortcut));
1639 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
1643 mainWebView.reload();
1647 // Don't consume the event.
1648 return super.onOptionsItemSelected(menuItem);
1652 // removeAllCookies is deprecated, but it is required for API < 21.
1653 @SuppressWarnings("deprecation")
1655 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1656 int menuItemId = menuItem.getItemId();
1658 switch (menuItemId) {
1664 if (mainWebView.canGoBack()) {
1665 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1666 navigatingHistory = true;
1668 // Load the previous website in the history.
1669 mainWebView.goBack();
1674 if (mainWebView.canGoForward()) {
1675 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1676 navigatingHistory = true;
1678 // Load the next website in the history.
1679 mainWebView.goForward();
1684 // Get the `WebBackForwardList`.
1685 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
1687 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
1688 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
1689 urlHistoryDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.history));
1692 case R.id.bookmarks:
1693 // Launch BookmarksActivity.
1694 Intent bookmarksIntent = new Intent(this, BookmarksActivity.class);
1695 startActivity(bookmarksIntent);
1698 case R.id.downloads:
1699 // Launch the system Download Manager.
1700 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1702 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1703 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1705 startActivity(downloadManagerIntent);
1709 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1710 currentDomainName = "";
1712 // Launch `SettingsActivity`.
1713 Intent settingsIntent = new Intent(this, SettingsActivity.class);
1714 startActivity(settingsIntent);
1718 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1719 currentDomainName = "";
1721 // Launch `DomainsActivity`.
1722 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1723 startActivity(domainsIntent);
1727 // Launch `GuideActivity`.
1728 Intent guideIntent = new Intent(this, GuideActivity.class);
1729 startActivity(guideIntent);
1733 // Launch `AboutActivity`.
1734 Intent aboutIntent = new Intent(this, AboutActivity.class);
1735 startActivity(aboutIntent);
1738 case R.id.clearAndExit:
1739 // Get a handle for `sharedPreferences`. `this` references the current context.
1740 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1742 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
1745 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
1746 // The command to remove cookies changed slightly in API 21.
1747 if (Build.VERSION.SDK_INT >= 21) {
1748 cookieManager.removeAllCookies(null);
1750 cookieManager.removeAllCookie();
1753 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1755 // We have to use two commands because `Runtime.exec()` does not like `*`.
1756 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
1757 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
1758 } catch (IOException e) {
1759 // Do nothing if an error is thrown.
1763 // Clear DOM storage.
1764 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
1765 // Ask `WebStorage` to clear the DOM storage.
1766 WebStorage webStorage = WebStorage.getInstance();
1767 webStorage.deleteAllData();
1769 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1771 // We have to use a `String[]` because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1772 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1774 // We have to use multiple commands because `Runtime.exec()` does not like `*`.
1775 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1776 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1777 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1778 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1779 } catch (IOException e) {
1780 // Do nothing if an error is thrown.
1785 if (clearEverything || sharedPreferences.getBoolean("clear_form_data", true)) {
1786 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1787 webViewDatabase.clearFormData();
1789 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1791 // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1792 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
1793 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
1794 } catch (IOException e) {
1795 // Do nothing if an error is thrown.
1800 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
1801 // `true` includes disk files.
1802 mainWebView.clearCache(true);
1804 // Manually delete the cache directories.
1806 // Delete the main cache directory.
1807 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1809 // 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.
1810 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1811 } catch (IOException e) {
1812 // Do nothing if an error is thrown.
1816 // Clear SSL certificate preferences.
1817 mainWebView.clearSslPreferences();
1819 // Clear the back/forward history.
1820 mainWebView.clearHistory();
1822 // Clear `formattedUrlString`.
1823 formattedUrlString = null;
1825 // Clear `customHeaders`.
1826 customHeaders.clear();
1828 // Detach all views from `mainWebViewRelativeLayout`.
1829 mainWebViewRelativeLayout.removeAllViews();
1831 // Destroy the internal state of `mainWebView`.
1832 mainWebView.destroy();
1834 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
1835 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
1836 if (clearEverything) {
1838 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
1839 } catch (IOException e) {
1840 // Do nothing if an error is thrown.
1844 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
1845 if (Build.VERSION.SDK_INT >= 21) {
1846 finishAndRemoveTask();
1851 // Remove the terminated program from RAM. The status code is `0`.
1856 // Close the navigation drawer.
1857 drawerLayout.closeDrawer(GravityCompat.START);
1862 public void onPostCreate(Bundle savedInstanceState) {
1863 super.onPostCreate(savedInstanceState);
1865 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
1866 drawerToggle.syncState();
1870 public void onConfigurationChanged(Configuration newConfig) {
1871 super.onConfigurationChanged(newConfig);
1873 // Reload the ad for the free flavor if we are not in full screen mode.
1874 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
1876 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1878 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1879 adView = findViewById(R.id.adview);
1882 // `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
1883 // ActivityCompat.invalidateOptionsMenu(this);
1887 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
1888 // Store the `HitTestResult`.
1889 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
1892 final String imageUrl;
1893 final String linkUrl;
1895 // Get a handle for the `ClipboardManager`.
1896 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
1898 switch (hitTestResult.getType()) {
1899 // `SRC_ANCHOR_TYPE` is a link.
1900 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1901 // Get the target URL.
1902 linkUrl = hitTestResult.getExtra();
1904 // Set the target URL as the title of the `ContextMenu`.
1905 menu.setHeaderTitle(linkUrl);
1907 // Add a `Load URL` entry.
1908 menu.add(R.string.load_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1910 public boolean onMenuItemClick(MenuItem item) {
1916 // Add a `Copy URL` entry.
1917 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1919 public boolean onMenuItemClick(MenuItem item) {
1920 // Save the link URL in a `ClipData`.
1921 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), linkUrl);
1923 // Set the `ClipData` as the clipboard's primary clip.
1924 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
1929 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1930 menu.add(R.string.cancel);
1933 case WebView.HitTestResult.EMAIL_TYPE:
1934 // Get the target URL.
1935 linkUrl = hitTestResult.getExtra();
1937 // Set the target URL as the title of the `ContextMenu`.
1938 menu.setHeaderTitle(linkUrl);
1940 // Add a `Write Email` entry.
1941 menu.add(R.string.write_email).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1943 public boolean onMenuItemClick(MenuItem item) {
1944 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1945 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1947 // Parse the url and set it as the data for the `Intent`.
1948 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
1950 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
1951 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1954 startActivity(emailIntent);
1959 // Add a `Copy Email Address` entry.
1960 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1962 public boolean onMenuItemClick(MenuItem item) {
1963 // Save the email address in a `ClipData`.
1964 ClipData srcEmailTypeClipData = ClipData.newPlainText(getResources().getString(R.string.email_address), linkUrl);
1966 // Set the `ClipData` as the clipboard's primary clip.
1967 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
1972 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1973 menu.add(R.string.cancel);
1976 // `IMAGE_TYPE` is an image.
1977 case WebView.HitTestResult.IMAGE_TYPE:
1978 // Get the image URL.
1979 imageUrl = hitTestResult.getExtra();
1981 // Set the image URL as the title of the `ContextMenu`.
1982 menu.setHeaderTitle(imageUrl);
1984 // Add a `View Image` entry.
1985 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1987 public boolean onMenuItemClick(MenuItem item) {
1993 // Add a `Download Image` entry.
1994 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1996 public boolean onMenuItemClick(MenuItem item) {
1997 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
1998 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
1999 downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
2004 // Add a `Copy URL` entry.
2005 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2007 public boolean onMenuItemClick(MenuItem item) {
2008 // Save the image URL in a `ClipData`.
2009 ClipData srcImageTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
2011 // Set the `ClipData` as the clipboard's primary clip.
2012 clipboardManager.setPrimaryClip(srcImageTypeClipData);
2017 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2018 menu.add(R.string.cancel);
2022 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2023 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2024 // Get the image URL.
2025 imageUrl = hitTestResult.getExtra();
2027 // Set the image URL as the title of the `ContextMenu`.
2028 menu.setHeaderTitle(imageUrl);
2030 // Add a `View Image` entry.
2031 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2033 public boolean onMenuItemClick(MenuItem item) {
2039 // Add a `Download Image` entry.
2040 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2042 public boolean onMenuItemClick(MenuItem item) {
2043 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
2044 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2045 downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
2050 // Add a `Copy URL` entry.
2051 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2053 public boolean onMenuItemClick(MenuItem item) {
2054 // Save the image URL in a `ClipData`.
2055 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
2057 // Set the `ClipData` as the clipboard's primary clip.
2058 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2063 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2064 menu.add(R.string.cancel);
2070 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
2071 // Get shortcutNameEditText from the alert dialog.
2072 EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
2074 // Create the bookmark shortcut based on formattedUrlString.
2075 Intent bookmarkShortcut = new Intent();
2076 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
2077 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
2079 // Place the bookmark shortcut on the home screen.
2080 Intent placeBookmarkShortcut = new Intent();
2081 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
2082 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
2083 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIconBitmap);
2084 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
2085 sendBroadcast(placeBookmarkShortcut);
2089 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
2090 // Download the image if it has an HTTP or HTTPS URI.
2091 if (imageUrl.startsWith("http")) {
2092 // Get a handle for the system `DOWNLOAD_SERVICE`.
2093 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2095 // Parse `imageUrl`.
2096 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
2098 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
2099 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2100 if (firstPartyCookiesEnabled) {
2101 // Get the cookies for `imageUrl`.
2102 String cookies = cookieManager.getCookie(imageUrl);
2104 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2105 downloadRequest.addRequestHeader("Cookie", cookies);
2108 // Get the file name from `dialogFragment`.
2109 EditText downloadImageNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_image_name);
2110 String imageName = downloadImageNameEditText.getText().toString();
2112 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
2113 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `imageName`.
2114 downloadRequest.setDestinationInExternalFilesDir(this, "/", imageName);
2115 } else { // Only set the title using `imageName`.
2116 downloadRequest.setTitle(imageName);
2119 // Allow `MediaScanner` to index the download if it is a media file.
2120 downloadRequest.allowScanningByMediaScanner();
2122 // Add the URL as the description for the download.
2123 downloadRequest.setDescription(imageUrl);
2125 // Show the download notification after the download is completed.
2126 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2128 // Initiate the download.
2129 downloadManager.enqueue(downloadRequest);
2130 } else { // The image is not an HTTP or HTTPS URI.
2131 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
2136 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
2137 // Download the file if it has an HTTP or HTTPS URI.
2138 if (downloadUrl.startsWith("http")) {
2140 // Get a handle for the system `DOWNLOAD_SERVICE`.
2141 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2143 // Parse `downloadUrl`.
2144 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
2146 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
2147 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2148 if (firstPartyCookiesEnabled) {
2149 // Get the cookies for `downloadUrl`.
2150 String cookies = cookieManager.getCookie(downloadUrl);
2152 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2153 downloadRequest.addRequestHeader("Cookie", cookies);
2156 // Get the file name from `dialogFragment`.
2157 EditText downloadFileNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_file_name);
2158 String fileName = downloadFileNameEditText.getText().toString();
2160 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
2161 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download location to `/sdcard/Android/data/com.stoutner.privacybrowser.standard/files` named `fileName`.
2162 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
2163 } else { // Only set the title using `fileName`.
2164 downloadRequest.setTitle(fileName);
2167 // Allow `MediaScanner` to index the download if it is a media file.
2168 downloadRequest.allowScanningByMediaScanner();
2170 // Add the URL as the description for the download.
2171 downloadRequest.setDescription(downloadUrl);
2173 // Show the download notification after the download is completed.
2174 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2176 // Initiate the download.
2177 downloadManager.enqueue(downloadRequest);
2178 } else { // The download is not an HTTP or HTTPS URI.
2179 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
2183 public void viewSslCertificate(View view) {
2184 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
2185 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
2186 viewSslCertificateDialogFragment.show(getFragmentManager(), getResources().getString(R.string.view_ssl_certificate));
2190 public void onSslErrorCancel() {
2191 sslErrorHandler.cancel();
2195 public void onSslErrorProceed() {
2196 sslErrorHandler.proceed();
2200 public void onSslMismatchBack() {
2201 if (mainWebView.canGoBack()) { // There is a back page in the history.
2202 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2203 navigatingHistory = true;
2206 mainWebView.goBack();
2207 } else { // There are no pages to go back to.
2208 // Load a blank page
2214 public void onSslMismatchProceed() {
2215 // Do not check the pinned SSL certificate for this domain again until the domain changes.
2216 ignorePinnedSslCertificate = true;
2220 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
2221 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2222 navigatingHistory = true;
2224 // Load the history entry.
2225 mainWebView.goBackOrForward(moveBackOrForwardSteps);
2229 public void onClearHistory() {
2230 // Clear the history.
2231 mainWebView.clearHistory();
2234 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
2236 public void onBackPressed() {
2237 // Close the navigation drawer if it is available. GravityCompat.START is the drawer on the left on Left-to-Right layout text.
2238 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
2239 drawerLayout.closeDrawer(GravityCompat.START);
2241 // Load the previous URL if available.
2242 if (mainWebView.canGoBack()) {
2243 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2244 navigatingHistory = true;
2247 mainWebView.goBack();
2249 // Pass `onBackPressed()` to the system.
2250 super.onBackPressed();
2255 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
2256 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
2257 String unformattedUrlString = urlTextBox.getText().toString().trim();
2259 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
2260 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
2261 // Add `http://` at the beginning if it is missing. Otherwise the app will segfault.
2262 if (!unformattedUrlString.startsWith("http")) {
2263 unformattedUrlString = "http://" + unformattedUrlString;
2266 // Initialize `unformattedUrl`.
2267 URL unformattedUrl = null;
2269 // 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.
2271 unformattedUrl = new URL(unformattedUrlString);
2272 } catch (MalformedURLException e) {
2273 e.printStackTrace();
2276 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2277 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2278 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2279 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2280 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2281 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2284 Uri.Builder formattedUri = new Uri.Builder();
2285 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2287 // Decode `formattedUri` as a `String` in `UTF-8`.
2288 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
2290 // Sanitize the search input and convert it to a search.
2291 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2293 // Add the base search URL.
2294 formattedUrlString = searchURL + encodedUrlString;
2297 loadUrl(formattedUrlString);
2299 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
2300 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2304 private void loadUrl(String url) {
2305 // Apply any custom domain settings.
2306 applyDomainSettings(url);
2309 mainWebView.loadUrl(url, customHeaders);
2311 // Set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
2312 urlIsLoading = true;
2315 public void findPreviousOnPage(View view) {
2316 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
2317 mainWebView.findNext(false);
2320 public void findNextOnPage(View view) {
2321 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2322 mainWebView.findNext(true);
2325 public void closeFindOnPage(View view) {
2326 // Delete the contents of `find_on_page_edittext`.
2327 findOnPageEditText.setText(null);
2329 // Clear the highlighted phrases.
2330 mainWebView.clearMatches();
2332 // Hide the Find on Page `RelativeLayout`.
2333 findOnPageLinearLayout.setVisibility(View.GONE);
2335 // Show the URL app bar.
2336 supportAppBar.setVisibility(View.VISIBLE);
2338 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
2339 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2342 private void applyAppSettings() {
2343 // Get a handle for `sharedPreferences`. `this` references the current context.
2344 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2346 // Store the values from `sharedPreferences` in variables.
2347 String homepageString = sharedPreferences.getString("homepage", "https://start.duckduckgo.com");
2348 String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
2349 String torSearchString = sharedPreferences.getString("tor_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
2350 String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
2351 String searchString = sharedPreferences.getString("search", "https://duckduckgo.com/html/?q=");
2352 String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
2353 adBlockerEnabled = sharedPreferences.getBoolean("block_ads", true);
2354 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
2355 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
2356 boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
2357 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
2358 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
2359 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
2360 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh", false);
2361 displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
2363 // Set the homepage, search, and proxy options.
2364 if (proxyThroughOrbot) { // Set the Tor options.
2365 // Set `torHomepageString` as `homepage`.
2366 homepage = torHomepageString;
2368 // If formattedUrlString is null assign the homepage to it.
2369 if (formattedUrlString == null) {
2370 formattedUrlString = homepage;
2373 // Set the search URL.
2374 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
2375 searchURL = torSearchCustomURLString;
2376 } else { // Use the string from the pre-built list.
2377 searchURL = torSearchString;
2380 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
2381 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
2383 // Set the `appBar` background to indicate proxying through Orbot is enabled. `this` refers to the context.
2385 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
2387 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
2390 // Display a message to the user if we are waiting on Orbot.
2391 if (!orbotStatus.equals("ON")) {
2392 // Set `waitingForOrbot`.
2393 waitingForOrbot = true;
2395 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
2396 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
2398 } else { // Set the non-Tor options.
2399 // Set `homepageString` as `homepage`.
2400 homepage = homepageString;
2402 // If formattedUrlString is null assign the homepage to it.
2403 if (formattedUrlString == null) {
2404 formattedUrlString = homepage;
2407 // Set the search URL.
2408 if (searchString.equals("Custom URL")) { // Get the custom URL string.
2409 searchURL = searchCustomURLString;
2410 } else { // Use the string from the pre-built list.
2411 searchURL = searchString;
2414 // Reset the proxy to default. The host is `""` and the port is `"0"`.
2415 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
2417 // Set the default `appBar` background. `this` refers to the context.
2419 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
2421 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
2424 // Reset `waitingForOrbot.
2425 waitingForOrbot = false;
2428 // Set swipe to refresh.
2429 swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
2431 // Set Do Not Track status.
2432 if (doNotTrackEnabled) {
2433 customHeaders.put("DNT", "1");
2435 customHeaders.remove("DNT");
2438 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
2439 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
2440 if (hideSystemBarsOnFullscreen) { // Hide everything.
2441 // Remove the translucent navigation setting if it is currently flagged.
2442 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2444 // Remove the translucent status bar overlay.
2445 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2447 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
2448 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
2450 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
2451 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
2452 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
2454 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
2455 } else { // Hide everything except the status and navigation bars.
2456 // Add the translucent status flag if it is unset.
2457 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2459 if (translucentNavigationBarOnFullscreen) {
2460 // Set the navigation bar to be translucent.
2461 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2463 // Set the navigation bar to be black.
2464 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2467 } else { // Switch to normal viewing mode.
2468 // Reset `inFullScreenBrowsingMode` to `false`.
2469 inFullScreenBrowsingMode = false;
2471 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
2472 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
2476 // Show the `BannerAd` in the free flavor.
2477 if (BuildConfig.FLAVOR.contentEquals("free")) {
2478 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
2479 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2481 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2482 adView = findViewById(R.id.adview);
2485 // Remove the translucent navigation bar flag if it is set.
2486 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2488 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
2489 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2491 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
2492 rootCoordinatorLayout.setSystemUiVisibility(0);
2494 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
2495 rootCoordinatorLayout.setFitsSystemWindows(true);
2499 // We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2500 @SuppressWarnings("deprecation")
2501 private void applyDomainSettings(String url) {
2502 // Reset `navigatingHistory`.
2503 navigatingHistory = false;
2505 // Parse the URL into a URI.
2506 Uri uri = Uri.parse(url);
2508 // Extract the domain from `uri`.
2509 String hostName = uri.getHost();
2511 // Initialize `loadingNewDomainName`.
2512 boolean loadingNewDomainName;
2514 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
2515 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
2516 //noinspection SimplifiableIfStatement
2517 if ((hostName == null) || (currentDomainName == null)) {
2518 loadingNewDomainName = true;
2519 } else { // Determine if `hostName` equals `currentDomainName`.
2520 loadingNewDomainName = !hostName.equals(currentDomainName);
2523 // 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.
2524 if (loadingNewDomainName) {
2525 // Set the new `hostname` as the `currentDomainName`.
2526 currentDomainName = hostName;
2528 // Reset `ignorePinnedSslCertificate`.
2529 ignorePinnedSslCertificate = false;
2531 // Reset `favoriteIconBitmap` and display it in the `appbar`.
2532 favoriteIconBitmap = favoriteIconDefaultBitmap;
2533 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
2535 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
2536 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2537 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2539 // Get a full cursor from `domainsDatabaseHelper`.
2540 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
2542 // Initialize `domainSettingsSet`.
2543 Set<String> domainSettingsSet = new HashSet<>();
2545 // Get the domain name column index.
2546 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
2548 // Populate `domainSettingsSet`.
2549 for (int i = 0; i < domainNameCursor.getCount(); i++) {
2550 // Move `domainsCursor` to the current row.
2551 domainNameCursor.moveToPosition(i);
2553 // Store the domain name in `domainSettingsSet`.
2554 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
2557 // Close `domainNameCursor.
2558 domainNameCursor.close();
2560 // Initialize variables to track if domain settings will be applied and, if so, under which name.
2561 domainSettingsApplied = false;
2562 String domainNameInDatabase = null;
2564 // Check the hostname.
2565 if (domainSettingsSet.contains(hostName)) {
2566 domainSettingsApplied = true;
2567 domainNameInDatabase = hostName;
2570 // If `hostName` is not `null`, check all the subdomains of `hostName` against wildcard domains in `domainCursor`.
2571 if (hostName != null) {
2572 while (hostName.contains(".") && !domainSettingsApplied) { // Stop checking if we run out of `.` or if we already know that `domainSettingsApplied` is `true`.
2573 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
2574 domainSettingsApplied = true;
2575 domainNameInDatabase = "*." + hostName;
2578 // Strip out the lowest subdomain of `host`.
2579 hostName = hostName.substring(hostName.indexOf(".") + 1);
2583 // Get a handle for the shared preference. `this` references the current context.
2584 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2586 // Store the default font size and user agent information.
2587 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
2588 String defaultUserAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
2589 String defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
2591 if (domainSettingsApplied) { // The url we are loading has custom domain settings.
2592 // Get a cursor for the current host and move it to the first position.
2593 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
2594 currentHostDomainSettingsCursor.moveToFirst();
2596 // Get the settings from the cursor.
2597 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
2598 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
2599 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
2600 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
2601 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
2602 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
2603 String userAgentString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
2604 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
2605 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
2606 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
2607 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
2608 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
2609 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
2610 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
2611 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
2612 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
2614 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
2615 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
2616 pinnedDomainSslStartDate = null;
2618 pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
2621 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
2622 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
2623 pinnedDomainSslEndDate = null;
2625 pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
2628 // Close `currentHostDomainSettingsCursor`.
2629 currentHostDomainSettingsCursor.close();
2631 // Apply the domain settings.
2632 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2633 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2634 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2635 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2637 // Apply the font size.
2638 if (fontSize == 0) { // Apply the default font size.
2639 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
2640 } else { // Apply the specified font size.
2641 mainWebView.getSettings().setTextZoom(fontSize);
2644 // Set third-party cookies status if API >= 21.
2645 if (Build.VERSION.SDK_INT >= 21) {
2646 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2649 // 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>
2650 if (!urlIsLoading) {
2651 switch (userAgentString) {
2652 case "System default user agent":
2653 // Set the user agent according to the system default.
2654 switch (defaultUserAgentString) {
2655 case "WebView default user agent":
2656 // Set the user agent to `""`, which uses the default value.
2657 mainWebView.getSettings().setUserAgentString("");
2660 case "Custom user agent":
2661 // Set the custom user agent.
2662 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
2666 // Use the selected user agent.
2667 mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
2671 case "WebView default user agent":
2672 // Set the user agent to `""`, which uses the default value.
2673 mainWebView.getSettings().setUserAgentString("");
2677 // Use the selected user agent.
2678 mainWebView.getSettings().setUserAgentString(userAgentString);
2682 // 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.
2684 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
2686 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
2688 } else { // The URL we are loading does not have custom domain settings. Load the defaults.
2689 // Store the values from `sharedPreferences` in variables.
2690 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
2691 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
2692 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
2693 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
2694 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
2696 // Apply the default settings.
2697 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2698 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2699 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2700 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2701 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
2703 // Reset the pinned SSL certificate information.
2704 domainSettingsDatabaseId = -1;
2705 pinnedDomainSslCertificate = false;
2706 pinnedDomainSslIssuedToCNameString = "";
2707 pinnedDomainSslIssuedToONameString = "";
2708 pinnedDomainSslIssuedToUNameString = "";
2709 pinnedDomainSslIssuedByCNameString = "";
2710 pinnedDomainSslIssuedByONameString = "";
2711 pinnedDomainSslIssuedByUNameString = "";
2712 pinnedDomainSslStartDate = null;
2713 pinnedDomainSslEndDate = null;
2715 // Set third-party cookies status if API >= 21.
2716 if (Build.VERSION.SDK_INT >= 21) {
2717 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2720 // 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>
2721 if (!urlIsLoading) {
2722 switch (defaultUserAgentString) {
2723 case "WebView default user agent":
2724 // Set the user agent to `""`, which uses the default value.
2725 mainWebView.getSettings().setUserAgentString("");
2728 case "Custom user agent":
2729 // Set the custom user agent.
2730 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
2734 // Use the selected user agent.
2735 mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
2739 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2740 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
2743 // Close `domainsDatabaseHelper`.
2744 domainsDatabaseHelper.close();
2746 // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode. `true` indicates that custom domain settings are applied.
2747 onTheFlyDisplayImagesSet = false;
2748 setDisplayWebpageImages();
2750 // Update the privacy icons, but only if `mainMenu` has already been populated.
2751 if (mainMenu != null) {
2752 updatePrivacyIcons(true);
2757 private void setDisplayWebpageImages() {
2758 if (!onTheFlyDisplayImagesSet) {
2759 if (domainSettingsApplied) { // Custom domain settings are applied.
2760 switch (displayWebpageImagesInt) {
2761 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
2762 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
2765 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
2766 mainWebView.getSettings().setLoadsImagesAutomatically(true);
2769 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
2770 mainWebView.getSettings().setLoadsImagesAutomatically(false);
2773 } else { // Default settings are applied.
2774 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
2779 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
2780 // Get handles for the icons.
2781 MenuItem privacyIconMenuItem = mainMenu.findItem(R.id.toggle_javascript);
2782 MenuItem firstPartyCookiesIconMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
2783 MenuItem domStorageIconMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
2784 MenuItem formDataIconMenuItem = mainMenu.findItem(R.id.toggle_save_form_data);
2786 // Update `privacyIcon`.
2787 if (javaScriptEnabled) { // JavaScript is enabled.
2788 privacyIconMenuItem.setIcon(R.drawable.javascript_enabled);
2789 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
2790 privacyIconMenuItem.setIcon(R.drawable.warning);
2791 } else { // All the dangerous features are disabled.
2792 privacyIconMenuItem.setIcon(R.drawable.privacy_mode);
2795 // Update `firstPartyCookiesIcon`.
2796 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
2797 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_enabled);
2798 } else { // First-party cookies are disabled.
2800 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_dark);
2802 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_light);
2806 // Update `domStorageIcon`.
2807 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
2808 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_enabled);
2809 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
2811 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
2813 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
2815 } else { // JavaScript is disabled, so DOM storage is ghosted.
2817 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
2819 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
2823 // Update `formDataIcon`.
2824 if (saveFormDataEnabled) { // Form data is enabled.
2825 formDataIconMenuItem.setIcon(R.drawable.form_data_enabled);
2826 } else { // Form data is disabled.
2828 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_dark);
2830 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_light);
2834 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`. `this` references the current activity.
2835 if (runInvalidateOptionsMenu) {
2836 ActivityCompat.invalidateOptionsMenu(this);
2840 private void highlightUrlText() {
2841 String urlString = urlTextBox.getText().toString();
2843 if (urlString.startsWith("http://")) { // Highlight connections that are not encrypted.
2844 urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
2845 } else if (urlString.startsWith("https://")) { // Highlight connections that are encrypted.
2846 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
2849 // Get the index of the `/` immediately after the domain name.
2850 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
2852 // De-emphasize the text after the domain name.
2853 if (endOfDomainName > 0) {
2854 urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);