2 * Copyright © 2015-2018 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.Manifest;
25 import android.annotation.SuppressLint;
26 import android.app.DialogFragment;
27 import android.app.DownloadManager;
28 import android.content.ActivityNotFoundException;
29 import android.content.BroadcastReceiver;
30 import android.content.ClipData;
31 import android.content.ClipboardManager;
32 import android.content.Context;
33 import android.content.Intent;
34 import android.content.IntentFilter;
35 import android.content.SharedPreferences;
36 import android.content.pm.PackageManager;
37 import android.content.res.Configuration;
38 import android.database.Cursor;
39 import android.graphics.Bitmap;
40 import android.graphics.BitmapFactory;
41 import android.graphics.Typeface;
42 import android.graphics.drawable.BitmapDrawable;
43 import android.graphics.drawable.Drawable;
44 import android.net.Uri;
45 import android.net.http.SslCertificate;
46 import android.net.http.SslError;
47 import android.os.Build;
48 import android.os.Bundle;
49 import android.os.Environment;
50 import android.os.Handler;
51 import android.preference.PreferenceManager;
52 import android.print.PrintDocumentAdapter;
53 import android.print.PrintManager;
54 import android.support.annotation.NonNull;
55 import android.support.design.widget.CoordinatorLayout;
56 import android.support.design.widget.FloatingActionButton;
57 import android.support.design.widget.NavigationView;
58 import android.support.design.widget.Snackbar;
59 import android.support.v4.app.ActivityCompat;
60 import android.support.v4.content.ContextCompat;
61 // `ShortcutInfoCompat`, `ShortcutManagerCompat`, and `IconCompat` can be switched to the non-compat version once API >= 26.
62 import android.support.v4.content.pm.ShortcutInfoCompat;
63 import android.support.v4.content.pm.ShortcutManagerCompat;
64 import android.support.v4.graphics.drawable.IconCompat;
65 import android.support.v4.view.GravityCompat;
66 import android.support.v4.widget.DrawerLayout;
67 import android.support.v4.widget.SwipeRefreshLayout;
68 import android.support.v7.app.ActionBar;
69 import android.support.v7.app.ActionBarDrawerToggle;
70 import android.support.v7.app.AppCompatActivity;
71 import android.support.v7.app.AppCompatDialogFragment;
72 import android.support.v7.widget.Toolbar;
73 import android.text.Editable;
74 import android.text.Spanned;
75 import android.text.TextWatcher;
76 import android.text.style.ForegroundColorSpan;
77 import android.util.Patterns;
78 import android.view.ContextMenu;
79 import android.view.GestureDetector;
80 import android.view.KeyEvent;
81 import android.view.Menu;
82 import android.view.MenuItem;
83 import android.view.MotionEvent;
84 import android.view.View;
85 import android.view.ViewGroup;
86 import android.view.WindowManager;
87 import android.view.inputmethod.InputMethodManager;
88 import android.webkit.CookieManager;
89 import android.webkit.HttpAuthHandler;
90 import android.webkit.SslErrorHandler;
91 import android.webkit.ValueCallback;
92 import android.webkit.WebBackForwardList;
93 import android.webkit.WebChromeClient;
94 import android.webkit.WebResourceResponse;
95 import android.webkit.WebStorage;
96 import android.webkit.WebView;
97 import android.webkit.WebViewClient;
98 import android.webkit.WebViewDatabase;
99 import android.widget.CursorAdapter;
100 import android.widget.EditText;
101 import android.widget.FrameLayout;
102 import android.widget.ImageView;
103 import android.widget.LinearLayout;
104 import android.widget.ListView;
105 import android.widget.ProgressBar;
106 import android.widget.RadioButton;
107 import android.widget.RelativeLayout;
108 import android.widget.TextView;
110 import com.stoutner.privacybrowser.BannerAd;
111 import com.stoutner.privacybrowser.BuildConfig;
112 import com.stoutner.privacybrowser.R;
113 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
114 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
115 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
116 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
117 import com.stoutner.privacybrowser.dialogs.DownloadLocationPermissionDialog;
118 import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
119 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
120 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
121 import com.stoutner.privacybrowser.dialogs.PinnedSslCertificateMismatchDialog;
122 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
123 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
124 import com.stoutner.privacybrowser.helpers.BlockListHelper;
125 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
126 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
127 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
128 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
129 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
131 import java.io.ByteArrayInputStream;
132 import java.io.ByteArrayOutputStream;
134 import java.io.IOException;
135 import java.io.UnsupportedEncodingException;
136 import java.net.MalformedURLException;
138 import java.net.URLDecoder;
139 import java.net.URLEncoder;
140 import java.util.ArrayList;
141 import java.util.Date;
142 import java.util.HashMap;
143 import java.util.HashSet;
144 import java.util.List;
145 import java.util.Map;
146 import java.util.Set;
148 // AppCompatActivity from android.support.v7.app.AppCompatActivity must be used to have access to the SupportActionBar until the minimum API is >= 21.
149 public class MainWebViewActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener,
150 CreateHomeScreenShortcutDialog.CreateHomeScreenSchortcutListener, DownloadFileDialog.DownloadFileListener, DownloadImageDialog.DownloadImageListener,
151 DownloadLocationPermissionDialog.DownloadLocationPermissionDialogListener, EditBookmarkDialog.EditBookmarkListener, EditBookmarkFolderDialog.EditBookmarkFolderListener,
152 HttpAuthenticationDialog.HttpAuthenticationListener, NavigationView.OnNavigationItemSelectedListener, PinnedSslCertificateMismatchDialog.PinnedSslCertificateMismatchListener,
153 SslCertificateErrorDialog.SslCertificateErrorListener, UrlHistoryDialog.UrlHistoryListener {
155 // `darkTheme` is public static so it can be accessed from `AboutActivity`, `GuideActivity`, `AddDomainDialog`, `SettingsActivity`, `DomainsActivity`, `DomainsListFragment`, `BookmarksActivity`,
156 // `BookmarksDatabaseViewActivity`, `CreateBookmarkDialog`, `CreateBookmarkFolderDialog`, `DownloadFileDialog`, `DownloadImageDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`,
157 // `EditBookmarkDatabaseViewDialog`, `HttpAuthenticationDialog`, `MoveToFolderDialog`, `SslCertificateErrorDialog`, `UrlHistoryDialog`, `ViewSslCertificateDialog`, `CreateHomeScreenShortcutDialog`,
158 // and `OrbotProxyHelper`. It is also used in `onCreate()`, `applyAppSettings()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
159 public static boolean darkTheme;
161 // `favoriteIconBitmap` is public static so it can be accessed from `CreateHomeScreenShortcutDialog`, `BookmarksActivity`, `BookmarksDatabaseViewActivity`, `CreateBookmarkDialog`,
162 // `CreateBookmarkFolderDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`, `EditBookmarkDatabaseViewDialog`, and `ViewSslCertificateDialog`. It is also used in `onCreate()`,
163 // `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onCreateHomeScreenShortcutCreate()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `applyDomainSettings()`.
164 public static Bitmap favoriteIconBitmap;
166 // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`, `CreateBookmarkDialog`, and `AddDomainDialog`.
167 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
168 public static String formattedUrlString;
170 // `sslCertificate` is public static so it can be accessed from `DomainsActivity`, `DomainsListFragment`, `DomainSettingsFragment`, `PinnedSslCertificateMismatchDialog`,
171 // and `ViewSslCertificateDialog`. It is also used in `onCreate()`.
172 public static SslCertificate sslCertificate;
174 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`.
175 public static String orbotStatus;
177 // `webViewTitle` is public static so it can be accessed from `CreateBookmarkDialog` and `CreateHomeScreenShortcutDialog`. It is also used in `onCreate()`.
178 public static String webViewTitle;
180 // `appliedUserAgentString` is public static so it can be accessed from `ViewSourceActivity`. It is also used in `applyDomainSettings()`.
181 public static String appliedUserAgentString;
183 // `reloadOnRestart` is public static so it can be accessed from `SettingsFragment`. It is also used in `onRestart()`
184 public static boolean reloadOnRestart;
186 // `reloadUrlOnRestart` is public static so it can be accessed from `SettingsFragment`. It is also used in `onRestart()`.
187 public static boolean loadUrlOnRestart;
189 // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onRestart()`.
190 public static boolean restartFromBookmarksActivity;
192 // The block list versions are public static so they can be accessed from `AboutTabFragment`. They are also used in `onCreate()`.
193 public static String easyListVersion;
194 public static String easyPrivacyVersion;
195 public static String fanboyAnnoyanceVersion;
196 public static String fanboySocialVersion;
198 // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`,
199 // `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
200 public static String currentBookmarksFolder;
202 // `domainSettingsDatabaseId` is public static so it can be accessed from `PinnedSslCertificateMismatchDialog`. It is also used in `onCreate()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
203 public static int domainSettingsDatabaseId;
205 // The pinned domain SSL Certificate variables are public static so they can be accessed from `PinnedSslCertificateMismatchDialog`. They are also used in `onCreate()` and `applyDomainSettings()`.
206 public static String pinnedDomainSslIssuedToCNameString;
207 public static String pinnedDomainSslIssuedToONameString;
208 public static String pinnedDomainSslIssuedToUNameString;
209 public static String pinnedDomainSslIssuedByCNameString;
210 public static String pinnedDomainSslIssuedByONameString;
211 public static String pinnedDomainSslIssuedByUNameString;
212 public static Date pinnedDomainSslStartDate;
213 public static Date pinnedDomainSslEndDate;
216 // `appBar` is used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applyAppSettings()`.
217 private ActionBar appBar;
219 // `navigatingHistory` is used in `onCreate()`, `onNavigationItemSelected()`, `onSslMismatchBack()`, and `applyDomainSettings()`.
220 private boolean navigatingHistory;
222 // `favoriteIconDefaultBitmap` is used in `onCreate()` and `applyDomainSettings`.
223 private Bitmap favoriteIconDefaultBitmap;
225 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, `onBackPressed()`, and `onRestart()`.
226 private DrawerLayout drawerLayout;
228 // `rootCoordinatorLayout` is used in `onCreate()` and `applyAppSettings()`.
229 private CoordinatorLayout rootCoordinatorLayout;
231 // `mainWebView` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
232 // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, and `setDisplayWebpageImages()`.
233 private WebView mainWebView;
235 // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
236 private FrameLayout fullScreenVideoFrameLayout;
238 // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu`, and `onRestart()`.
239 private SwipeRefreshLayout swipeRefreshLayout;
241 // `urlAppBarRelativeLayout` is used in `onCreate()` and `applyDomainSettings()`.
242 private RelativeLayout urlAppBarRelativeLayout;
244 // `favoriteIconImageView` is used in `onCreate()` and `applyDomainSettings()`
245 private ImageView favoriteIconImageView;
247 // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `loadUrlFromTextBox()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
248 private CookieManager cookieManager;
250 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
251 private final Map<String, String> customHeaders = new HashMap<>();
253 // `javaScriptEnabled` is also used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
254 private boolean javaScriptEnabled;
256 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applyDomainSettings()`.
257 private boolean firstPartyCookiesEnabled;
259 // `thirdPartyCookiesEnabled` used in `onCreate()`, `onPrepareOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
260 private boolean thirdPartyCookiesEnabled;
262 // `domStorageEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
263 private boolean domStorageEnabled;
265 // `saveFormDataEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
266 private boolean saveFormDataEnabled;
268 // `nightMode` is used in `onCreate()` and `applyDomainSettings()`.
269 private boolean nightMode;
271 // `swipeToRefreshEnabled` is used in `onPrepareOptionsMenu()` and `applyAppSettings()`.
272 private boolean swipeToRefreshEnabled;
274 // `displayWebpageImagesBoolean` is used in `applyAppSettings()` and `applyDomainSettings()`.
275 private boolean displayWebpageImagesBoolean;
277 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applyAppSettings()`.
278 private String homepage;
280 // `searchURL` is used in `loadURLFromTextBox()` and `applyAppSettings()`.
281 private String searchURL;
283 // The block list variables are used in `onCreate()` and `applyAppSettings()`.
284 private boolean easyListEnabled;
285 private boolean easyPrivacyEnabled;
286 private boolean fanboysAnnoyanceListEnabled;
287 private boolean fanboysSocialBlockingListEnabled;
289 // `privacyBrowserRuntime` is used in `onCreate()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
290 private Runtime privacyBrowserRuntime;
292 // `proxyThroughOrbot` is used in `onRestart()` and `applyAppSettings()`.
293 boolean proxyThroughOrbot;
295 // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
296 private boolean incognitoModeEnabled;
298 // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
299 private boolean fullScreenBrowsingModeEnabled;
301 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
302 private boolean inFullScreenBrowsingMode;
304 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
305 private boolean hideSystemBarsOnFullscreen;
307 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
308 private boolean translucentNavigationBarOnFullscreen;
310 // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
311 private boolean reapplyDomainSettingsOnRestart;
313 // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
314 private boolean reapplyAppSettingsOnRestart;
316 // `currentDomainName` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onAddDomain()`, and `applyDomainSettings()`.
317 private String currentDomainName;
319 // `ignorePinnedSslCertificateForDomain` is used in `onCreate()`, `onSslMismatchProceed()`, and `applyDomainSettings()`.
320 private boolean ignorePinnedSslCertificate;
322 // `waitingForOrbot` is used in `onCreate()` and `applyAppSettings()`.
323 private boolean waitingForOrbot;
325 // `domainSettingsApplied` is used in `prepareOptionsMenu()`, `applyDomainSettings()`, and `setDisplayWebpageImages()`.
326 private boolean domainSettingsApplied;
328 // `displayWebpageImagesInt` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
329 private int displayWebpageImagesInt;
331 // `onTheFlyDisplayImagesSet` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
332 private boolean onTheFlyDisplayImagesSet;
334 // `waitingForOrbotData` is used in `onCreate()` and `applyAppSettings()`.
335 private String waitingForOrbotHTMLString;
337 // `privateDataDirectoryString` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
338 private String privateDataDirectoryString;
340 // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
341 private LinearLayout findOnPageLinearLayout;
343 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
344 private EditText findOnPageEditText;
346 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
347 private Menu mainMenu;
349 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
350 private ActionBarDrawerToggle drawerToggle;
352 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
353 private Toolbar supportAppBar;
355 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, `loadUrl()`, and `highlightUrlText()`.
356 private EditText urlTextBox;
358 // The color spans are used in `onCreate()` and `highlightUrlText()`.
359 private ForegroundColorSpan redColorSpan;
360 private ForegroundColorSpan initialGrayColorSpan;
361 private ForegroundColorSpan finalGrayColorSpan;
363 // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
366 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
367 private SslErrorHandler sslErrorHandler;
369 // `httpAuthHandler` is used in `onCreate()`, `onHttpAuthenticationCancel()`, and `onHttpAuthenticationProceed()`.
370 private static HttpAuthHandler httpAuthHandler;
372 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
373 private InputMethodManager inputMethodManager;
375 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
376 private RelativeLayout mainWebViewRelativeLayout;
378 // `urlIsLoading` is used in `onCreate()`, `loadUrl()`, and `applyDomainSettings()`.
379 private boolean urlIsLoading;
381 // `pinnedDomainSslCertificate` is used in `onCreate()` and `applyDomainSettings()`.
382 private boolean pinnedDomainSslCertificate;
384 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
385 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
387 // `bookmarksListView` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, and `loadBookmarksFolder()`.
388 private ListView bookmarksListView;
390 // `bookmarksTitleTextView` is used in `onCreate()` and `loadBookmarksFolder()`.
391 private TextView bookmarksTitleTextView;
393 // `bookmarksCursor` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
394 private Cursor bookmarksCursor;
396 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
397 private CursorAdapter bookmarksCursorAdapter;
399 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
400 private String oldFolderNameString;
402 // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
403 private ValueCallback<Uri[]> fileChooserCallback;
405 // The download strings are used in `onCreate()` and `onRequestPermissionResult()`.
406 private String downloadUrl;
407 private String downloadContentDisposition;
408 private long downloadContentLength;
410 // `downloadImageUrl` is used in `onCreateContextMenu()` and `onRequestPermissionResult()`.
411 private String downloadImageUrl;
413 // The request codes are used in `onCreate()`, `onCreateContextMenu()`, `onCloseDownloadLocationPermissionDialog()`, and `onRequestPermissionResult()`.
414 private final int DOWNLOAD_FILE_REQUEST_CODE = 1;
415 private final int DOWNLOAD_IMAGE_REQUEST_CODE = 2;
418 // 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.
419 // Also, remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
420 @SuppressLint({"SetJavaScriptEnabled", "ClickableViewAccessibility"})
421 // Remove Android Studio's warning about deprecations. We have to use the deprecated `getColor()` until API >= 23.
422 @SuppressWarnings("deprecation")
423 protected void onCreate(Bundle savedInstanceState) {
424 // Get a handle for `sharedPreferences`. `this` references the current context.
425 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
427 // Get the theme preference.
428 darkTheme = sharedPreferences.getBoolean("dark_theme", false);
430 // Set the activity theme.
432 setTheme(R.style.PrivacyBrowserDark);
434 setTheme(R.style.PrivacyBrowserLight);
437 // Run the default commands.
438 super.onCreate(savedInstanceState);
440 // Set the content view.
441 setContentView(R.layout.main_drawerlayout);
443 // Get a handle for `inputMethodManager`.
444 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
446 // `SupportActionBar` from `android.support.v7.app.ActionBar` must be used until the minimum API is >= 21.
447 supportAppBar = findViewById(R.id.app_bar);
448 setSupportActionBar(supportAppBar);
449 appBar = getSupportActionBar();
451 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
452 assert appBar != null;
454 // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
455 appBar.setCustomView(R.layout.url_app_bar);
456 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
458 // Initialize the foreground color spans for highlighting the URLs. We have to use the deprecated `getColor()` until API >= 23.
459 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
460 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
461 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
463 // Get a handle for `urlTextBox`.
464 urlTextBox = findViewById(R.id.url_edittext);
466 // Remove the formatting from `urlTextBar` when the user is editing the text.
467 urlTextBox.setOnFocusChangeListener((View v, boolean hasFocus) -> {
468 if (hasFocus) { // The user is editing `urlTextBox`.
469 // Remove the highlighting.
470 urlTextBox.getText().removeSpan(redColorSpan);
471 urlTextBox.getText().removeSpan(initialGrayColorSpan);
472 urlTextBox.getText().removeSpan(finalGrayColorSpan);
473 } else { // The user has stopped editing `urlTextBox`.
474 // Reapply the highlighting.
479 // Set the go button on the keyboard to load the URL in `urlTextBox`.
480 urlTextBox.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
481 // If the event is a key-down event on the `enter` button, load the URL.
482 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
483 // Load the URL into the mainWebView and consume the event.
485 loadUrlFromTextBox();
486 } catch (UnsupportedEncodingException e) {
489 // If the enter key was pressed, consume the event.
492 // If any other key was pressed, do not consume the event.
497 // Set `waitingForOrbotHTMLString`.
498 waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
500 // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
501 currentDomainName = "";
502 orbotStatus = "unknown";
503 waitingForOrbot = false;
505 // Create an Orbot status `BroadcastReceiver`.
506 BroadcastReceiver orbotStatusBroadcastReceiver = new BroadcastReceiver() {
508 public void onReceive(Context context, Intent intent) {
509 // Store the content of the status message in `orbotStatus`.
510 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
512 // If we are waiting on Orbot, load the website now that Orbot is connected.
513 if (orbotStatus.equals("ON") && waitingForOrbot) {
514 // Reset `waitingForOrbot`.
515 waitingForOrbot = false;
517 // Load `formattedUrlString
518 loadUrl(formattedUrlString);
523 // Register `orbotStatusBroadcastReceiver` on `this` context.
524 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
526 // Get handles for views that need to be accessed.
527 drawerLayout = findViewById(R.id.drawerlayout);
528 rootCoordinatorLayout = findViewById(R.id.root_coordinatorlayout);
529 bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
530 bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
531 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
532 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
533 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
534 mainWebViewRelativeLayout = findViewById(R.id.main_webview_relativelayout);
535 mainWebView = findViewById(R.id.main_webview);
536 findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
537 findOnPageEditText = findViewById(R.id.find_on_page_edittext);
538 fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
539 urlAppBarRelativeLayout = findViewById(R.id.url_app_bar_relativelayout);
540 favoriteIconImageView = findViewById(R.id.favorite_icon);
542 // Set the bookmarks drawer resources according to the theme. This can't be done in the layout due to compatibility issues with the `DrawerLayout` support widget.
544 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
545 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
546 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
547 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
549 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
550 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
551 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
552 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
555 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
556 launchBookmarksActivityFab.setOnClickListener(v -> {
557 // Create an intent to launch the bookmarks activity.
558 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
560 // Include the current folder with the `Intent`.
561 bookmarksIntent.putExtra("Current Folder", currentBookmarksFolder);
564 startActivity(bookmarksIntent);
567 // Set the create new bookmark folder FAB to display the `AlertDialog`.
568 createBookmarkFolderFab.setOnClickListener(v -> {
569 // Show the `CreateBookmarkFolderDialog` `AlertDialog` and name the instance `@string/create_folder`.
570 AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
571 createBookmarkFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_folder));
574 // Set the create new bookmark FAB to display the `AlertDialog`.
575 createBookmarkFab.setOnClickListener(view -> {
576 // Show the `CreateBookmarkDialog` `AlertDialog` and name the instance `@string/create_bookmark`.
577 AppCompatDialogFragment createBookmarkDialog = new CreateBookmarkDialog();
578 createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
581 // Create a double-tap listener to toggle full-screen mode.
582 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
583 // Override `onDoubleTap()`. All other events are handled using the default settings.
585 public boolean onDoubleTap(MotionEvent event) {
586 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
587 // Toggle `inFullScreenBrowsingMode`.
588 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
590 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
591 // Hide the `appBar`.
594 // Hide the `BannerAd` in the free flavor.
595 if (BuildConfig.FLAVOR.contentEquals("free")) {
596 BannerAd.hideAd(adView);
599 // Modify the system bars.
600 if (hideSystemBarsOnFullscreen) { // Hide everything.
601 // Remove the translucent overlays.
602 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
604 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
605 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
607 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
608 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
609 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
611 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
613 // Set `rootCoordinatorLayout` to fill the whole screen.
614 rootCoordinatorLayout.setFitsSystemWindows(false);
615 } else { // Hide everything except the status and navigation bars.
616 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
617 rootCoordinatorLayout.setFitsSystemWindows(false);
619 // 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.
620 if (translucentNavigationBarOnFullscreen) {
621 // Set the navigation bar to be translucent.
622 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
625 } else { // Switch to normal viewing mode.
626 // Show the `appBar`.
629 // Show the `BannerAd` in the free flavor.
630 if (BuildConfig.FLAVOR.contentEquals("free")) {
631 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
632 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
634 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
635 adView = findViewById(R.id.adview);
638 // Remove the translucent navigation bar flag if it is set.
639 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
641 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
642 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
644 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
645 rootCoordinatorLayout.setSystemUiVisibility(0);
647 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
648 rootCoordinatorLayout.setFitsSystemWindows(true);
651 // Consume the double-tap.
653 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
659 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
660 mainWebView.setOnTouchListener((View v, MotionEvent event) -> {
661 // Call `performClick()` on the view, which is required for accessibility.
664 // Send the `event` to `gestureDetector`.
665 return gestureDetector.onTouchEvent(event);
668 // Update `findOnPageCountTextView`.
669 mainWebView.setFindListener(new WebView.FindListener() {
670 // Get a handle for `findOnPageCountTextView`.
671 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
674 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
675 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
676 // Set `findOnPageCountTextView` to `0/0`.
677 findOnPageCountTextView.setText(R.string.zero_of_zero);
678 } else if (isDoneCounting) { // There are matches.
679 // `activeMatchOrdinal` is zero-based.
680 int activeMatch = activeMatchOrdinal + 1;
682 // Build the match string.
683 String matchString = activeMatch + "/" + numberOfMatches;
685 // Set `findOnPageCountTextView`.
686 findOnPageCountTextView.setText(matchString);
691 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
692 findOnPageEditText.addTextChangedListener(new TextWatcher() {
694 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
699 public void onTextChanged(CharSequence s, int start, int before, int count) {
704 public void afterTextChanged(Editable s) {
705 // Search for the text in `mainWebView`.
706 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
710 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
711 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
712 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
713 // Hide the soft keyboard. `0` indicates no additional flags.
714 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
716 // Consume the event.
718 } else { // A different key was pressed.
719 // Do not consume the event.
724 // Implement swipe to refresh
725 swipeRefreshLayout = findViewById(R.id.swipe_refreshlayout);
726 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
727 swipeRefreshLayout.setOnRefreshListener(() -> mainWebView.reload());
729 // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
730 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
731 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
733 // Listen for touches on the navigation menu.
734 final NavigationView navigationView = findViewById(R.id.navigationview);
735 navigationView.setNavigationItemSelectedListener(this);
737 // 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.
738 final Menu navigationMenu = navigationView.getMenu();
739 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
740 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
741 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
743 // Initialize the bookmarks database helper. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
744 // The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
745 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
747 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
748 currentBookmarksFolder = "";
750 // Load the home folder, which is `""` in the database.
751 loadBookmarksFolder();
753 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
754 // Convert the id from long to int to match the format of the bookmarks database.
755 int databaseID = (int) id;
757 // Get the bookmark `Cursor` for this ID and move it to the first row.
758 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
759 bookmarkCursor.moveToFirst();
761 // Act upon the bookmark according to the type.
762 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
763 // Store the new folder name in `currentBookmarksFolder`.
764 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
766 // Load the new folder.
767 loadBookmarksFolder();
768 } else { // The selected bookmark is not a folder.
769 // Load the bookmark URL.
770 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
772 // Close the bookmarks drawer.
773 drawerLayout.closeDrawer(GravityCompat.END);
776 // Close the `Cursor`.
777 bookmarkCursor.close();
780 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
781 // Convert the database ID from `long` to `int`.
782 int databaseId = (int) id;
784 // Find out if the selected bookmark is a folder.
785 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
788 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
789 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
791 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
792 AppCompatDialogFragment editFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId);
793 editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
795 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
796 AppCompatDialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId);
797 editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
800 // Consume the event.
804 // The `DrawerListener` allows us to update the Navigation Menu.
805 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
807 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
811 public void onDrawerOpened(@NonNull View drawerView) {
815 public void onDrawerClosed(@NonNull View drawerView) {
819 public void onDrawerStateChanged(int newState) {
820 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // The drawer is opening or closing.
821 // Update the `Back`, `Forward`, and `History` menu items.
822 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
823 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
824 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
826 // Hide the keyboard (if displayed) so we can see the navigation menu. `0` indicates no additional flags.
827 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
829 // Clear the focus from `urlTextBox` if it has it.
830 urlTextBox.clearFocus();
835 // drawerToggle creates the hamburger icon at the start of the AppBar.
836 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
838 // Get a handle for the progress bar.
839 final ProgressBar progressBar = findViewById(R.id.progress_bar);
841 mainWebView.setWebChromeClient(new WebChromeClient() {
842 // Update the progress bar when a page is loading.
844 public void onProgressChanged(WebView view, int progress) {
845 // Inject the night mode CSS if night mode is enabled.
847 // `background-color: #212121` sets the background to be dark gray. `color: #BDBDBD` sets the text color to be light gray. `box-shadow: none` removes a lower underline on links
848 // used by WordPress. `text-decoration: none` removes all text underlines. `text-shadow: none` removes text shadows, which usually have a hard coded color.
849 // `border: none` removes all borders, which can also be used to underline text.
850 // `a {color: #1565C0}` sets links to be a dark blue. `!important` takes precedent over any existing sub-settings.
851 mainWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; " +
852 "style.innerHTML = '* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important;" +
853 "text-shadow: none !important; border: none !important;} a {color: #1565C0 !important;}'; parent.appendChild(style)})()", value -> {
854 // Initialize a `Handler` to display `mainWebView`.
855 Handler displayWebViewHandler = new Handler();
857 // Setup a `Runnable` to display `mainWebView` after a delay to allow the CSS to be applied.
858 Runnable displayWebViewRunnable = () -> {
859 // Only display `mainWebView` if the progress bar is one. This prevents the display of the `WebView` while it is still loading.
860 if (progressBar.getVisibility() == View.GONE) {
861 mainWebView.setVisibility(View.VISIBLE);
865 // Use `displayWebViewHandler` to delay the displaying of `mainWebView` for 500 milliseconds.
866 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
870 // Update the progress bar.
871 progressBar.setProgress(progress);
873 // Set the visibility of the progress bar.
874 if (progress < 100) {
875 // Show the progress bar.
876 progressBar.setVisibility(View.VISIBLE);
878 // Hide the progress bar.
879 progressBar.setVisibility(View.GONE);
881 // Display `mainWebView` if night mode is disabled.
882 // Because of a race condition between `applyDomainSettings` and `onPageStarted`, when night mode is set by domain settings the `WebView` may be hidden even if night mode is not
883 // currently enabled.
885 mainWebView.setVisibility(View.VISIBLE);
888 //Stop the `SwipeToRefresh` indicator if it is running
889 swipeRefreshLayout.setRefreshing(false);
893 // Set the favorite icon when it changes.
895 public void onReceivedIcon(WebView view, Bitmap icon) {
896 // Only update the favorite icon if the website has finished loading.
897 if (progressBar.getVisibility() == View.GONE) {
898 // Save a copy of the favorite icon.
899 favoriteIconBitmap = icon;
901 // Place the favorite icon in the appBar.
902 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
906 // Save a copy of the title when it changes.
908 public void onReceivedTitle(WebView view, String title) {
909 // Save a copy of the title.
910 webViewTitle = title;
913 // Enter full screen video.
915 public void onShowCustomView(View view, CustomViewCallback callback) {
916 // Pause the ad if this is the free flavor.
917 if (BuildConfig.FLAVOR.contentEquals("free")) {
918 BannerAd.pauseAd(adView);
921 // Remove the translucent overlays.
922 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
924 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
925 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
927 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
928 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
929 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
931 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
933 // Set `rootCoordinatorLayout` to fill the entire screen.
934 rootCoordinatorLayout.setFitsSystemWindows(false);
936 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
937 fullScreenVideoFrameLayout.addView(view);
938 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
941 // Exit full screen video.
943 public void onHideCustomView() {
944 // Hide `fullScreenVideoFrameLayout`.
945 fullScreenVideoFrameLayout.removeAllViews();
946 fullScreenVideoFrameLayout.setVisibility(View.GONE);
948 // Add the translucent status flag. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
949 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
951 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars. This also clears the `SYSTEM_UI` flags.
952 rootCoordinatorLayout.setFitsSystemWindows(true);
954 // Show the ad if this is the free flavor.
955 if (BuildConfig.FLAVOR.contentEquals("free")) {
956 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
957 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
959 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
960 adView = findViewById(R.id.adview);
966 public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
967 // Show the file chooser if the device is running API >= 21.
968 if (Build.VERSION.SDK_INT >= 21) {
969 // Store the file path callback.
970 fileChooserCallback = filePathCallback;
972 // Create an intent to open a chooser based ont the file chooser parameters.
973 Intent fileChooserIntent = fileChooserParams.createIntent();
975 // Open the file chooser. Currently only one `startActivityForResult` exists in this activity, so the request code, used to differentiate them, is simply `0`.
976 startActivityForResult(fileChooserIntent, 0);
982 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
983 registerForContextMenu(mainWebView);
985 // Allow the downloading of files.
986 mainWebView.setDownloadListener((String url, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
987 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
988 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
989 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
991 // Store the variables for future use by `onRequestPermissionsResult()`.
993 downloadContentDisposition = contentDisposition;
994 downloadContentLength = contentLength;
996 // Show a dialog if the user has previously denied the permission.
997 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
998 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
999 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
1001 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
1002 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
1003 } else { // Show the permission request directly.
1004 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
1005 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
1007 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
1008 // Get a handle for the download file alert dialog.
1009 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
1011 // Show the download file alert dialog.
1012 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
1016 // Allow pinch to zoom.
1017 mainWebView.getSettings().setBuiltInZoomControls(true);
1019 // Hide zoom controls.
1020 mainWebView.getSettings().setDisplayZoomControls(false);
1022 // Set `mainWebView` to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
1023 mainWebView.getSettings().setUseWideViewPort(true);
1025 // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
1026 mainWebView.getSettings().setLoadWithOverviewMode(true);
1028 // Explicitly disable geolocation.
1029 mainWebView.getSettings().setGeolocationEnabled(false);
1031 // Initialize cookieManager.
1032 cookieManager = CookieManager.getInstance();
1034 // 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).
1035 customHeaders.put("X-Requested-With", "");
1037 // 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.
1038 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
1040 // Get the intent that started the app.
1041 final Intent launchingIntent = getIntent();
1043 // Extract the launching intent data as `launchingIntentUriData`.
1044 final Uri launchingIntentUriData = launchingIntent.getData();
1046 // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
1047 if (launchingIntentUriData != null) {
1048 formattedUrlString = launchingIntentUriData.toString();
1051 // Get a handle for the `Runtime`.
1052 privacyBrowserRuntime = Runtime.getRuntime();
1054 // Store the application's private data directory.
1055 privateDataDirectoryString = getApplicationInfo().dataDir;
1056 // `dataDir` will vary, but will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
1058 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
1059 inFullScreenBrowsingMode = false;
1061 // Initialize AdView for the free flavor.
1062 adView = findViewById(R.id.adview);
1064 // Initialize the privacy settings variables.
1065 javaScriptEnabled = false;
1066 firstPartyCookiesEnabled = false;
1067 thirdPartyCookiesEnabled = false;
1068 domStorageEnabled = false;
1069 saveFormDataEnabled = false;
1072 // Initialize `webViewTitle`.
1073 webViewTitle = getString(R.string.no_title);
1075 // Initialize `favoriteIconBitmap`. `ContextCompat` must be used until API >= 21.
1076 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
1077 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
1078 assert favoriteIconBitmapDrawable != null;
1079 favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
1081 // If the favorite icon is null, load the default.
1082 if (favoriteIconBitmap == null) {
1083 favoriteIconBitmap = favoriteIconDefaultBitmap;
1086 // Apply the app settings from the shared preferences.
1089 // Instantiate the block list helper.
1090 BlockListHelper blockListHelper = new BlockListHelper();
1092 // Parse the block lists.
1093 final ArrayList<List<String[]>> easyList = blockListHelper.parseBlockList(getAssets(), "blocklists/easylist.txt");
1094 final ArrayList<List<String[]>> easyPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/easyprivacy.txt");
1095 final ArrayList<List<String[]>> fanboyAnnoyance = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-annoyance.txt");
1096 final ArrayList<List<String[]>> fanboySocial = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-social.txt");
1098 // Store the list versions.
1099 easyListVersion = easyList.get(0).get(0)[0];
1100 easyPrivacyVersion = easyPrivacy.get(0).get(0)[0];
1101 fanboyAnnoyanceVersion = fanboyAnnoyance.get(0).get(0)[0];
1102 fanboySocialVersion = fanboySocial.get(0).get(0)[0];
1104 mainWebView.setWebViewClient(new WebViewClient() {
1105 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
1106 // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
1107 @SuppressWarnings("deprecation")
1109 public boolean shouldOverrideUrlLoading(WebView view, String url) {
1110 if (url.startsWith("http")) { // Load the URL in Privacy Browser.
1111 // Apply the domain settings for the new URL.
1112 applyDomainSettings(url, true, false);
1114 // Returning false causes the current `WebView` to handle the URL and prevents it from adding redirects to the history list.
1116 } else if (url.startsWith("mailto:")) { // Load the email address in an external email program.
1117 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1118 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1120 // Parse the url and set it as the data for the intent.
1121 emailIntent.setData(Uri.parse(url));
1123 // Open the email program in a new task instead of as part of Privacy Browser.
1124 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1127 startActivity(emailIntent);
1129 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1131 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
1132 // Open the dialer and load the phone number, but wait for the user to place the call.
1133 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
1135 // Add the phone number to the intent.
1136 dialIntent.setData(Uri.parse(url));
1138 // Open the dialer in a new task instead of as part of Privacy Browser.
1139 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1142 startActivity(dialIntent);
1144 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1146 } else { // Load a system chooser to select an app that can handle the URL.
1147 // Open an app that can handle the URL.
1148 Intent genericIntent = new Intent(Intent.ACTION_VIEW);
1150 // Add the URL to the intent.
1151 genericIntent.setData(Uri.parse(url));
1153 // List all apps that can handle the URL instead of just opening the first one.
1154 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
1156 // Open the app in a new task instead of as part of Privacy Browser.
1157 genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1159 // Start the app or display a snackbar if no app is available to handle the URL.
1161 startActivity(genericIntent);
1162 } catch (ActivityNotFoundException exception) {
1163 Snackbar.make(mainWebView, getString(R.string.unrecognized_url) + " " + url, Snackbar.LENGTH_SHORT).show();
1166 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1171 // Check requests against the block lists. The deprecated `shouldInterceptRequest` must be used until minimum API >= 21.
1172 @SuppressWarnings("deprecation")
1174 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
1175 // Create an empty web resource response to be used if the resource request is blocked.
1176 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
1178 // Check EasyList if it is enabled.
1179 if (easyListEnabled) {
1180 if (blockListHelper.isBlocked(formattedUrlString, url, easyList)) {
1181 // The resource request was blocked. Return an empty web resource response.
1182 return emptyWebResourceResponse;
1186 // Check EasyPrivacy if it is enabled.
1187 if (easyPrivacyEnabled) {
1188 if (blockListHelper.isBlocked(formattedUrlString, url, easyPrivacy)) {
1189 // The resource request was blocked. Return an empty web resource response.
1190 return emptyWebResourceResponse;
1194 // Check Fanboy’s Annoyance List if it is enabled.
1195 if (fanboysAnnoyanceListEnabled) {
1196 if (blockListHelper.isBlocked(formattedUrlString, url, fanboyAnnoyance)) {
1197 // The resource request was blocked. Return an empty web resource response.
1198 return emptyWebResourceResponse;
1200 } else if (fanboysSocialBlockingListEnabled){ // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
1201 if (blockListHelper.isBlocked(formattedUrlString, url, fanboySocial)) {
1202 // The resource request was blocked. Return an empty web resource response.
1203 return emptyWebResourceResponse;
1207 // The resource request has not been blocked. `return null` loads the requested resource.
1211 // Handle HTTP authentication requests.
1213 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
1214 // Store `handler` so it can be accessed from `onHttpAuthenticationCancel()` and `onHttpAuthenticationProceed()`.
1215 httpAuthHandler = handler;
1217 // Display the HTTP authentication dialog.
1218 AppCompatDialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm);
1219 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
1222 // Update the URL in urlTextBox when the page starts to load.
1224 public void onPageStarted(WebView view, String url, Bitmap favicon) {// If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
1226 mainWebView.setVisibility(View.INVISIBLE);
1229 // Hide the keyboard. `0` indicates no additional flags.
1230 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1232 // Check to see if we are waiting on Orbot.
1233 if (!waitingForOrbot) { // We are not waiting on Orbot, so we need to process the URL.
1234 // 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.
1235 formattedUrlString = url;
1237 // Display the formatted URL text.
1238 urlTextBox.setText(formattedUrlString);
1240 // Apply text highlighting to `urlTextBox`.
1243 // Apply any custom domain settings if the URL was loaded by navigating history.
1244 if (navigatingHistory) {
1245 applyDomainSettings(url, true, false);
1248 // 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.
1249 urlIsLoading = true;
1253 // It is necessary to update `formattedUrlString` and `urlTextBox` after the page finishes loading because the final URL can change during load.
1255 public void onPageFinished(WebView view, String url) {
1256 // Flush any cookies to persistent storage. `CookieManager` has become very lazy about flushing cookies in recent versions.
1257 if (firstPartyCookiesEnabled && Build.VERSION.SDK_INT >= 21) {
1258 cookieManager.flush();
1261 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
1262 urlIsLoading = false;
1264 // Clear the cache and history if Incognito Mode is enabled.
1265 if (incognitoModeEnabled) {
1266 // Clear the cache. `true` includes disk files.
1267 mainWebView.clearCache(true);
1269 // Clear the back/forward history.
1270 mainWebView.clearHistory();
1272 // Manually delete cache folders.
1274 // Delete the main cache directory.
1275 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1277 // Delete the secondary `Service Worker` cache directory.
1278 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1279 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1280 } catch (IOException e) {
1281 // Do nothing if an error is thrown.
1285 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
1286 if (!waitingForOrbot) {
1287 // Check to see if `WebView` has set `url` to be `about:blank`.
1288 if (url.equals("about:blank")) { // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
1289 // Set `formattedUrlString` to `""`.
1290 formattedUrlString = "";
1292 urlTextBox.setText(formattedUrlString);
1294 // Request focus for `urlTextBox`.
1295 urlTextBox.requestFocus();
1297 // Display the keyboard.
1298 inputMethodManager.showSoftInput(urlTextBox, 0);
1300 // Apply the domain settings. This clears any settings from the previous domain.
1301 applyDomainSettings(formattedUrlString, true, false);
1302 } else { // `WebView` has loaded a webpage.
1303 // Set `formattedUrlString`.
1304 formattedUrlString = url;
1306 // Only update `urlTextBox` if the user is not typing in it.
1307 if (!urlTextBox.hasFocus()) {
1308 // Display the formatted URL text.
1309 urlTextBox.setText(formattedUrlString);
1311 // Apply text highlighting to `urlTextBox`.
1316 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
1317 sslCertificate = mainWebView.getCertificate();
1319 // 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.
1320 if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate) {
1321 // Initialize the current SSL certificate variables.
1322 String currentWebsiteIssuedToCName = "";
1323 String currentWebsiteIssuedToOName = "";
1324 String currentWebsiteIssuedToUName = "";
1325 String currentWebsiteIssuedByCName = "";
1326 String currentWebsiteIssuedByOName = "";
1327 String currentWebsiteIssuedByUName = "";
1328 Date currentWebsiteSslStartDate = null;
1329 Date currentWebsiteSslEndDate = null;
1332 // Extract the individual pieces of information from the current website SSL certificate if it is not null.
1333 if (sslCertificate != null) {
1334 currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
1335 currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
1336 currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
1337 currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
1338 currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
1339 currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
1340 currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
1341 currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
1344 // 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`.
1345 String currentWebsiteSslStartDateString = "";
1346 String currentWebsiteSslEndDateString = "";
1347 String pinnedDomainSslStartDateString = "";
1348 String pinnedDomainSslEndDateString = "";
1350 // Convert the `Dates` to `Strings` if they are not `null`.
1351 if (currentWebsiteSslStartDate != null) {
1352 currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
1355 if (currentWebsiteSslEndDate != null) {
1356 currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
1359 if (pinnedDomainSslStartDate != null) {
1360 pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
1363 if (pinnedDomainSslEndDate != null) {
1364 pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
1367 // Check to see if the pinned SSL certificate matches the current website certificate.
1368 if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) ||
1369 !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) || !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) ||
1370 !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
1371 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) {
1372 // The pinned SSL certificate doesn't match the current domain certificate.
1373 //Display the pinned SSL certificate mismatch `AlertDialog`.
1374 AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
1375 pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
1381 // Handle SSL Certificate errors.
1383 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
1384 // Get the current website SSL certificate.
1385 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
1387 // Extract the individual pieces of information from the current website SSL certificate.
1388 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
1389 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
1390 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
1391 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
1392 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
1393 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
1394 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
1395 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
1397 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
1398 if (pinnedDomainSslCertificate &&
1399 currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) &&
1400 currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) && currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) &&
1401 currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
1402 currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) {
1403 // An SSL certificate is pinned and matches the current domain certificate.
1404 // Proceed to the website without displaying an error.
1406 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
1407 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
1408 sslErrorHandler = handler;
1410 // Display the SSL error `AlertDialog`.
1411 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
1412 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
1417 // Load the website if not waiting for Orbot to connect.
1418 if (!waitingForOrbot) {
1419 loadUrl(formattedUrlString);
1424 protected void onNewIntent(Intent intent) {
1425 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1428 // Check to see if the intent contains a new URL.
1429 if (intent.getData() != null) {
1430 // Get the intent data and convert it to a string.
1431 final Uri intentUriData = intent.getData();
1432 formattedUrlString = intentUriData.toString();
1434 // Load the website.
1435 loadUrl(formattedUrlString);
1437 // Close the navigation drawer if it is open.
1438 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1439 drawerLayout.closeDrawer(GravityCompat.START);
1442 // Close the bookmarks drawer if it is open.
1443 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
1444 drawerLayout.closeDrawer(GravityCompat.END);
1447 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1448 mainWebView.requestFocus();
1453 public void onRestart() {
1454 // Run the default commands.
1457 // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
1458 if (proxyThroughOrbot) {
1459 // Request Orbot to start. If Orbot is already running no hard will be caused by this request.
1460 Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
1462 // Send the intent to the Orbot package.
1463 orbotIntent.setPackage("org.torproject.android");
1466 sendBroadcast(orbotIntent);
1469 // Apply the app settings if returning from the Settings activity..
1470 if (reapplyAppSettingsOnRestart) {
1471 // Apply the app settings.
1474 // Reload the webpage if displaying of images has been disabled in the Settings activity.
1475 if (reloadOnRestart) {
1476 // Reload `mainWebView`.
1477 mainWebView.reload();
1479 // Reset `reloadOnRestartBoolean`.
1480 reloadOnRestart = false;
1483 // Reset the return from settings flag.
1484 reapplyAppSettingsOnRestart = false;
1487 // Apply the domain settings if returning from the Domains activity.
1488 if (reapplyDomainSettingsOnRestart) {
1489 // Reapply the domain settings.
1490 applyDomainSettings(formattedUrlString, false, true);
1492 // Reset `reapplyDomainSettingsOnRestart`.
1493 reapplyDomainSettingsOnRestart = false;
1496 // Load the URL on restart to apply changes to night mode.
1497 if (loadUrlOnRestart) {
1498 // Load the current `formattedUrlString`.
1499 loadUrl(formattedUrlString);
1501 // Reset `loadUrlOnRestart.
1502 loadUrlOnRestart = false;
1505 // Update the bookmarks drawer if returning from the Bookmarks activity.
1506 if (restartFromBookmarksActivity) {
1507 // Close the bookmarks drawer.
1508 drawerLayout.closeDrawer(GravityCompat.END);
1510 // Reload the bookmarks drawer.
1511 loadBookmarksFolder();
1513 // Reset `restartFromBookmarksActivity`.
1514 restartFromBookmarksActivity = false;
1517 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
1518 updatePrivacyIcons(true);
1521 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1523 public void onResume() {
1524 // Run the default commands.
1527 // Resume JavaScript (if enabled).
1528 mainWebView.resumeTimers();
1530 // Resume `mainWebView`.
1531 mainWebView.onResume();
1533 // Resume the adView for the free flavor.
1534 if (BuildConfig.FLAVOR.contentEquals("free")) {
1535 BannerAd.resumeAd(adView);
1540 public void onPause() {
1541 // Pause `mainWebView`.
1542 mainWebView.onPause();
1544 // Stop all JavaScript.
1545 mainWebView.pauseTimers();
1547 // Pause the adView or it will continue to consume resources in the background on the free flavor.
1548 if (BuildConfig.FLAVOR.contentEquals("free")) {
1549 BannerAd.pauseAd(adView);
1556 public boolean onCreateOptionsMenu(Menu menu) {
1557 // Inflate the menu; this adds items to the action bar if it is present.
1558 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1560 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1563 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1564 updatePrivacyIcons(false);
1566 // Get handles for the menu items.
1567 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1568 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1569 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1570 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1572 // Only display third-party cookies if SDK >= 21
1573 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1575 // Get the shared preference values. `this` references the current context.
1576 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1578 // Set the status of the additional app bar icons. The default is `false`.
1579 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
1580 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1581 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1582 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1583 } else { //Do not display the additional icons.
1584 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1585 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1586 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1593 public boolean onPrepareOptionsMenu(Menu menu) {
1594 // Get handles for the menu items.
1595 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
1596 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1597 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1598 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1599 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1600 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
1601 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1602 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1603 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);
1604 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1605 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1606 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1608 // Set the text for the domain menu item.
1609 if (domainSettingsApplied) {
1610 addOrEditDomain.setTitle(R.string.edit_domain_settings);
1612 addOrEditDomain.setTitle(R.string.add_domain_settings);
1615 // Set the status of the menu item checkboxes.
1616 toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1617 toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1618 toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1619 toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);
1620 displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1622 // Enable third-party cookies if first-party cookies are enabled.
1623 toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1625 // Enable `DOM Storage` if JavaScript is enabled.
1626 toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
1628 // Enable `Clear Cookies` if there are any.
1629 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1631 // Get a count of the number of files in the `Local Storage` directory.
1632 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1633 int localStorageDirectoryNumberOfFiles = 0;
1634 if (localStorageDirectory.exists()) {
1635 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1638 // Get a count of the number of files in the `IndexedDB` directory.
1639 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1640 int indexedDBDirectoryNumberOfFiles = 0;
1641 if (indexedDBDirectory.exists()) {
1642 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1645 // Enable `Clear DOM Storage` if there is any.
1646 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1648 // Enable `Clear Form Data` is there is any.
1649 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1650 clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
1652 // Enable `Clear Data` if any of the submenu items are enabled.
1653 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
1655 // Initialize font size variables.
1656 int fontSize = mainWebView.getSettings().getTextZoom();
1657 String fontSizeTitle;
1658 MenuItem selectedFontSizeMenuItem;
1660 // Prepare the font size title and current size menu item.
1663 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
1664 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1668 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
1669 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1673 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
1674 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1678 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1679 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1683 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
1684 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1688 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
1689 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1693 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
1694 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1698 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
1699 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1703 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1704 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1708 // Set the font size title and select the current size menu item.
1709 fontSizeMenuItem.setTitle(fontSizeTitle);
1710 selectedFontSizeMenuItem.setChecked(true);
1712 // Only show `Refresh` if `swipeToRefresh` is disabled.
1713 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
1715 // Run all the other default commands.
1716 super.onPrepareOptionsMenu(menu);
1718 // Display the menu.
1723 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1724 @SuppressLint("SetJavaScriptEnabled")
1725 // removeAllCookies is deprecated, but it is required for API < 21.
1726 @SuppressWarnings("deprecation")
1727 public boolean onOptionsItemSelected(MenuItem menuItem) {
1728 // Get the selected menu item ID.
1729 int menuItemId = menuItem.getItemId();
1731 // Set the commands that relate to the menu entries.
1732 switch (menuItemId) {
1733 case R.id.add_or_edit_domain:
1734 if (domainSettingsApplied) { // Edit the current domain settings.
1735 // Reapply the domain settings on returning to `MainWebViewActivity`.
1736 reapplyDomainSettingsOnRestart = true;
1737 currentDomainName = "";
1739 // Create an intent to launch the domains activity.
1740 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1742 // Put extra information instructing the domains activity to directly load the current domain and close on back instread of returning to the domains list.
1743 domainsIntent.putExtra("loadDomain", domainSettingsDatabaseId);
1744 domainsIntent.putExtra("closeOnBack", true);
1747 startActivity(domainsIntent);
1748 } else { // Add a new domain.
1749 // Apply the new domain settings on returning to `MainWebViewActivity`.
1750 reapplyDomainSettingsOnRestart = true;
1751 currentDomainName = "";
1753 // Get the current domain
1754 Uri currentUri = Uri.parse(formattedUrlString);
1755 String currentDomain = currentUri.getHost();
1757 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1758 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1760 // Create the domain and store the database ID.
1761 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1763 // Create an intent to launch the domains activity.
1764 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1766 // Put extra information instructing the domains activity to directly load the new domain and close on back instead of returning to the domains list.
1767 domainsIntent.putExtra("loadDomain", newDomainDatabaseId);
1768 domainsIntent.putExtra("closeOnBack", true);
1771 startActivity(domainsIntent);
1775 case R.id.toggle_javascript:
1776 // Switch the status of javaScriptEnabled.
1777 javaScriptEnabled = !javaScriptEnabled;
1779 // Apply the new JavaScript status.
1780 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1782 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1783 updatePrivacyIcons(true);
1785 // Display a `Snackbar`.
1786 if (javaScriptEnabled) { // JavaScrip is enabled.
1787 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1788 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
1789 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1790 } else { // Privacy mode.
1791 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1794 // Reload the WebView.
1795 mainWebView.reload();
1798 case R.id.toggle_first_party_cookies:
1799 // Switch the status of firstPartyCookiesEnabled.
1800 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1802 // Update the menu checkbox.
1803 menuItem.setChecked(firstPartyCookiesEnabled);
1805 // Apply the new cookie status.
1806 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1808 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1809 updatePrivacyIcons(true);
1811 // Display a `Snackbar`.
1812 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1813 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1814 } else if (javaScriptEnabled){ // JavaScript is still enabled.
1815 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1816 } else { // Privacy mode.
1817 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1820 // Reload the WebView.
1821 mainWebView.reload();
1824 case R.id.toggle_third_party_cookies:
1825 if (Build.VERSION.SDK_INT >= 21) {
1826 // Switch the status of thirdPartyCookiesEnabled.
1827 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1829 // Update the menu checkbox.
1830 menuItem.setChecked(thirdPartyCookiesEnabled);
1832 // Apply the new cookie status.
1833 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1835 // Display a `Snackbar`.
1836 if (thirdPartyCookiesEnabled) {
1837 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1839 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1842 // Reload the WebView.
1843 mainWebView.reload();
1844 } // Else do nothing because SDK < 21.
1847 case R.id.toggle_dom_storage:
1848 // Switch the status of domStorageEnabled.
1849 domStorageEnabled = !domStorageEnabled;
1851 // Update the menu checkbox.
1852 menuItem.setChecked(domStorageEnabled);
1854 // Apply the new DOM Storage status.
1855 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1857 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1858 updatePrivacyIcons(true);
1860 // Display a `Snackbar`.
1861 if (domStorageEnabled) {
1862 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1864 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1867 // Reload the WebView.
1868 mainWebView.reload();
1871 case R.id.toggle_save_form_data:
1872 // Switch the status of saveFormDataEnabled.
1873 saveFormDataEnabled = !saveFormDataEnabled;
1875 // Update the menu checkbox.
1876 menuItem.setChecked(saveFormDataEnabled);
1878 // Apply the new form data status.
1879 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1881 // Display a `Snackbar`.
1882 if (saveFormDataEnabled) {
1883 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1885 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1888 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1889 updatePrivacyIcons(true);
1891 // Reload the WebView.
1892 mainWebView.reload();
1895 case R.id.clear_cookies:
1896 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1897 .setAction(R.string.undo, v -> {
1898 // Do nothing because everything will be handled by `onDismissed()` below.
1900 .addCallback(new Snackbar.Callback() {
1902 public void onDismissed(Snackbar snackbar, int event) {
1904 // The user pushed the `Undo` button.
1905 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1909 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1911 // `cookieManager.removeAllCookie()` varies by SDK.
1912 if (Build.VERSION.SDK_INT < 21) {
1913 cookieManager.removeAllCookie();
1915 // `null` indicates no callback.
1916 cookieManager.removeAllCookies(null);
1924 case R.id.clear_dom_storage:
1925 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1926 .setAction(R.string.undo, v -> {
1927 // Do nothing because everything will be handled by `onDismissed()` below.
1929 .addCallback(new Snackbar.Callback() {
1931 public void onDismissed(Snackbar snackbar, int event) {
1933 // The user pushed the `Undo` button.
1934 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1938 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1940 // Delete the DOM Storage.
1941 WebStorage webStorage = WebStorage.getInstance();
1942 webStorage.deleteAllData();
1944 // Manually delete the DOM storage files and directories.
1946 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1947 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1949 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1950 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1951 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1952 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1953 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1954 } catch (IOException e) {
1955 // Do nothing if an error is thrown.
1963 case R.id.clear_form_data:
1964 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1965 .setAction(R.string.undo, v -> {
1966 // Do nothing because everything will be handled by `onDismissed()` below.
1968 .addCallback(new Snackbar.Callback() {
1970 public void onDismissed(Snackbar snackbar, int event) {
1972 // The user pushed the `Undo` button.
1973 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1977 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1979 // Delete the form data.
1980 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1981 mainWebViewDatabase.clearFormData();
1988 case R.id.font_size_twenty_five_percent:
1989 mainWebView.getSettings().setTextZoom(25);
1992 case R.id.font_size_fifty_percent:
1993 mainWebView.getSettings().setTextZoom(50);
1996 case R.id.font_size_seventy_five_percent:
1997 mainWebView.getSettings().setTextZoom(75);
2000 case R.id.font_size_one_hundred_percent:
2001 mainWebView.getSettings().setTextZoom(100);
2004 case R.id.font_size_one_hundred_twenty_five_percent:
2005 mainWebView.getSettings().setTextZoom(125);
2008 case R.id.font_size_one_hundred_fifty_percent:
2009 mainWebView.getSettings().setTextZoom(150);
2012 case R.id.font_size_one_hundred_seventy_five_percent:
2013 mainWebView.getSettings().setTextZoom(175);
2016 case R.id.font_size_two_hundred_percent:
2017 mainWebView.getSettings().setTextZoom(200);
2020 case R.id.display_images:
2021 if (mainWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
2022 mainWebView.getSettings().setLoadsImagesAutomatically(false);
2023 mainWebView.reload();
2024 } else { // Images are not currently loaded automatically.
2025 mainWebView.getSettings().setLoadsImagesAutomatically(true);
2028 // Set `onTheFlyDisplayImagesSet`.
2029 onTheFlyDisplayImagesSet = true;
2033 // Setup the share string.
2034 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
2036 // Create the share intent.
2037 Intent shareIntent = new Intent();
2038 shareIntent.setAction(Intent.ACTION_SEND);
2039 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
2040 shareIntent.setType("text/plain");
2043 startActivity(Intent.createChooser(shareIntent, "Share URL"));
2046 case R.id.find_on_page:
2047 // Hide the URL app bar.
2048 supportAppBar.setVisibility(View.GONE);
2050 // Show the Find on Page `RelativeLayout`.
2051 findOnPageLinearLayout.setVisibility(View.VISIBLE);
2053 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android.
2054 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
2055 findOnPageEditText.postDelayed(() -> {
2056 // Set the focus on `findOnPageEditText`.
2057 findOnPageEditText.requestFocus();
2059 // Display the keyboard. `0` sets no input flags.
2060 inputMethodManager.showSoftInput(findOnPageEditText, 0);
2065 // Get a `PrintManager` instance.
2066 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
2068 // Convert `mainWebView` to `printDocumentAdapter`.
2069 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
2071 // Remove the lint error below that `printManager` might be `null`.
2072 assert printManager != null;
2074 // Print the document. The print attributes are `null`.
2075 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
2078 case R.id.view_source:
2079 // Launch the Vew Source activity.
2080 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
2081 startActivity(viewSourceIntent);
2084 case R.id.add_to_homescreen:
2085 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
2086 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
2087 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2089 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
2093 mainWebView.reload();
2097 // Don't consume the event.
2098 return super.onOptionsItemSelected(menuItem);
2102 // removeAllCookies is deprecated, but it is required for API < 21.
2103 @SuppressWarnings("deprecation")
2105 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2106 int menuItemId = menuItem.getItemId();
2108 switch (menuItemId) {
2114 if (mainWebView.canGoBack()) {
2115 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2116 navigatingHistory = true;
2118 // Load the previous website in the history.
2119 mainWebView.goBack();
2124 if (mainWebView.canGoForward()) {
2125 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2126 navigatingHistory = true;
2128 // Load the next website in the history.
2129 mainWebView.goForward();
2134 // Get the `WebBackForwardList`.
2135 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
2137 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
2138 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
2139 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2142 case R.id.downloads:
2143 // Launch the system Download Manager.
2144 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2146 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2147 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2149 startActivity(downloadManagerIntent);
2153 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2154 reapplyDomainSettingsOnRestart = true;
2155 currentDomainName = "";
2157 // Launch `DomainsActivity`.
2158 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2159 startActivity(domainsIntent);
2163 // Set the flag to reapply app settings on restart when returning from Settings.
2164 reapplyAppSettingsOnRestart = true;
2166 // Set the flag to reapply the domain settings on restart when returning from Settings.
2167 reapplyDomainSettingsOnRestart = true;
2168 currentDomainName = "";
2170 // Launch `SettingsActivity`.
2171 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2172 startActivity(settingsIntent);
2176 // Launch `GuideActivity`.
2177 Intent guideIntent = new Intent(this, GuideActivity.class);
2178 startActivity(guideIntent);
2182 // Launch `AboutActivity`.
2183 Intent aboutIntent = new Intent(this, AboutActivity.class);
2184 startActivity(aboutIntent);
2187 case R.id.clearAndExit:
2188 // Get a handle for `sharedPreferences`. `this` references the current context.
2189 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2191 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2194 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2195 // The command to remove cookies changed slightly in API 21.
2196 if (Build.VERSION.SDK_INT >= 21) {
2197 cookieManager.removeAllCookies(null);
2199 cookieManager.removeAllCookie();
2202 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2204 // We have to use two commands because `Runtime.exec()` does not like `*`.
2205 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2206 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2207 } catch (IOException e) {
2208 // Do nothing if an error is thrown.
2212 // Clear DOM storage.
2213 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2214 // Ask `WebStorage` to clear the DOM storage.
2215 WebStorage webStorage = WebStorage.getInstance();
2216 webStorage.deleteAllData();
2218 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2220 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2221 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2223 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2224 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2225 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2226 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2227 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2228 } catch (IOException e) {
2229 // Do nothing if an error is thrown.
2234 if (clearEverything || sharedPreferences.getBoolean("clear_form_data", true)) {
2235 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
2236 webViewDatabase.clearFormData();
2238 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2240 // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2241 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
2242 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
2243 } catch (IOException e) {
2244 // Do nothing if an error is thrown.
2249 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2250 // `true` includes disk files.
2251 mainWebView.clearCache(true);
2253 // Manually delete the cache directories.
2255 // Delete the main cache directory.
2256 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2258 // Delete the secondary `Service Worker` cache directory.
2259 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2260 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2261 } catch (IOException e) {
2262 // Do nothing if an error is thrown.
2266 // Clear SSL certificate preferences.
2267 mainWebView.clearSslPreferences();
2269 // Clear the back/forward history.
2270 mainWebView.clearHistory();
2272 // Clear `formattedUrlString`.
2273 formattedUrlString = null;
2275 // Clear `customHeaders`.
2276 customHeaders.clear();
2278 // Detach all views from `mainWebViewRelativeLayout`.
2279 mainWebViewRelativeLayout.removeAllViews();
2281 // Destroy the internal state of `mainWebView`.
2282 mainWebView.destroy();
2284 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
2285 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
2286 if (clearEverything) {
2288 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
2289 } catch (IOException e) {
2290 // Do nothing if an error is thrown.
2294 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
2295 if (Build.VERSION.SDK_INT >= 21) {
2296 finishAndRemoveTask();
2301 // Remove the terminated program from RAM. The status code is `0`.
2306 // Close the navigation drawer.
2307 drawerLayout.closeDrawer(GravityCompat.START);
2312 public void onPostCreate(Bundle savedInstanceState) {
2313 super.onPostCreate(savedInstanceState);
2315 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
2316 drawerToggle.syncState();
2320 public void onConfigurationChanged(Configuration newConfig) {
2321 super.onConfigurationChanged(newConfig);
2323 // Reload the ad for the free flavor if we are not in full screen mode.
2324 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2326 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2328 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2329 adView = findViewById(R.id.adview);
2332 // `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:
2333 // https://code.google.com/p/android/issues/detail?id=20493#c8
2334 // ActivityCompat.invalidateOptionsMenu(this);
2338 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2339 // Store the `HitTestResult`.
2340 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
2343 final String imageUrl;
2344 final String linkUrl;
2346 // Get a handle for the `ClipboardManager`.
2347 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2349 // Remove the lint errors below that `clipboardManager` might be `null`.
2350 assert clipboardManager != null;
2352 switch (hitTestResult.getType()) {
2353 // `SRC_ANCHOR_TYPE` is a link.
2354 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2355 // Get the target URL.
2356 linkUrl = hitTestResult.getExtra();
2358 // Set the target URL as the title of the `ContextMenu`.
2359 menu.setHeaderTitle(linkUrl);
2361 // Add a Load URL entry.
2362 menu.add(R.string.load_url).setOnMenuItemClickListener((MenuItem item) -> {
2367 // Add a Copy URL entry.
2368 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2369 // Save the link URL in a `ClipData`.
2370 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2372 // Set the `ClipData` as the clipboard's primary clip.
2373 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2377 // Add a Download URL entry.
2378 menu.add(R.string.download_url).setOnMenuItemClickListener((MenuItem item) -> {
2379 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2380 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2381 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2383 // Store the variables for future use by `onRequestPermissionsResult()`.
2384 downloadUrl = linkUrl;
2385 downloadContentDisposition = "none";
2386 downloadContentLength = -1;
2388 // Show a dialog if the user has previously denied the permission.
2389 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2390 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
2391 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
2393 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
2394 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2395 } else { // Show the permission request directly.
2396 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
2397 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2399 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2400 // Get a handle for the download file alert dialog.
2401 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(linkUrl, "none", -1);
2403 // Show the download file alert dialog.
2404 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2409 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2410 menu.add(R.string.cancel);
2413 case WebView.HitTestResult.EMAIL_TYPE:
2414 // Get the target URL.
2415 linkUrl = hitTestResult.getExtra();
2417 // Set the target URL as the title of the `ContextMenu`.
2418 menu.setHeaderTitle(linkUrl);
2420 // Add a `Write Email` entry.
2421 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2422 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2423 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2425 // Parse the url and set it as the data for the `Intent`.
2426 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2428 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2429 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2432 startActivity(emailIntent);
2436 // Add a `Copy Email Address` entry.
2437 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2438 // Save the email address in a `ClipData`.
2439 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2441 // Set the `ClipData` as the clipboard's primary clip.
2442 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2446 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2447 menu.add(R.string.cancel);
2450 // `IMAGE_TYPE` is an image.
2451 case WebView.HitTestResult.IMAGE_TYPE:
2452 // Get the image URL.
2453 imageUrl = hitTestResult.getExtra();
2455 // Set the image URL as the title of the `ContextMenu`.
2456 menu.setHeaderTitle(imageUrl);
2458 // Add a `View Image` entry.
2459 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2464 // Add a `Download Image` entry.
2465 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2466 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2467 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2468 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2470 // Store the image URL for use by `onRequestPermissionResult()`.
2471 downloadImageUrl = imageUrl;
2473 // Show a dialog if the user has previously denied the permission.
2474 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2475 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2476 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2478 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
2479 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2480 } else { // Show the permission request directly.
2481 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
2482 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2484 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2485 // Get a handle for the download image alert dialog.
2486 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2488 // Show the download image alert dialog.
2489 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2494 // Add a `Copy URL` entry.
2495 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2496 // Save the image URL in a `ClipData`.
2497 ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2499 // Set the `ClipData` as the clipboard's primary clip.
2500 clipboardManager.setPrimaryClip(srcImageTypeClipData);
2504 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2505 menu.add(R.string.cancel);
2509 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2510 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2511 // Get the image URL.
2512 imageUrl = hitTestResult.getExtra();
2514 // Set the image URL as the title of the `ContextMenu`.
2515 menu.setHeaderTitle(imageUrl);
2517 // Add a `View Image` entry.
2518 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2523 // Add a `Download Image` entry.
2524 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2525 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2526 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2527 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2529 // Store the image URL for use by `onRequestPermissionResult()`.
2530 downloadImageUrl = imageUrl;
2532 // Show a dialog if the user has previously denied the permission.
2533 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2534 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2535 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2537 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
2538 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2539 } else { // Show the permission request directly.
2540 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
2541 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2543 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2544 // Get a handle for the download image alert dialog.
2545 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2547 // Show the download image alert dialog.
2548 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2553 // Add a `Copy URL` entry.
2554 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2555 // Save the image URL in a `ClipData`.
2556 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2558 // Set the `ClipData` as the clipboard's primary clip.
2559 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2563 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2564 menu.add(R.string.cancel);
2570 public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
2571 // Get the `EditTexts` from the `dialogFragment`.
2572 EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
2573 EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
2575 // Extract the strings from the `EditTexts`.
2576 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2577 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2579 // Convert the favoriteIcon Bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2580 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2581 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2582 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2584 // Display the new bookmark below the current items in the (0 indexed) list.
2585 int newBookmarkDisplayOrder = bookmarksListView.getCount();
2587 // Create the bookmark.
2588 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2590 // Update `bookmarksCursor` with the current contents of this folder.
2591 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2593 // Update the `ListView`.
2594 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2596 // Scroll to the new bookmark.
2597 bookmarksListView.setSelection(newBookmarkDisplayOrder);
2601 public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
2602 // Get handles for the views in `dialogFragment`.
2603 EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
2604 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
2605 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
2607 // Get new folder name string.
2608 String folderNameString = createFolderNameEditText.getText().toString();
2610 // Get the new folder icon `Bitmap`.
2611 Bitmap folderIconBitmap;
2612 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
2613 // Get the default folder icon and convert it to a `Bitmap`.
2614 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2615 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2616 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2617 } else { // Use the `WebView` favorite icon.
2618 folderIconBitmap = favoriteIconBitmap;
2621 // Convert `folderIconBitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
2622 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2623 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2624 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2626 // Move all the bookmarks down one in the display order.
2627 for (int i = 0; i < bookmarksListView.getCount(); i++) {
2628 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2629 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2632 // Create the folder, which will be placed at the top of the `ListView`.
2633 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2635 // Update `bookmarksCursor` with the current contents of this folder.
2636 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2638 // Update the `ListView`.
2639 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2641 // Scroll to the new folder.
2642 bookmarksListView.setSelection(0);
2646 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
2647 // Get the shortcut name.
2648 EditText shortcutNameEditText = dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
2649 String shortcutNameString = shortcutNameEditText.getText().toString();
2651 // Convert the favorite icon bitmap to an `Icon`. `IconCompat` is required until API >= 26.
2652 IconCompat favoriteIcon = IconCompat.createWithBitmap(favoriteIconBitmap);
2654 // Setup the shortcut intent.
2655 Intent shortcutIntent = new Intent();
2656 shortcutIntent.setAction(Intent.ACTION_VIEW);
2657 shortcutIntent.setData(Uri.parse(formattedUrlString));
2659 // Create a shortcut info builder. The shortcut name becomes the shortcut ID.
2660 ShortcutInfoCompat.Builder shortcutInfoBuilder = new ShortcutInfoCompat.Builder(this, shortcutNameString);
2662 // Add the required fields to the shortcut info builder.
2663 shortcutInfoBuilder.setIcon(favoriteIcon);
2664 shortcutInfoBuilder.setIntent(shortcutIntent);
2665 shortcutInfoBuilder.setShortLabel(shortcutNameString);
2667 // Request the pin. `ShortcutManagerCompat` can be switched to `ShortcutManager` once API >= 26.
2668 ShortcutManagerCompat.requestPinShortcut(this, shortcutInfoBuilder.build(), null);
2672 public void onCloseDownloadLocationPermissionDialog(int downloadType) {
2673 switch (downloadType) {
2674 case DownloadLocationPermissionDialog.DOWNLOAD_FILE:
2675 // Request the WRITE_EXTERNAL_STORAGE permission with a file request code.
2676 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2679 case DownloadLocationPermissionDialog.DOWNLOAD_IMAGE:
2680 // Request the WRITE_EXTERNAL_STORAGE permission with an image request code.
2681 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2687 public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
2688 switch (requestCode) {
2689 case DOWNLOAD_FILE_REQUEST_CODE:
2690 // Show the download file alert dialog. When the dialog closes, the correct command will be used based on the permission status.
2691 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(downloadUrl, downloadContentDisposition, downloadContentLength);
2693 // On API 23, displaying the fragment must be delayed or the app will crash.
2694 if (Build.VERSION.SDK_INT == 23) {
2695 new Handler().postDelayed(() -> downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
2697 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2700 // Reset the download variables.
2702 downloadContentDisposition = "";
2703 downloadContentLength = 0;
2706 case DOWNLOAD_IMAGE_REQUEST_CODE:
2707 // Show the download image alert dialog. When the dialog closes, the correct command will be used based on the permission status.
2708 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(downloadImageUrl);
2710 // On API 23, displaying the fragment must be delayed or the app will crash.
2711 if (Build.VERSION.SDK_INT == 23) {
2712 new Handler().postDelayed(() -> downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
2714 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2717 // Reset the image URL variable.
2718 downloadImageUrl = "";
2724 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
2725 // Download the image if it has an HTTP or HTTPS URI.
2726 if (imageUrl.startsWith("http")) {
2727 // Get a handle for the system `DOWNLOAD_SERVICE`.
2728 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2730 // Parse `imageUrl`.
2731 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
2733 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
2734 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2735 if (firstPartyCookiesEnabled) {
2736 // Get the cookies for `imageUrl`.
2737 String cookies = cookieManager.getCookie(imageUrl);
2739 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2740 downloadRequest.addRequestHeader("Cookie", cookies);
2743 // Get the file name from the dialog fragment.
2744 EditText downloadImageNameEditText = dialogFragment.getDialog().findViewById(R.id.download_image_name);
2745 String imageName = downloadImageNameEditText.getText().toString();
2747 // Specify the download location.
2748 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
2749 // Download to the public download directory.
2750 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, imageName);
2751 } else { // External write permission denied.
2752 // Download to the app's external download directory.
2753 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, imageName);
2756 // Allow `MediaScanner` to index the download if it is a media file.
2757 downloadRequest.allowScanningByMediaScanner();
2759 // Add the URL as the description for the download.
2760 downloadRequest.setDescription(imageUrl);
2762 // Show the download notification after the download is completed.
2763 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2765 // Remove the lint warning below that `downloadManager` might be `null`.
2766 assert downloadManager != null;
2768 // Initiate the download.
2769 downloadManager.enqueue(downloadRequest);
2770 } else { // The image is not an HTTP or HTTPS URI.
2771 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
2776 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
2777 // Download the file if it has an HTTP or HTTPS URI.
2778 if (downloadUrl.startsWith("http")) {
2779 // Get a handle for the system `DOWNLOAD_SERVICE`.
2780 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2782 // Parse `downloadUrl`.
2783 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
2785 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
2786 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2787 if (firstPartyCookiesEnabled) {
2788 // Get the cookies for `downloadUrl`.
2789 String cookies = cookieManager.getCookie(downloadUrl);
2791 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2792 downloadRequest.addRequestHeader("Cookie", cookies);
2795 // Get the file name from the dialog fragment.
2796 EditText downloadFileNameEditText = dialogFragment.getDialog().findViewById(R.id.download_file_name);
2797 String fileName = downloadFileNameEditText.getText().toString();
2799 // Specify the download location.
2800 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
2801 // Download to the public download directory.
2802 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
2803 } else { // External write permission denied.
2804 // Download to the app's external download directory.
2805 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, fileName);
2808 // Allow `MediaScanner` to index the download if it is a media file.
2809 downloadRequest.allowScanningByMediaScanner();
2811 // Add the URL as the description for the download.
2812 downloadRequest.setDescription(downloadUrl);
2814 // Show the download notification after the download is completed.
2815 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2817 // Remove the lint warning below that `downloadManager` might be `null`.
2818 assert downloadManager != null;
2820 // Initiate the download.
2821 downloadManager.enqueue(downloadRequest);
2822 } else { // The download is not an HTTP or HTTPS URI.
2823 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
2828 public void onSaveBookmark(AppCompatDialogFragment dialogFragment, int selectedBookmarkDatabaseId) {
2829 // Get handles for the views from `dialogFragment`.
2830 EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
2831 EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
2832 RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
2834 // Store the bookmark strings.
2835 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
2836 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
2838 // Update the bookmark.
2839 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
2840 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
2841 } else { // Update the bookmark using the `WebView` favorite icon.
2842 // Convert the favorite icon to a byte array. `0` is for lossless compression (the only option for a PNG).
2843 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2844 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
2845 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
2847 // Update the bookmark and the favorite icon.
2848 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
2851 // Update `bookmarksCursor` with the current contents of this folder.
2852 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2854 // Update the `ListView`.
2855 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2859 public void onSaveBookmarkFolder(AppCompatDialogFragment dialogFragment, int selectedFolderDatabaseId) {
2860 // Get handles for the views from `dialogFragment`.
2861 EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
2862 RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
2863 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
2864 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
2866 // Get the new folder name.
2867 String newFolderNameString = editFolderNameEditText.getText().toString();
2869 // Check if the favorite icon has changed.
2870 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
2871 // Update the name in the database.
2872 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2873 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
2874 // Get the new folder icon `Bitmap`.
2875 Bitmap folderIconBitmap;
2876 if (defaultFolderIconRadioButton.isChecked()) {
2877 // Get the default folder icon and convert it to a `Bitmap`.
2878 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2879 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2880 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2881 } else { // Use the `WebView` favorite icon.
2882 folderIconBitmap = favoriteIconBitmap;
2885 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
2886 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2887 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2888 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2890 // Update the folder icon in the database.
2891 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, folderIconByteArray);
2892 } else { // The folder icon and the name have changed.
2893 // Get the new folder icon `Bitmap`.
2894 Bitmap folderIconBitmap;
2895 if (defaultFolderIconRadioButton.isChecked()) {
2896 // Get the default folder icon and convert it to a `Bitmap`.
2897 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2898 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2899 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2900 } else { // Use the `WebView` favorite icon.
2901 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
2904 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
2905 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2906 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2907 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2909 // Update the folder name and icon in the database.
2910 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
2913 // Update `bookmarksCursor` with the current contents of this folder.
2914 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2916 // Update the `ListView`.
2917 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2921 public void onHttpAuthenticationCancel() {
2922 // Cancel the `HttpAuthHandler`.
2923 httpAuthHandler.cancel();
2927 public void onHttpAuthenticationProceed(AppCompatDialogFragment dialogFragment) {
2928 // Get handles for the `EditTexts`.
2929 EditText usernameEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_username);
2930 EditText passwordEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_password);
2932 // Proceed with the HTTP authentication.
2933 httpAuthHandler.proceed(usernameEditText.getText().toString(), passwordEditText.getText().toString());
2936 public void viewSslCertificate(View view) {
2937 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
2938 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
2939 viewSslCertificateDialogFragment.show(getFragmentManager(), getString(R.string.view_ssl_certificate));
2943 public void onSslErrorCancel() {
2944 sslErrorHandler.cancel();
2948 public void onSslErrorProceed() {
2949 sslErrorHandler.proceed();
2953 public void onSslMismatchBack() {
2954 if (mainWebView.canGoBack()) { // There is a back page in the history.
2955 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2956 navigatingHistory = true;
2959 mainWebView.goBack();
2960 } else { // There are no pages to go back to.
2961 // Load a blank page
2967 public void onSslMismatchProceed() {
2968 // Do not check the pinned SSL certificate for this domain again until the domain changes.
2969 ignorePinnedSslCertificate = true;
2973 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
2974 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2975 navigatingHistory = true;
2977 // Load the history entry.
2978 mainWebView.goBackOrForward(moveBackOrForwardSteps);
2982 public void onClearHistory() {
2983 // Clear the history.
2984 mainWebView.clearHistory();
2987 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
2989 public void onBackPressed() {
2990 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
2991 // Close the navigation drawer.
2992 drawerLayout.closeDrawer(GravityCompat.START);
2993 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
2994 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
2995 // close the bookmarks drawer.
2996 drawerLayout.closeDrawer(GravityCompat.END);
2997 } else { // A subfolder is displayed.
2998 // Place the former parent folder in `currentFolder`.
2999 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolder(currentBookmarksFolder);
3001 // Load the new folder.
3002 loadBookmarksFolder();
3005 } else if (mainWebView.canGoBack()) { // There is at least one item in the `WebView` history.
3006 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3007 navigatingHistory = true;
3010 mainWebView.goBack();
3011 } else { // There isn't anything to do in Privacy Browser.
3012 // Pass `onBackPressed()` to the system.
3013 super.onBackPressed();
3017 // Process the results of an upload file chooser. Currently there is only one `startActivityForResult` in this activity, so the request code, used to differentiate them, is ignored.
3019 public void onActivityResult(int requestCode, int resultCode, Intent data) {
3020 // File uploads only work on API >= 21.
3021 if (Build.VERSION.SDK_INT >= 21) {
3022 // Pass the file to the WebView.
3023 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
3027 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
3028 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
3029 String unformattedUrlString = urlTextBox.getText().toString().trim();
3031 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
3032 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
3033 // Add `http://` at the beginning if it is missing. Otherwise the app will segfault.
3034 if (!unformattedUrlString.startsWith("http")) {
3035 unformattedUrlString = "http://" + unformattedUrlString;
3038 // Initialize `unformattedUrl`.
3039 URL unformattedUrl = null;
3041 // 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.
3043 unformattedUrl = new URL(unformattedUrlString);
3044 } catch (MalformedURLException e) {
3045 e.printStackTrace();
3048 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
3049 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
3050 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
3051 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
3052 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
3053 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
3056 Uri.Builder formattedUri = new Uri.Builder();
3057 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
3059 // Decode `formattedUri` as a `String` in `UTF-8`.
3060 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
3062 // Sanitize the search input and convert it to a search.
3063 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
3065 // Add the base search URL.
3066 formattedUrlString = searchURL + encodedUrlString;
3069 // Clear the focus from the URL text box. Otherwise, proximate typing in the box will retain the colorized formatting instead of being reset during refocus.
3070 urlTextBox.clearFocus();
3072 loadUrl(formattedUrlString);
3076 private void loadUrl(String url) {
3077 // Apply any custom domain settings.
3078 applyDomainSettings(url, true, false);
3081 mainWebView.loadUrl(url, customHeaders);
3083 // Set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
3084 urlIsLoading = true;
3087 public void findPreviousOnPage(View view) {
3088 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
3089 mainWebView.findNext(false);
3092 public void findNextOnPage(View view) {
3093 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
3094 mainWebView.findNext(true);
3097 public void closeFindOnPage(View view) {
3098 // Delete the contents of `find_on_page_edittext`.
3099 findOnPageEditText.setText(null);
3101 // Clear the highlighted phrases.
3102 mainWebView.clearMatches();
3104 // Hide the Find on Page `RelativeLayout`.
3105 findOnPageLinearLayout.setVisibility(View.GONE);
3107 // Show the URL app bar.
3108 supportAppBar.setVisibility(View.VISIBLE);
3110 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
3111 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
3114 private void applyAppSettings() {
3115 // Get a handle for the shared preferences.
3116 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3118 // Store the values from the shared preferences in variables.
3119 String homepageString = sharedPreferences.getString("homepage", "https://start.duckduckgo.com");
3120 String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
3121 String torSearchString = sharedPreferences.getString("tor_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
3122 String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
3123 String searchString = sharedPreferences.getString("search", "https://duckduckgo.com/html/?q=");
3124 String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
3125 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3126 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
3127 proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
3128 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3129 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
3130 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
3131 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh", false);
3132 displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
3134 // Set the homepage, search, and proxy options.
3135 if (proxyThroughOrbot) { // Set the Tor options.
3136 // Set `torHomepageString` as `homepage`.
3137 homepage = torHomepageString;
3139 // If formattedUrlString is null assign the homepage to it.
3140 if (formattedUrlString == null) {
3141 formattedUrlString = homepage;
3144 // Set the search URL.
3145 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
3146 searchURL = torSearchCustomURLString;
3147 } else { // Use the string from the pre-built list.
3148 searchURL = torSearchString;
3151 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
3152 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
3154 // Set the `appBar` background to indicate proxying through Orbot is enabled. `this` refers to the context.
3156 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
3158 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
3161 // Display a message to the user if we are waiting on Orbot.
3162 if (!orbotStatus.equals("ON")) {
3163 // Set `waitingForOrbot`.
3164 waitingForOrbot = true;
3166 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
3167 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
3169 } else { // Set the non-Tor options.
3170 // Set `homepageString` as `homepage`.
3171 homepage = homepageString;
3173 // If formattedUrlString is null assign the homepage to it.
3174 if (formattedUrlString == null) {
3175 formattedUrlString = homepage;
3178 // Set the search URL.
3179 if (searchString.equals("Custom URL")) { // Get the custom URL string.
3180 searchURL = searchCustomURLString;
3181 } else { // Use the string from the pre-built list.
3182 searchURL = searchString;
3185 // Reset the proxy to default. The host is `""` and the port is `"0"`.
3186 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
3188 // Set the default `appBar` background. `this` refers to the context.
3190 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
3192 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
3195 // Reset `waitingForOrbot.
3196 waitingForOrbot = false;
3199 // Set swipe to refresh.
3200 swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
3202 // Set Do Not Track status.
3203 if (doNotTrackEnabled) {
3204 customHeaders.put("DNT", "1");
3206 customHeaders.remove("DNT");
3209 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
3210 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
3211 if (hideSystemBarsOnFullscreen) { // Hide everything.
3212 // Remove the translucent navigation setting if it is currently flagged.
3213 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3215 // Remove the translucent status bar overlay.
3216 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3218 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
3219 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
3221 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3222 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3223 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3225 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3226 } else { // Hide everything except the status and navigation bars.
3227 // Add the translucent status flag if it is unset.
3228 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3230 if (translucentNavigationBarOnFullscreen) {
3231 // Set the navigation bar to be translucent.
3232 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3234 // Set the navigation bar to be black.
3235 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3238 } else { // Switch to normal viewing mode.
3239 // Reset `inFullScreenBrowsingMode` to `false`.
3240 inFullScreenBrowsingMode = false;
3242 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
3243 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
3247 // Show the `BannerAd` in the free flavor.
3248 if (BuildConfig.FLAVOR.contentEquals("free")) {
3249 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
3250 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
3252 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
3253 adView = findViewById(R.id.adview);
3256 // Remove the translucent navigation bar flag if it is set.
3257 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3259 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
3260 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3262 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
3263 rootCoordinatorLayout.setSystemUiVisibility(0);
3265 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
3266 rootCoordinatorLayout.setFitsSystemWindows(true);
3270 // `reloadWebsite` is used if returnig from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
3271 // The deprecated `.getDrawable()` must be used until the minimum API >= 21.
3272 @SuppressWarnings("deprecation")
3273 private void applyDomainSettings(String url, boolean resetFavoriteIcon, boolean reloadWebsite) {
3274 // Reset `navigatingHistory`.
3275 navigatingHistory = false;
3277 // Parse the URL into a URI.
3278 Uri uri = Uri.parse(url);
3280 // Extract the domain from `uri`.
3281 String hostName = uri.getHost();
3283 // Initialize `loadingNewDomainName`.
3284 boolean loadingNewDomainName;
3286 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
3287 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
3288 //noinspection SimplifiableIfStatement
3289 if ((hostName == null) || (currentDomainName == null)) {
3290 loadingNewDomainName = true;
3291 } else { // Determine if `hostName` equals `currentDomainName`.
3292 loadingNewDomainName = !hostName.equals(currentDomainName);
3295 // Only apply the domain settings if a new domain is being loaded. This allows the user to set temporary settings for JavaScript, cookies, DOM storage, etc.
3296 if (loadingNewDomainName) {
3297 // Set the new `hostname` as the `currentDomainName`.
3298 currentDomainName = hostName;
3300 // Reset `ignorePinnedSslCertificate`.
3301 ignorePinnedSslCertificate = false;
3303 // Reset the favorite icon if specified.
3304 if (resetFavoriteIcon) {
3305 favoriteIconBitmap = favoriteIconDefaultBitmap;
3306 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
3309 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
3310 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3311 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3313 // Get a full cursor from `domainsDatabaseHelper`.
3314 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3316 // Initialize `domainSettingsSet`.
3317 Set<String> domainSettingsSet = new HashSet<>();
3319 // Get the domain name column index.
3320 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3322 // Populate `domainSettingsSet`.
3323 for (int i = 0; i < domainNameCursor.getCount(); i++) {
3324 // Move `domainsCursor` to the current row.
3325 domainNameCursor.moveToPosition(i);
3327 // Store the domain name in `domainSettingsSet`.
3328 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3331 // Close `domainNameCursor.
3332 domainNameCursor.close();
3334 // Initialize variables to track if domain settings will be applied and, if so, under which name.
3335 domainSettingsApplied = false;
3336 String domainNameInDatabase = null;
3338 // Check the hostname.
3339 if (domainSettingsSet.contains(hostName)) {
3340 domainSettingsApplied = true;
3341 domainNameInDatabase = hostName;
3344 // If `hostName` is not `null`, check all the subdomains of `hostName` against wildcard domains in `domainCursor`.
3345 if (hostName != null) {
3346 while (hostName.contains(".") && !domainSettingsApplied) { // Stop checking if we run out of `.` or if we already know that `domainSettingsApplied` is `true`.
3347 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
3348 domainSettingsApplied = true;
3349 domainNameInDatabase = "*." + hostName;
3352 // Strip out the lowest subdomain of `host`.
3353 hostName = hostName.substring(hostName.indexOf(".") + 1);
3357 // Get a handle for the shared preference. `this` references the current context.
3358 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3360 // Store the general preference information.
3361 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
3362 String defaultUserAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
3363 String defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
3364 nightMode = sharedPreferences.getBoolean("night_mode", false);
3366 if (domainSettingsApplied) { // The url we are loading has custom domain settings.
3367 // Get a cursor for the current host and move it to the first position.
3368 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3369 currentHostDomainSettingsCursor.moveToFirst();
3371 // Get the settings from the cursor.
3372 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3373 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3374 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3375 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3376 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3377 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3378 easyListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3379 easyPrivacyEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3380 fanboysAnnoyanceListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3381 fanboysSocialBlockingListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3382 String userAgentString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3383 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3384 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3385 int nightModeInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
3386 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3387 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3388 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3389 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3390 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3391 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3392 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3394 // Set `nightMode` according to `nightModeInt`. If `nightModeInt` is `DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT` the current setting from `sharedPreferences` will be used.
3395 switch (nightModeInt) {
3396 case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
3400 case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
3405 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3407 javaScriptEnabled = true;
3410 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
3411 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
3412 pinnedDomainSslStartDate = null;
3414 pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
3417 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
3418 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
3419 pinnedDomainSslEndDate = null;
3421 pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
3424 // Close `currentHostDomainSettingsCursor`.
3425 currentHostDomainSettingsCursor.close();
3427 // Apply the domain settings.
3428 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3429 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3430 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3431 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3433 // Apply the font size.
3434 if (fontSize == 0) { // Apply the default font size.
3435 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3436 } else { // Apply the specified font size.
3437 mainWebView.getSettings().setTextZoom(fontSize);
3440 // Set third-party cookies status if API >= 21.
3441 if (Build.VERSION.SDK_INT >= 21) {
3442 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3445 // 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.
3446 // <https://redmine.stoutner.com/issues/160>
3447 if (!urlIsLoading) {
3448 switch (userAgentString) {
3449 case "System default user agent":
3450 // Set the user agent according to the system default.
3451 switch (defaultUserAgentString) {
3452 case "WebView default user agent":
3453 // Set the user agent to `""`, which uses the default value.
3454 mainWebView.getSettings().setUserAgentString("");
3457 case "Custom user agent":
3458 // Set the custom user agent.
3459 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3463 // Use the selected user agent.
3464 mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
3468 case "WebView default user agent":
3469 // Set the user agent to `""`, which uses the default value.
3470 mainWebView.getSettings().setUserAgentString("");
3474 // Use the selected user agent.
3475 mainWebView.getSettings().setUserAgentString(userAgentString);
3478 // Store the applied user agent string.
3479 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
3482 // 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.
3484 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
3486 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
3488 } else { // The URL we are loading does not have custom domain settings. Load the defaults.
3489 // Store the values from `sharedPreferences` in variables.
3490 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
3491 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
3492 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
3493 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
3494 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
3495 easyListEnabled = sharedPreferences.getBoolean("easylist", true);
3496 easyPrivacyEnabled = sharedPreferences.getBoolean("easyprivacy", true);
3497 fanboysAnnoyanceListEnabled = sharedPreferences.getBoolean("fanboy_annoyance_list", true);
3498 fanboysSocialBlockingListEnabled = sharedPreferences.getBoolean("fanboy_social_blocking_list", true);
3500 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3502 javaScriptEnabled = true;
3505 // Apply the default settings.
3506 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3507 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3508 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3509 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3510 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3512 // Reset the pinned SSL certificate information.
3513 domainSettingsDatabaseId = -1;
3514 pinnedDomainSslCertificate = false;
3515 pinnedDomainSslIssuedToCNameString = "";
3516 pinnedDomainSslIssuedToONameString = "";
3517 pinnedDomainSslIssuedToUNameString = "";
3518 pinnedDomainSslIssuedByCNameString = "";
3519 pinnedDomainSslIssuedByONameString = "";
3520 pinnedDomainSslIssuedByUNameString = "";
3521 pinnedDomainSslStartDate = null;
3522 pinnedDomainSslEndDate = null;
3524 // Set third-party cookies status if API >= 21.
3525 if (Build.VERSION.SDK_INT >= 21) {
3526 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3529 // 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.
3530 // <https://redmine.stoutner.com/issues/160>
3531 if (!urlIsLoading) {
3532 switch (defaultUserAgentString) {
3533 case "WebView default user agent":
3534 // Set the user agent to `""`, which uses the default value.
3535 mainWebView.getSettings().setUserAgentString("");
3538 case "Custom user agent":
3539 // Set the custom user agent.
3540 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3544 // Use the selected user agent.
3545 mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
3548 // Store the applied user agent string.
3549 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
3552 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
3553 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
3556 // Close `domainsDatabaseHelper`.
3557 domainsDatabaseHelper.close();
3559 // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode. `true` indicates that custom domain settings are applied.
3560 onTheFlyDisplayImagesSet = false;
3561 setDisplayWebpageImages();
3563 // Update the privacy icons, but only if `mainMenu` has already been populated.
3564 if (mainMenu != null) {
3565 updatePrivacyIcons(true);
3568 // Reload the website if returning from the Domains activity.
3569 if (reloadWebsite) {
3570 mainWebView.reload();
3575 private void setDisplayWebpageImages() {
3576 if (!onTheFlyDisplayImagesSet) {
3577 if (domainSettingsApplied) { // Custom domain settings are applied.
3578 switch (displayWebpageImagesInt) {
3579 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
3580 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
3583 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
3584 mainWebView.getSettings().setLoadsImagesAutomatically(true);
3587 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
3588 mainWebView.getSettings().setLoadsImagesAutomatically(false);
3591 } else { // Default settings are applied.
3592 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
3597 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
3598 // Get handles for the icons.
3599 MenuItem privacyIconMenuItem = mainMenu.findItem(R.id.toggle_javascript);
3600 MenuItem firstPartyCookiesIconMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
3601 MenuItem domStorageIconMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
3602 MenuItem formDataIconMenuItem = mainMenu.findItem(R.id.toggle_save_form_data);
3604 // Update `privacyIcon`.
3605 if (javaScriptEnabled) { // JavaScript is enabled.
3606 privacyIconMenuItem.setIcon(R.drawable.javascript_enabled);
3607 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
3608 privacyIconMenuItem.setIcon(R.drawable.warning);
3609 } else { // All the dangerous features are disabled.
3610 privacyIconMenuItem.setIcon(R.drawable.privacy_mode);
3613 // Update `firstPartyCookiesIcon`.
3614 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
3615 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_enabled);
3616 } else { // First-party cookies are disabled.
3618 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_dark);
3620 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_light);
3624 // Update `domStorageIcon`.
3625 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
3626 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_enabled);
3627 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
3629 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
3631 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
3633 } else { // JavaScript is disabled, so DOM storage is ghosted.
3635 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
3637 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
3641 // Update `formDataIcon`.
3642 if (saveFormDataEnabled) { // Form data is enabled.
3643 formDataIconMenuItem.setIcon(R.drawable.form_data_enabled);
3644 } else { // Form data is disabled.
3646 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_dark);
3648 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_light);
3652 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
3653 if (runInvalidateOptionsMenu) {
3654 invalidateOptionsMenu();
3658 private void highlightUrlText() {
3659 String urlString = urlTextBox.getText().toString();
3661 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
3662 urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3663 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
3664 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3667 // Get the index of the `/` immediately after the domain name.
3668 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
3670 // De-emphasize the text after the domain name.
3671 if (endOfDomainName > 0) {
3672 urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3676 private void loadBookmarksFolder() {
3677 // Update `bookmarksCursor` with the contents of the bookmarks database for the current folder.
3678 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3680 // Populate the bookmarks cursor adapter. `this` specifies the `Context`. `false` disables `autoRequery`.
3681 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
3683 public View newView(Context context, Cursor cursor, ViewGroup parent) {
3684 // Inflate the individual item layout. `false` does not attach it to the root.
3685 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
3689 public void bindView(View view, Context context, Cursor cursor) {
3690 // Get handles for the views.
3691 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
3692 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
3694 // Get the favorite icon byte array from the `Cursor`.
3695 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
3697 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
3698 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
3700 // Display the bitmap in `bookmarkFavoriteIcon`.
3701 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
3703 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
3704 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
3705 bookmarkNameTextView.setText(bookmarkNameString);
3707 // Make the font bold for folders.
3708 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
3709 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
3710 } else { // Reset the font to default for normal bookmarks.
3711 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
3716 // Populate the `ListView` with the adapter.
3717 bookmarksListView.setAdapter(bookmarksCursorAdapter);
3719 // Set the bookmarks drawer title.
3720 if (currentBookmarksFolder.isEmpty()) {
3721 bookmarksTitleTextView.setText(R.string.bookmarks);
3723 bookmarksTitleTextView.setText(currentBookmarksFolder);