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.BroadcastReceiver;
29 import android.content.ClipData;
30 import android.content.ClipboardManager;
31 import android.content.Context;
32 import android.content.Intent;
33 import android.content.IntentFilter;
34 import android.content.SharedPreferences;
35 import android.content.pm.PackageManager;
36 import android.content.res.Configuration;
37 import android.database.Cursor;
38 import android.graphics.Bitmap;
39 import android.graphics.BitmapFactory;
40 import android.graphics.Typeface;
41 import android.graphics.drawable.BitmapDrawable;
42 import android.graphics.drawable.Drawable;
43 import android.net.Uri;
44 import android.net.http.SslCertificate;
45 import android.net.http.SslError;
46 import android.os.Build;
47 import android.os.Bundle;
48 import android.os.Environment;
49 import android.os.Handler;
50 import android.preference.PreferenceManager;
51 import android.print.PrintDocumentAdapter;
52 import android.print.PrintManager;
53 import android.support.annotation.NonNull;
54 import android.support.design.widget.CoordinatorLayout;
55 import android.support.design.widget.FloatingActionButton;
56 import android.support.design.widget.NavigationView;
57 import android.support.design.widget.Snackbar;
58 import android.support.v4.app.ActivityCompat;
59 import android.support.v4.content.ContextCompat;
60 // `ShortcutInfoCompat`, `ShortcutManagerCompat`, and `IconCompat` can be switched to the non-compat version once API >= 26.
61 import android.support.v4.content.pm.ShortcutInfoCompat;
62 import android.support.v4.content.pm.ShortcutManagerCompat;
63 import android.support.v4.graphics.drawable.IconCompat;
64 import android.support.v4.view.GravityCompat;
65 import android.support.v4.widget.DrawerLayout;
66 import android.support.v4.widget.SwipeRefreshLayout;
67 import android.support.v7.app.ActionBar;
68 import android.support.v7.app.ActionBarDrawerToggle;
69 import android.support.v7.app.AppCompatActivity;
70 import android.support.v7.app.AppCompatDialogFragment;
71 import android.support.v7.widget.Toolbar;
72 import android.text.Editable;
73 import android.text.Spanned;
74 import android.text.TextWatcher;
75 import android.text.style.ForegroundColorSpan;
76 import android.util.Patterns;
77 import android.view.ContextMenu;
78 import android.view.GestureDetector;
79 import android.view.KeyEvent;
80 import android.view.Menu;
81 import android.view.MenuItem;
82 import android.view.MotionEvent;
83 import android.view.View;
84 import android.view.ViewGroup;
85 import android.view.WindowManager;
86 import android.view.inputmethod.InputMethodManager;
87 import android.webkit.CookieManager;
88 import android.webkit.HttpAuthHandler;
89 import android.webkit.SslErrorHandler;
90 import android.webkit.WebBackForwardList;
91 import android.webkit.WebChromeClient;
92 import android.webkit.WebResourceResponse;
93 import android.webkit.WebStorage;
94 import android.webkit.WebView;
95 import android.webkit.WebViewClient;
96 import android.webkit.WebViewDatabase;
97 import android.widget.CursorAdapter;
98 import android.widget.EditText;
99 import android.widget.FrameLayout;
100 import android.widget.ImageView;
101 import android.widget.LinearLayout;
102 import android.widget.ListView;
103 import android.widget.ProgressBar;
104 import android.widget.RadioButton;
105 import android.widget.RelativeLayout;
106 import android.widget.TextView;
108 import com.stoutner.privacybrowser.BannerAd;
109 import com.stoutner.privacybrowser.BuildConfig;
110 import com.stoutner.privacybrowser.R;
111 import com.stoutner.privacybrowser.dialogs.AddDomainDialog;
112 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
113 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
114 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
115 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
116 import com.stoutner.privacybrowser.dialogs.DownloadLocationPermissionDialog;
117 import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
118 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
119 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
120 import com.stoutner.privacybrowser.dialogs.PinnedSslCertificateMismatchDialog;
121 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
122 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
123 import com.stoutner.privacybrowser.helpers.BlockListHelper;
124 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
125 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
126 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
127 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
128 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
130 import java.io.ByteArrayInputStream;
131 import java.io.ByteArrayOutputStream;
133 import java.io.IOException;
134 import java.io.UnsupportedEncodingException;
135 import java.net.MalformedURLException;
137 import java.net.URLDecoder;
138 import java.net.URLEncoder;
139 import java.util.ArrayList;
140 import java.util.Date;
141 import java.util.HashMap;
142 import java.util.HashSet;
143 import java.util.List;
144 import java.util.Map;
145 import java.util.Set;
147 // AppCompatActivity from android.support.v7.app.AppCompatActivity must be used to have access to the SupportActionBar until the minimum API is >= 21.
148 public class MainWebViewActivity extends AppCompatActivity implements AddDomainDialog.AddDomainListener, CreateBookmarkDialog.CreateBookmarkListener,
149 CreateBookmarkFolderDialog.CreateBookmarkFolderListener, CreateHomeScreenShortcutDialog.CreateHomeScreenSchortcutListener, DownloadFileDialog.DownloadFileListener,
150 DownloadImageDialog.DownloadImageListener, DownloadLocationPermissionDialog.DownloadLocationPermissionDialogListener, EditBookmarkDialog.EditBookmarkListener,
151 EditBookmarkFolderDialog.EditBookmarkFolderListener, HttpAuthenticationDialog.HttpAuthenticationListener, NavigationView.OnNavigationItemSelectedListener,
152 PinnedSslCertificateMismatchDialog.PinnedSslCertificateMismatchListener, SslCertificateErrorDialog.SslCertificateErrorListener, UrlHistoryDialog.UrlHistoryListener {
154 // `darkTheme` is public static so it can be accessed from `AboutActivity`, `GuideActivity`, `AddDomainDialog`, `SettingsActivity`, `DomainsActivity`, `DomainsListFragment`, `BookmarksActivity`,
155 // `BookmarksDatabaseViewActivity`, `CreateBookmarkDialog`, `CreateBookmarkFolderDialog`, `DownloadFileDialog`, `DownloadImageDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`,
156 // `EditBookmarkDatabaseViewDialog`, `HttpAuthenticationDialog`, `MoveToFolderDialog`, `SslCertificateErrorDialog`, `UrlHistoryDialog`, `ViewSslCertificateDialog`, `CreateHomeScreenShortcutDialog`,
157 // and `OrbotProxyHelper`. It is also used in `onCreate()`, `applyAppSettings()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
158 public static boolean darkTheme;
160 // `favoriteIconBitmap` is public static so it can be accessed from `CreateHomeScreenShortcutDialog`, `BookmarksActivity`, `BookmarksDatabaseViewActivity`, `CreateBookmarkDialog`,
161 // `CreateBookmarkFolderDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`, `EditBookmarkDatabaseViewDialog`, and `ViewSslCertificateDialog`. It is also used in `onCreate()`,
162 // `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onCreateHomeScreenShortcutCreate()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `applyDomainSettings()`.
163 public static Bitmap favoriteIconBitmap;
165 // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`, `CreateBookmarkDialog`, and `AddDomainDialog`.
166 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
167 public static String formattedUrlString;
169 // `sslCertificate` is public static so it can be accessed from `DomainsActivity`, `DomainsListFragment`, `DomainSettingsFragment`, `PinnedSslCertificateMismatchDialog`,
170 // and `ViewSslCertificateDialog`. It is also used in `onCreate()`.
171 public static SslCertificate sslCertificate;
173 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`.
174 public static String orbotStatus;
176 // `webViewTitle` is public static so it can be accessed from `CreateBookmarkDialog` and `CreateHomeScreenShortcutDialog`. It is also used in `onCreate()`.
177 public static String webViewTitle;
179 // `appliedUserAgentString` is public static so it can be accessed from `ViewSourceActivity`. It is also used in `applyDomainSettings()`.
180 public static String appliedUserAgentString;
182 // `reloadOnRestart` is public static so it can be accessed from `SettingsFragment`. It is also used in `onRestart()`
183 public static boolean reloadOnRestart;
185 // `reloadUrlOnRestart` is public static so it can be accessed from `SettingsFragment`. It is also used in `onRestart()`.
186 public static boolean loadUrlOnRestart;
188 // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onRestart()`.
189 public static boolean restartFromBookmarksActivity;
191 // The block list versions are public static so they can be accessed from `AboutTabFragment`. They are also used in `onCreate()`.
192 public static String easyListVersion;
193 public static String easyPrivacyVersion;
194 public static String fanboyAnnoyanceVersion;
195 public static String fanboySocialVersion;
197 // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`,
198 // `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
199 public static String currentBookmarksFolder;
201 // `domainSettingsDatabaseId` is public static so it can be accessed from `PinnedSslCertificateMismatchDialog`. It is also used in `onCreate()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
202 public static int domainSettingsDatabaseId;
204 // The pinned domain SSL Certificate variables are public static so they can be accessed from `PinnedSslCertificateMismatchDialog`. They are also used in `onCreate()` and `applyDomainSettings()`.
205 public static String pinnedDomainSslIssuedToCNameString;
206 public static String pinnedDomainSslIssuedToONameString;
207 public static String pinnedDomainSslIssuedToUNameString;
208 public static String pinnedDomainSslIssuedByCNameString;
209 public static String pinnedDomainSslIssuedByONameString;
210 public static String pinnedDomainSslIssuedByUNameString;
211 public static Date pinnedDomainSslStartDate;
212 public static Date pinnedDomainSslEndDate;
215 // `appBar` is used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applyAppSettings()`.
216 private ActionBar appBar;
218 // `navigatingHistory` is used in `onCreate()`, `onNavigationItemSelected()`, `onSslMismatchBack()`, and `applyDomainSettings()`.
219 private boolean navigatingHistory;
221 // `favoriteIconDefaultBitmap` is used in `onCreate()` and `applyDomainSettings`.
222 private Bitmap favoriteIconDefaultBitmap;
224 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, `onBackPressed()`, and `onRestart()`.
225 private DrawerLayout drawerLayout;
227 // `rootCoordinatorLayout` is used in `onCreate()` and `applyAppSettings()`.
228 private CoordinatorLayout rootCoordinatorLayout;
230 // `mainWebView` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
231 // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, and `setDisplayWebpageImages()`.
232 private WebView mainWebView;
234 // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
235 private FrameLayout fullScreenVideoFrameLayout;
237 // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu`, and `onRestart()`.
238 private SwipeRefreshLayout swipeRefreshLayout;
240 // `urlAppBarRelativeLayout` is used in `onCreate()` and `applyDomainSettings()`.
241 private RelativeLayout urlAppBarRelativeLayout;
243 // `favoriteIconImageView` is used in `onCreate()` and `applyDomainSettings()`
244 private ImageView favoriteIconImageView;
246 // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `loadUrlFromTextBox()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
247 private CookieManager cookieManager;
249 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
250 private final Map<String, String> customHeaders = new HashMap<>();
252 // `javaScriptEnabled` is also used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
253 private boolean javaScriptEnabled;
255 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applyDomainSettings()`.
256 private boolean firstPartyCookiesEnabled;
258 // `thirdPartyCookiesEnabled` used in `onCreate()`, `onPrepareOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
259 private boolean thirdPartyCookiesEnabled;
261 // `domStorageEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
262 private boolean domStorageEnabled;
264 // `saveFormDataEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
265 private boolean saveFormDataEnabled;
267 // `nightMode` is used in `onCreate()` and `applyDomainSettings()`.
268 private boolean nightMode;
270 // `swipeToRefreshEnabled` is used in `onPrepareOptionsMenu()` and `applyAppSettings()`.
271 private boolean swipeToRefreshEnabled;
273 // `displayWebpageImagesBoolean` is used in `applyAppSettings()` and `applyDomainSettings()`.
274 private boolean displayWebpageImagesBoolean;
276 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applyAppSettings()`.
277 private String homepage;
279 // `searchURL` is used in `loadURLFromTextBox()` and `applyAppSettings()`.
280 private String searchURL;
282 // The block list variables are used in `onCreate()` and `applyAppSettings()`.
283 private boolean easyListEnabled;
284 private boolean easyPrivacyEnabled;
285 private boolean fanboysAnnoyanceListEnabled;
286 private boolean fanboysSocialBlockingListEnabled;
288 // `privacyBrowserRuntime` is used in `onCreate()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
289 private Runtime privacyBrowserRuntime;
291 // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
292 private boolean incognitoModeEnabled;
294 // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
295 private boolean fullScreenBrowsingModeEnabled;
297 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
298 private boolean inFullScreenBrowsingMode;
300 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
301 private boolean hideSystemBarsOnFullscreen;
303 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
304 private boolean translucentNavigationBarOnFullscreen;
306 // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
307 private boolean reapplyDomainSettingsOnRestart;
309 // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
310 private boolean reapplyAppSettingsOnRestart;
312 // `currentDomainName` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onAddDomain()`, and `applyDomainSettings()`.
313 private String currentDomainName;
315 // `ignorePinnedSslCertificateForDomain` is used in `onCreate()`, `onSslMismatchProceed()`, and `applyDomainSettings()`.
316 private boolean ignorePinnedSslCertificate;
318 // `waitingForOrbot` is used in `onCreate()` and `applyAppSettings()`.
319 private boolean waitingForOrbot;
321 // `domainSettingsApplied` is used in `prepareOptionsMenu()`, `applyDomainSettings()`, and `setDisplayWebpageImages()`.
322 private boolean domainSettingsApplied;
324 // `displayWebpageImagesInt` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
325 private int displayWebpageImagesInt;
327 // `onTheFlyDisplayImagesSet` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
328 private boolean onTheFlyDisplayImagesSet;
330 // `waitingForOrbotData` is used in `onCreate()` and `applyAppSettings()`.
331 private String waitingForOrbotHTMLString;
333 // `privateDataDirectoryString` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
334 private String privateDataDirectoryString;
336 // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
337 private LinearLayout findOnPageLinearLayout;
339 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
340 private EditText findOnPageEditText;
342 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
343 private Menu mainMenu;
345 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
346 private ActionBarDrawerToggle drawerToggle;
348 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
349 private Toolbar supportAppBar;
351 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, `loadUrl()`, and `highlightUrlText()`.
352 private EditText urlTextBox;
354 // The color spans are used in `onCreate()` and `highlightUrlText()`.
355 private ForegroundColorSpan redColorSpan;
356 private ForegroundColorSpan initialGrayColorSpan;
357 private ForegroundColorSpan finalGrayColorSpan;
359 // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
362 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
363 private SslErrorHandler sslErrorHandler;
365 // `httpAuthHandler` is used in `onCreate()`, `onHttpAuthenticationCancel()`, and `onHttpAuthenticationProceed()`.
366 private static HttpAuthHandler httpAuthHandler;
368 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
369 private InputMethodManager inputMethodManager;
371 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
372 private RelativeLayout mainWebViewRelativeLayout;
374 // `urlIsLoading` is used in `onCreate()`, `loadUrl()`, and `applyDomainSettings()`.
375 private boolean urlIsLoading;
377 // `pinnedDomainSslCertificate` is used in `onCreate()` and `applyDomainSettings()`.
378 private boolean pinnedDomainSslCertificate;
380 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
381 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
383 // `bookmarksListView` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, and `loadBookmarksFolder()`.
384 private ListView bookmarksListView;
386 // `bookmarksTitleTextView` is used in `onCreate()` and `loadBookmarksFolder()`.
387 private TextView bookmarksTitleTextView;
389 // `bookmarksCursor` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
390 private Cursor bookmarksCursor;
392 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
393 private CursorAdapter bookmarksCursorAdapter;
395 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
396 private String oldFolderNameString;
398 // The download strings are used in `onCreate()` and `onRequestPermissionResult()`.
399 private String downloadUrl;
400 private String downloadContentDisposition;
401 private long downloadContentLength;
403 // `downloadImageUrl` is used in `onCreateContextMenu()` and `onRequestPermissionResult()`.
404 private String downloadImageUrl;
406 // The request codes are used in `onCreate()`, `onCreateContextMenu()`, `onCloseDownloadLocationPermissionDialog()`, and `onRequestPermissionResult()`.
407 private final int DOWNLOAD_FILE_REQUEST_CODE = 1;
408 private final int DOWNLOAD_IMAGE_REQUEST_CODE = 2;
411 // 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.
412 // Also, remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
413 @SuppressLint({"SetJavaScriptEnabled", "ClickableViewAccessibility"})
414 // Remove Android Studio's warning about deprecations. We have to use the deprecated `getColor()` until API >= 23.
415 @SuppressWarnings("deprecation")
416 protected void onCreate(Bundle savedInstanceState) {
417 // Get a handle for `sharedPreferences`. `this` references the current context.
418 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
420 // Get the theme preference.
421 darkTheme = sharedPreferences.getBoolean("dark_theme", false);
423 // Set the activity theme.
425 setTheme(R.style.PrivacyBrowserDark);
427 setTheme(R.style.PrivacyBrowserLight);
430 // Run the default commands.
431 super.onCreate(savedInstanceState);
433 // Set the content view.
434 setContentView(R.layout.main_drawerlayout);
436 // Get a handle for `inputMethodManager`.
437 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
439 // `SupportActionBar` from `android.support.v7.app.ActionBar` must be used until the minimum API is >= 21.
440 supportAppBar = findViewById(R.id.app_bar);
441 setSupportActionBar(supportAppBar);
442 appBar = getSupportActionBar();
444 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
445 assert appBar != null;
447 // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
448 appBar.setCustomView(R.layout.url_app_bar);
449 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
451 // Initialize the foreground color spans for highlighting the URLs. We have to use the deprecated `getColor()` until API >= 23.
452 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
453 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
454 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
456 // Get a handle for `urlTextBox`.
457 urlTextBox = findViewById(R.id.url_edittext);
459 // Remove the formatting from `urlTextBar` when the user is editing the text.
460 urlTextBox.setOnFocusChangeListener((View v, boolean hasFocus) -> {
461 if (hasFocus) { // The user is editing `urlTextBox`.
462 // Remove the highlighting.
463 urlTextBox.getText().removeSpan(redColorSpan);
464 urlTextBox.getText().removeSpan(initialGrayColorSpan);
465 urlTextBox.getText().removeSpan(finalGrayColorSpan);
466 } else { // The user has stopped editing `urlTextBox`.
467 // Reapply the highlighting.
472 // Set the go button on the keyboard to load the URL in `urlTextBox`.
473 urlTextBox.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
474 // If the event is a key-down event on the `enter` button, load the URL.
475 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
476 // Load the URL into the mainWebView and consume the event.
478 loadUrlFromTextBox();
479 } catch (UnsupportedEncodingException e) {
482 // If the enter key was pressed, consume the event.
485 // If any other key was pressed, do not consume the event.
490 // Set `waitingForOrbotHTMLString`.
491 waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
493 // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
494 currentDomainName = "";
495 orbotStatus = "unknown";
496 waitingForOrbot = false;
498 // Create an Orbot status `BroadcastReceiver`.
499 BroadcastReceiver orbotStatusBroadcastReceiver = new BroadcastReceiver() {
501 public void onReceive(Context context, Intent intent) {
502 // Store the content of the status message in `orbotStatus`.
503 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
505 // If we are waiting on Orbot, load the website now that Orbot is connected.
506 if (orbotStatus.equals("ON") && waitingForOrbot) {
507 // Reset `waitingForOrbot`.
508 waitingForOrbot = false;
510 // Load `formattedUrlString
511 loadUrl(formattedUrlString);
516 // Register `orbotStatusBroadcastReceiver` on `this` context.
517 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
519 // Get handles for views that need to be accessed.
520 drawerLayout = findViewById(R.id.drawerlayout);
521 rootCoordinatorLayout = findViewById(R.id.root_coordinatorlayout);
522 bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
523 bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
524 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
525 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
526 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
527 mainWebViewRelativeLayout = findViewById(R.id.main_webview_relativelayout);
528 mainWebView = findViewById(R.id.main_webview);
529 findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
530 findOnPageEditText = findViewById(R.id.find_on_page_edittext);
531 fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
532 urlAppBarRelativeLayout = findViewById(R.id.url_app_bar_relativelayout);
533 favoriteIconImageView = findViewById(R.id.favorite_icon);
535 // 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.
537 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
538 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
539 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
540 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
542 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
543 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
544 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
545 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
548 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
549 launchBookmarksActivityFab.setOnClickListener(v -> {
550 // Create an intent to launch the bookmarks activity.
551 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
553 // Include the current folder with the `Intent`.
554 bookmarksIntent.putExtra("Current Folder", currentBookmarksFolder);
557 startActivity(bookmarksIntent);
560 // Set the create new bookmark folder FAB to display the `AlertDialog`.
561 createBookmarkFolderFab.setOnClickListener(v -> {
562 // Show the `CreateBookmarkFolderDialog` `AlertDialog` and name the instance `@string/create_folder`.
563 AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
564 createBookmarkFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_folder));
567 // Set the create new bookmark FAB to display the `AlertDialog`.
568 createBookmarkFab.setOnClickListener(view -> {
569 // Show the `CreateBookmarkDialog` `AlertDialog` and name the instance `@string/create_bookmark`.
570 AppCompatDialogFragment createBookmarkDialog = new CreateBookmarkDialog();
571 createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
574 // Create a double-tap listener to toggle full-screen mode.
575 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
576 // Override `onDoubleTap()`. All other events are handled using the default settings.
578 public boolean onDoubleTap(MotionEvent event) {
579 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
580 // Toggle `inFullScreenBrowsingMode`.
581 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
583 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
584 // Hide the `appBar`.
587 // Hide the `BannerAd` in the free flavor.
588 if (BuildConfig.FLAVOR.contentEquals("free")) {
589 BannerAd.hideAd(adView);
592 // Modify the system bars.
593 if (hideSystemBarsOnFullscreen) { // Hide everything.
594 // Remove the translucent overlays.
595 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
597 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
598 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
600 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
601 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
602 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
604 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
606 // Set `rootCoordinatorLayout` to fill the whole screen.
607 rootCoordinatorLayout.setFitsSystemWindows(false);
608 } else { // Hide everything except the status and navigation bars.
609 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
610 rootCoordinatorLayout.setFitsSystemWindows(false);
612 // 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.
613 if (translucentNavigationBarOnFullscreen) {
614 // Set the navigation bar to be translucent.
615 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
618 } else { // Switch to normal viewing mode.
619 // Show the `appBar`.
622 // Show the `BannerAd` in the free flavor.
623 if (BuildConfig.FLAVOR.contentEquals("free")) {
624 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
625 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
627 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
628 adView = findViewById(R.id.adview);
631 // Remove the translucent navigation bar flag if it is set.
632 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
634 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
635 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
637 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
638 rootCoordinatorLayout.setSystemUiVisibility(0);
640 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
641 rootCoordinatorLayout.setFitsSystemWindows(true);
644 // Consume the double-tap.
646 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
652 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
653 mainWebView.setOnTouchListener((View v, MotionEvent event) -> {
654 // Call `performClick()` on the view, which is required for accessibility.
657 // Send the `event` to `gestureDetector`.
658 return gestureDetector.onTouchEvent(event);
661 // Update `findOnPageCountTextView`.
662 mainWebView.setFindListener(new WebView.FindListener() {
663 // Get a handle for `findOnPageCountTextView`.
664 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
667 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
668 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
669 // Set `findOnPageCountTextView` to `0/0`.
670 findOnPageCountTextView.setText(R.string.zero_of_zero);
671 } else if (isDoneCounting) { // There are matches.
672 // `activeMatchOrdinal` is zero-based.
673 int activeMatch = activeMatchOrdinal + 1;
675 // Build the match string.
676 String matchString = activeMatch + "/" + numberOfMatches;
678 // Set `findOnPageCountTextView`.
679 findOnPageCountTextView.setText(matchString);
684 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
685 findOnPageEditText.addTextChangedListener(new TextWatcher() {
687 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
692 public void onTextChanged(CharSequence s, int start, int before, int count) {
697 public void afterTextChanged(Editable s) {
698 // Search for the text in `mainWebView`.
699 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
703 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
704 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
705 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
706 // Hide the soft keyboard. `0` indicates no additional flags.
707 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
709 // Consume the event.
711 } else { // A different key was pressed.
712 // Do not consume the event.
717 // Implement swipe to refresh
718 swipeRefreshLayout = findViewById(R.id.swipe_refreshlayout);
719 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
720 swipeRefreshLayout.setOnRefreshListener(() -> mainWebView.reload());
722 // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
723 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
724 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
726 // Listen for touches on the navigation menu.
727 final NavigationView navigationView = findViewById(R.id.navigationview);
728 navigationView.setNavigationItemSelectedListener(this);
730 // 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.
731 final Menu navigationMenu = navigationView.getMenu();
732 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
733 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
734 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
736 // Initialize the bookmarks database helper. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
737 // The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
738 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
740 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
741 currentBookmarksFolder = "";
743 // Load the home folder, which is `""` in the database.
744 loadBookmarksFolder();
746 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
747 // Convert the id from long to int to match the format of the bookmarks database.
748 int databaseID = (int) id;
750 // Get the bookmark `Cursor` for this ID and move it to the first row.
751 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
752 bookmarkCursor.moveToFirst();
754 // Act upon the bookmark according to the type.
755 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
756 // Store the new folder name in `currentBookmarksFolder`.
757 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
759 // Load the new folder.
760 loadBookmarksFolder();
761 } else { // The selected bookmark is not a folder.
762 // Load the bookmark URL.
763 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
765 // Close the bookmarks drawer.
766 drawerLayout.closeDrawer(GravityCompat.END);
769 // Close the `Cursor`.
770 bookmarkCursor.close();
773 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
774 // Convert the database ID from `long` to `int`.
775 int databaseId = (int) id;
777 // Find out if the selected bookmark is a folder.
778 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
781 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
782 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
784 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
785 AppCompatDialogFragment editFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId);
786 editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
788 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
789 AppCompatDialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId);
790 editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
793 // Consume the event.
797 // The `DrawerListener` allows us to update the Navigation Menu.
798 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
800 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
804 public void onDrawerOpened(@NonNull View drawerView) {
808 public void onDrawerClosed(@NonNull View drawerView) {
812 public void onDrawerStateChanged(int newState) {
813 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // The drawer is opening or closing.
814 // Update the `Back`, `Forward`, and `History` menu items.
815 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
816 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
817 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
819 // Hide the keyboard (if displayed) so we can see the navigation menu. `0` indicates no additional flags.
820 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
822 // Clear the focus from `urlTextBox` if it has it.
823 urlTextBox.clearFocus();
828 // drawerToggle creates the hamburger icon at the start of the AppBar.
829 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
831 // Get a handle for the progress bar.
832 final ProgressBar progressBar = findViewById(R.id.progress_bar);
834 mainWebView.setWebChromeClient(new WebChromeClient() {
835 // Update the progress bar when a page is loading.
837 public void onProgressChanged(WebView view, int progress) {
838 // Inject the night mode CSS if night mode is enabled.
840 // `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
841 // used by WordPress. `text-decoration: none` removes all text underlines. `text-shadow: none` removes text shadows, which usually have a hard coded color.
842 // `border: none` removes all borders, which can also be used to underline text.
843 // `a {color: #1565C0}` sets links to be a dark blue. `!important` takes precedent over any existing sub-settings.
844 mainWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; " +
845 "style.innerHTML = '* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important;" +
846 "text-shadow: none !important; border: none !important;} a {color: #1565C0 !important;}'; parent.appendChild(style)})()", value -> {
847 // Initialize a `Handler` to display `mainWebView`.
848 Handler displayWebViewHandler = new Handler();
850 // Setup a `Runnable` to display `mainWebView` after a delay to allow the CSS to be applied.
851 Runnable displayWebViewRunnable = () -> {
852 // Only display `mainWebView` if the progress bar is one. This prevents the display of the `WebView` while it is still loading.
853 if (progressBar.getVisibility() == View.GONE) {
854 mainWebView.setVisibility(View.VISIBLE);
858 // Use `displayWebViewHandler` to delay the displaying of `mainWebView` for 500 milliseconds.
859 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
863 // Update the progress bar.
864 progressBar.setProgress(progress);
866 // Set the visibility of the progress bar.
867 if (progress < 100) {
868 // Show the progress bar.
869 progressBar.setVisibility(View.VISIBLE);
871 // Hide the progress bar.
872 progressBar.setVisibility(View.GONE);
874 // Display `mainWebView` if night mode is disabled.
875 // 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
876 // currently enabled.
878 mainWebView.setVisibility(View.VISIBLE);
881 //Stop the `SwipeToRefresh` indicator if it is running
882 swipeRefreshLayout.setRefreshing(false);
886 // Set the favorite icon when it changes.
888 public void onReceivedIcon(WebView view, Bitmap icon) {
889 // Only update the favorite icon if the website has finished loading.
890 if (progressBar.getVisibility() == View.GONE) {
891 // Save a copy of the favorite icon.
892 favoriteIconBitmap = icon;
894 // Place the favorite icon in the appBar.
895 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
899 // Save a copy of the title when it changes.
901 public void onReceivedTitle(WebView view, String title) {
902 // Save a copy of the title.
903 webViewTitle = title;
906 // Enter full screen video
908 public void onShowCustomView(View view, CustomViewCallback callback) {
909 // Pause the ad if this is the free flavor.
910 if (BuildConfig.FLAVOR.contentEquals("free")) {
911 BannerAd.pauseAd(adView);
914 // Remove the translucent overlays.
915 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
917 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
918 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
920 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
921 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
922 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
924 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
926 // Set `rootCoordinatorLayout` to fill the entire screen.
927 rootCoordinatorLayout.setFitsSystemWindows(false);
929 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
930 fullScreenVideoFrameLayout.addView(view);
931 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
934 // Exit full screen video
935 public void onHideCustomView() {
936 // Hide `fullScreenVideoFrameLayout`.
937 fullScreenVideoFrameLayout.removeAllViews();
938 fullScreenVideoFrameLayout.setVisibility(View.GONE);
940 // Add the translucent status flag. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
941 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
943 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars. This also clears the `SYSTEM_UI` flags.
944 rootCoordinatorLayout.setFitsSystemWindows(true);
946 // Show the ad if this is the free flavor.
947 if (BuildConfig.FLAVOR.contentEquals("free")) {
948 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
949 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
951 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
952 adView = findViewById(R.id.adview);
957 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
958 registerForContextMenu(mainWebView);
960 // Allow the downloading of files.
961 mainWebView.setDownloadListener((String url, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
962 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
963 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
964 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
966 // Store the variables for future use by `onRequestPermissionsResult()`.
968 downloadContentDisposition = contentDisposition;
969 downloadContentLength = contentLength;
971 // Show a dialog if the user has previously denied the permission.
972 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
973 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
974 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
976 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
977 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
978 } else { // Show the permission request directly.
979 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
980 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
982 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
983 // Get a handle for the download file alert dialog.
984 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
986 // Show the download file alert dialog.
987 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
991 // Allow pinch to zoom.
992 mainWebView.getSettings().setBuiltInZoomControls(true);
994 // Hide zoom controls.
995 mainWebView.getSettings().setDisplayZoomControls(false);
997 // Set `mainWebView` to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
998 mainWebView.getSettings().setUseWideViewPort(true);
1000 // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
1001 mainWebView.getSettings().setLoadWithOverviewMode(true);
1003 // Explicitly disable geolocation.
1004 mainWebView.getSettings().setGeolocationEnabled(false);
1006 // Initialize cookieManager.
1007 cookieManager = CookieManager.getInstance();
1009 // 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).
1010 customHeaders.put("X-Requested-With", "");
1012 // 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.
1013 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
1015 // Get the intent that started the app.
1016 final Intent launchingIntent = getIntent();
1018 // Extract the launching intent data as `launchingIntentUriData`.
1019 final Uri launchingIntentUriData = launchingIntent.getData();
1021 // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
1022 if (launchingIntentUriData != null) {
1023 formattedUrlString = launchingIntentUriData.toString();
1026 // Get a handle for the `Runtime`.
1027 privacyBrowserRuntime = Runtime.getRuntime();
1029 // Store the application's private data directory.
1030 privateDataDirectoryString = getApplicationInfo().dataDir;
1031 // `dataDir` will vary, but will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
1033 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
1034 inFullScreenBrowsingMode = false;
1036 // Initialize AdView for the free flavor.
1037 adView = findViewById(R.id.adview);
1039 // Initialize the privacy settings variables.
1040 javaScriptEnabled = false;
1041 firstPartyCookiesEnabled = false;
1042 thirdPartyCookiesEnabled = false;
1043 domStorageEnabled = false;
1044 saveFormDataEnabled = false;
1047 // Initialize `webViewTitle`.
1048 webViewTitle = getString(R.string.no_title);
1050 // Initialize `favoriteIconBitmap`. `ContextCompat` must be used until API >= 21.
1051 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
1052 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
1053 assert favoriteIconBitmapDrawable != null;
1054 favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
1056 // If the favorite icon is null, load the default.
1057 if (favoriteIconBitmap == null) {
1058 favoriteIconBitmap = favoriteIconDefaultBitmap;
1061 // Apply the app settings from the shared preferences.
1064 // Instantiate the block list helper.
1065 BlockListHelper blockListHelper = new BlockListHelper();
1067 // Parse the block lists.
1068 final ArrayList<List<String[]>> easyList = blockListHelper.parseBlockList(getAssets(), "blocklists/easylist.txt");
1069 final ArrayList<List<String[]>> easyPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/easyprivacy.txt");
1070 final ArrayList<List<String[]>> fanboyAnnoyance = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-annoyance.txt");
1071 final ArrayList<List<String[]>> fanboySocial = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-social.txt");
1073 // Store the list versions.
1074 easyListVersion = easyList.get(0).get(0)[0];
1075 easyPrivacyVersion = easyPrivacy.get(0).get(0)[0];
1076 fanboyAnnoyanceVersion = fanboyAnnoyance.get(0).get(0)[0];
1077 fanboySocialVersion = fanboySocial.get(0).get(0)[0];
1079 mainWebView.setWebViewClient(new WebViewClient() {
1080 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
1081 // We have to use the deprecated `shouldOverrideUrlLoading` until API >= 24.
1082 @SuppressWarnings("deprecation")
1084 public boolean shouldOverrideUrlLoading(WebView view, String url) {
1085 if (url.startsWith("mailto:")) { // Load the email address in an external email program.
1086 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1087 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1089 // Parse the url and set it as the data for the `Intent`.
1090 emailIntent.setData(Uri.parse(url));
1092 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
1093 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1096 startActivity(emailIntent);
1098 // Returning `true` indicates the application is handling the URL.
1100 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
1101 // `ACTION_DIAL` open the dialer and loads the phone number, but waits for the user to place the call.
1102 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
1104 // Add the phone number to the intent.
1105 dialIntent.setData(Uri.parse(url));
1107 // `FLAG_ACTIVITY_NEW_TASK` opens the dialer in a new task instead as part of Privacy Browser.
1108 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1111 startActivity(dialIntent);
1113 // Returning `true` indicates the application is handling the URL.
1115 } else { // Load the URL in Privacy Browser.
1116 // Apply the domain settings for the new URL.
1117 applyDomainSettings(url, true);
1119 // Returning `false` causes the current `WebView` to handle the URL and prevents it from adding redirects to the history list.
1124 // Check requests against the block lists. The deprecated `shouldInterceptRequest` must be used until minimum API >= 21.
1125 @SuppressWarnings("deprecation")
1127 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
1128 // Create an empty web resource response to be used if the resource request is blocked.
1129 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
1131 // Check EasyList if it is enabled.
1132 if (easyListEnabled) {
1133 if (blockListHelper.isBlocked(formattedUrlString, url, easyList)) {
1134 // The resource request was blocked. Return an empty web resource response.
1135 return emptyWebResourceResponse;
1139 // Check EasyPrivacy if it is enabled.
1140 if (easyPrivacyEnabled) {
1141 if (blockListHelper.isBlocked(formattedUrlString, url, easyPrivacy)) {
1142 // The resource request was blocked. Return an empty web resource response.
1143 return emptyWebResourceResponse;
1147 // Check Fanboy’s Annoyance List if it is enabled.
1148 if (fanboysAnnoyanceListEnabled) {
1149 if (blockListHelper.isBlocked(formattedUrlString, url, fanboyAnnoyance)) {
1150 // The resource request was blocked. Return an empty web resource response.
1151 return emptyWebResourceResponse;
1153 } else if (fanboysSocialBlockingListEnabled){ // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
1154 if (blockListHelper.isBlocked(formattedUrlString, url, fanboySocial)) {
1155 // The resource request was blocked. Return an empty web resource response.
1156 return emptyWebResourceResponse;
1160 // The resource request has not been blocked. `return null` loads the requested resource.
1164 // Handle HTTP authentication requests.
1166 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
1167 // Store `handler` so it can be accessed from `onHttpAuthenticationCancel()` and `onHttpAuthenticationProceed()`.
1168 httpAuthHandler = handler;
1170 // Display the HTTP authentication dialog.
1171 AppCompatDialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm);
1172 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
1175 // Update the URL in urlTextBox when the page starts to load.
1177 public void onPageStarted(WebView view, String url, Bitmap favicon) {// If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
1179 mainWebView.setVisibility(View.INVISIBLE);
1182 // Hide the keyboard. `0` indicates no additional flags.
1183 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1185 // Check to see if we are waiting on Orbot.
1186 if (!waitingForOrbot) { // We are not waiting on Orbot, so we need to process the URL.
1187 // 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.
1188 formattedUrlString = url;
1190 // Display the formatted URL text.
1191 urlTextBox.setText(formattedUrlString);
1193 // Apply text highlighting to `urlTextBox`.
1196 // Apply any custom domain settings if the URL was loaded by navigating history.
1197 if (navigatingHistory) {
1198 applyDomainSettings(url, true);
1201 // 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.
1202 urlIsLoading = true;
1206 // It is necessary to update `formattedUrlString` and `urlTextBox` after the page finishes loading because the final URL can change during load.
1208 public void onPageFinished(WebView view, String url) {
1209 // Flush any cookies to persistent storage. `CookieManager` has become very lazy about flushing cookies in recent versions.
1210 if (firstPartyCookiesEnabled && Build.VERSION.SDK_INT >= 21) {
1211 cookieManager.flush();
1214 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
1215 urlIsLoading = false;
1217 // Clear the cache and history if Incognito Mode is enabled.
1218 if (incognitoModeEnabled) {
1219 // Clear the cache. `true` includes disk files.
1220 mainWebView.clearCache(true);
1222 // Clear the back/forward history.
1223 mainWebView.clearHistory();
1225 // Manually delete cache folders.
1227 // Delete the main `cache` folder.
1228 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1230 // Delete the `app_webview` folder, which contains an additional `WebView` cache. See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
1231 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
1232 } catch (IOException e) {
1233 // Do nothing if an error is thrown.
1237 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
1238 if (!waitingForOrbot) {
1239 // Check to see if `WebView` has set `url` to be `about:blank`.
1240 if (url.equals("about:blank")) { // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
1241 // Set `formattedUrlString` to `""`.
1242 formattedUrlString = "";
1244 urlTextBox.setText(formattedUrlString);
1246 // Request focus for `urlTextBox`.
1247 urlTextBox.requestFocus();
1249 // Display the keyboard.
1250 inputMethodManager.showSoftInput(urlTextBox, 0);
1252 // Apply the domain settings. This clears any settings from the previous domain.
1253 applyDomainSettings(formattedUrlString, true);
1254 } else { // `WebView` has loaded a webpage.
1255 // Set `formattedUrlString`.
1256 formattedUrlString = url;
1258 // Only update `urlTextBox` if the user is not typing in it.
1259 if (!urlTextBox.hasFocus()) {
1260 // Display the formatted URL text.
1261 urlTextBox.setText(formattedUrlString);
1263 // Apply text highlighting to `urlTextBox`.
1268 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
1269 sslCertificate = mainWebView.getCertificate();
1271 // 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.
1272 if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate) {
1273 // Initialize the current SSL certificate variables.
1274 String currentWebsiteIssuedToCName = "";
1275 String currentWebsiteIssuedToOName = "";
1276 String currentWebsiteIssuedToUName = "";
1277 String currentWebsiteIssuedByCName = "";
1278 String currentWebsiteIssuedByOName = "";
1279 String currentWebsiteIssuedByUName = "";
1280 Date currentWebsiteSslStartDate = null;
1281 Date currentWebsiteSslEndDate = null;
1284 // Extract the individual pieces of information from the current website SSL certificate if it is not null.
1285 if (sslCertificate != null) {
1286 currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
1287 currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
1288 currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
1289 currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
1290 currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
1291 currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
1292 currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
1293 currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
1296 // 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`.
1297 String currentWebsiteSslStartDateString = "";
1298 String currentWebsiteSslEndDateString = "";
1299 String pinnedDomainSslStartDateString = "";
1300 String pinnedDomainSslEndDateString = "";
1302 // Convert the `Dates` to `Strings` if they are not `null`.
1303 if (currentWebsiteSslStartDate != null) {
1304 currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
1307 if (currentWebsiteSslEndDate != null) {
1308 currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
1311 if (pinnedDomainSslStartDate != null) {
1312 pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
1315 if (pinnedDomainSslEndDate != null) {
1316 pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
1319 // Check to see if the pinned SSL certificate matches the current website certificate.
1320 if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) ||
1321 !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) || !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) ||
1322 !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
1323 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) {
1324 // The pinned SSL certificate doesn't match the current domain certificate.
1325 //Display the pinned SSL certificate mismatch `AlertDialog`.
1326 AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
1327 pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
1333 // Handle SSL Certificate errors.
1335 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
1336 // Get the current website SSL certificate.
1337 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
1339 // Extract the individual pieces of information from the current website SSL certificate.
1340 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
1341 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
1342 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
1343 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
1344 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
1345 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
1346 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
1347 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
1349 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
1350 if (pinnedDomainSslCertificate &&
1351 currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) &&
1352 currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) && currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) &&
1353 currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
1354 currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) {
1355 // An SSL certificate is pinned and matches the current domain certificate.
1356 // Proceed to the website without displaying an error.
1358 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
1359 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
1360 sslErrorHandler = handler;
1362 // Display the SSL error `AlertDialog`.
1363 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
1364 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
1369 // Load the website if not waiting for Orbot to connect.
1370 if (!waitingForOrbot) {
1371 loadUrl(formattedUrlString);
1376 protected void onNewIntent(Intent intent) {
1377 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1380 // Check to see if the intent contains a new URL.
1381 if (intent.getData() != null) {
1382 // Get the intent data and convert it to a string.
1383 final Uri intentUriData = intent.getData();
1384 formattedUrlString = intentUriData.toString();
1386 // Load the website.
1387 loadUrl(formattedUrlString);
1389 // Close the navigation drawer if it is open.
1390 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1391 drawerLayout.closeDrawer(GravityCompat.START);
1394 // Close the bookmarks drawer if it is open.
1395 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
1396 drawerLayout.closeDrawer(GravityCompat.END);
1399 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1400 mainWebView.requestFocus();
1405 public void onRestart() {
1406 // Run the default commands.
1409 // Apply the app settings if returning from the Settings activity..
1410 if (reapplyAppSettingsOnRestart) {
1411 // Apply the app settings.
1414 // Reload the webpage if displaying of images has been disabled in the Settings activity.
1415 if (reloadOnRestart) {
1416 // Reload `mainWebView`.
1417 mainWebView.reload();
1419 // Reset `reloadOnRestartBoolean`.
1420 reloadOnRestart = false;
1423 // Reset the return from settings flag.
1424 reapplyAppSettingsOnRestart = false;
1427 // Apply the domain settings if returning from the Domains activity.
1428 if (reapplyDomainSettingsOnRestart) {
1429 // Reapply the domain settings.
1430 applyDomainSettings(formattedUrlString, false);
1432 // Reset `reapplyDomainSettingsOnRestart`.
1433 reapplyDomainSettingsOnRestart = false;
1436 // Load the URL on restart to apply changes to night mode.
1437 if (loadUrlOnRestart) {
1438 // Load the current `formattedUrlString`.
1439 loadUrl(formattedUrlString);
1441 // Reset `loadUrlOnRestart.
1442 loadUrlOnRestart = false;
1445 // Update the bookmarks drawer if returning from the Bookmarks activity.
1446 if (restartFromBookmarksActivity) {
1447 // Close the bookmarks drawer.
1448 drawerLayout.closeDrawer(GravityCompat.END);
1450 // Reload the bookmarks drawer.
1451 loadBookmarksFolder();
1453 // Reset `restartFromBookmarksActivity`.
1454 restartFromBookmarksActivity = false;
1457 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
1458 updatePrivacyIcons(true);
1461 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1463 public void onResume() {
1464 // Run the default commands.
1467 // Resume JavaScript (if enabled).
1468 mainWebView.resumeTimers();
1470 // Resume `mainWebView`.
1471 mainWebView.onResume();
1473 // Resume the adView for the free flavor.
1474 if (BuildConfig.FLAVOR.contentEquals("free")) {
1475 BannerAd.resumeAd(adView);
1480 public void onPause() {
1481 // Pause `mainWebView`.
1482 mainWebView.onPause();
1484 // Stop all JavaScript.
1485 mainWebView.pauseTimers();
1487 // Pause the adView or it will continue to consume resources in the background on the free flavor.
1488 if (BuildConfig.FLAVOR.contentEquals("free")) {
1489 BannerAd.pauseAd(adView);
1496 public boolean onCreateOptionsMenu(Menu menu) {
1497 // Inflate the menu; this adds items to the action bar if it is present.
1498 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1500 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1503 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1504 updatePrivacyIcons(false);
1506 // Get handles for the menu items.
1507 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1508 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1509 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1510 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1512 // Only display third-party cookies if SDK >= 21
1513 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1515 // Get the shared preference values. `this` references the current context.
1516 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1518 // Set the status of the additional app bar icons. The default is `false`.
1519 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
1520 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1521 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1522 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1523 } else { //Do not display the additional icons.
1524 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1525 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1526 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1533 public boolean onPrepareOptionsMenu(Menu menu) {
1534 // Get handles for the menu items.
1535 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
1536 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1537 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1538 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1539 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1540 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
1541 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1542 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1543 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);
1544 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1545 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1546 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1548 // Set the text for the domain menu item.
1549 if (domainSettingsApplied) {
1550 addOrEditDomain.setTitle(R.string.edit_domain_settings);
1552 addOrEditDomain.setTitle(R.string.add_domain_settings);
1555 // Set the status of the menu item checkboxes.
1556 toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1557 toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1558 toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1559 toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);
1560 displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1562 // Enable third-party cookies if first-party cookies are enabled.
1563 toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1565 // Enable `DOM Storage` if JavaScript is enabled.
1566 toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
1568 // Enable `Clear Cookies` if there are any.
1569 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1571 // Get a count of the number of files in the `Local Storage` directory.
1572 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1573 int localStorageDirectoryNumberOfFiles = 0;
1574 if (localStorageDirectory.exists()) {
1575 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1578 // Get a count of the number of files in the `IndexedDB` directory.
1579 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1580 int indexedDBDirectoryNumberOfFiles = 0;
1581 if (indexedDBDirectory.exists()) {
1582 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1585 // Enable `Clear DOM Storage` if there is any.
1586 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1588 // Enable `Clear Form Data` is there is any.
1589 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1590 clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
1592 // Enable `Clear Data` if any of the submenu items are enabled.
1593 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
1595 // Initialize font size variables.
1596 int fontSize = mainWebView.getSettings().getTextZoom();
1597 String fontSizeTitle;
1598 MenuItem selectedFontSizeMenuItem;
1600 // Prepare the font size title and current size menu item.
1603 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
1604 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1608 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
1609 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1613 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
1614 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1618 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1619 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1623 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
1624 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1628 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
1629 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1633 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
1634 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1638 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
1639 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1643 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1644 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1648 // Set the font size title and select the current size menu item.
1649 fontSizeMenuItem.setTitle(fontSizeTitle);
1650 selectedFontSizeMenuItem.setChecked(true);
1652 // Only show `Refresh` if `swipeToRefresh` is disabled.
1653 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
1655 // Run all the other default commands.
1656 super.onPrepareOptionsMenu(menu);
1658 // Display the menu.
1663 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1664 @SuppressLint("SetJavaScriptEnabled")
1665 // removeAllCookies is deprecated, but it is required for API < 21.
1666 @SuppressWarnings("deprecation")
1667 public boolean onOptionsItemSelected(MenuItem menuItem) {
1668 // Get the selected menu item ID.
1669 int menuItemId = menuItem.getItemId();
1671 // Set the commands that relate to the menu entries.
1672 switch (menuItemId) {
1673 case R.id.add_or_edit_domain:
1674 if (domainSettingsApplied) { // Edit the current domain settings.
1675 // Reapply the domain settings on returning to `MainWebViewActivity`.
1676 reapplyDomainSettingsOnRestart = true;
1677 currentDomainName = "";
1679 // Create an intent to launch the domains activity.
1680 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1682 // Put extra information instructing the domains activity to directly load the current domain.
1683 domainsIntent.putExtra("LoadDomain", domainSettingsDatabaseId);
1686 startActivity(domainsIntent);
1687 } else { // Add a new domain.
1688 // Show the add domain `AlertDialog`.
1689 AppCompatDialogFragment addDomainDialog = new AddDomainDialog();
1690 addDomainDialog.show(getSupportFragmentManager(), getResources().getString(R.string.add_domain));
1694 case R.id.toggle_javascript:
1695 // Switch the status of javaScriptEnabled.
1696 javaScriptEnabled = !javaScriptEnabled;
1698 // Apply the new JavaScript status.
1699 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1701 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1702 updatePrivacyIcons(true);
1704 // Display a `Snackbar`.
1705 if (javaScriptEnabled) { // JavaScrip is enabled.
1706 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1707 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
1708 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1709 } else { // Privacy mode.
1710 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1713 // Reload the WebView.
1714 mainWebView.reload();
1717 case R.id.toggle_first_party_cookies:
1718 // Switch the status of firstPartyCookiesEnabled.
1719 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1721 // Update the menu checkbox.
1722 menuItem.setChecked(firstPartyCookiesEnabled);
1724 // Apply the new cookie status.
1725 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1727 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1728 updatePrivacyIcons(true);
1730 // Display a `Snackbar`.
1731 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1732 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1733 } else if (javaScriptEnabled){ // JavaScript is still enabled.
1734 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1735 } else { // Privacy mode.
1736 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1739 // Reload the WebView.
1740 mainWebView.reload();
1743 case R.id.toggle_third_party_cookies:
1744 if (Build.VERSION.SDK_INT >= 21) {
1745 // Switch the status of thirdPartyCookiesEnabled.
1746 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1748 // Update the menu checkbox.
1749 menuItem.setChecked(thirdPartyCookiesEnabled);
1751 // Apply the new cookie status.
1752 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1754 // Display a `Snackbar`.
1755 if (thirdPartyCookiesEnabled) {
1756 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1758 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1761 // Reload the WebView.
1762 mainWebView.reload();
1763 } // Else do nothing because SDK < 21.
1766 case R.id.toggle_dom_storage:
1767 // Switch the status of domStorageEnabled.
1768 domStorageEnabled = !domStorageEnabled;
1770 // Update the menu checkbox.
1771 menuItem.setChecked(domStorageEnabled);
1773 // Apply the new DOM Storage status.
1774 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1776 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1777 updatePrivacyIcons(true);
1779 // Display a `Snackbar`.
1780 if (domStorageEnabled) {
1781 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1783 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1786 // Reload the WebView.
1787 mainWebView.reload();
1790 case R.id.toggle_save_form_data:
1791 // Switch the status of saveFormDataEnabled.
1792 saveFormDataEnabled = !saveFormDataEnabled;
1794 // Update the menu checkbox.
1795 menuItem.setChecked(saveFormDataEnabled);
1797 // Apply the new form data status.
1798 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1800 // Display a `Snackbar`.
1801 if (saveFormDataEnabled) {
1802 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1804 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1807 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1808 updatePrivacyIcons(true);
1810 // Reload the WebView.
1811 mainWebView.reload();
1814 case R.id.clear_cookies:
1815 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1816 .setAction(R.string.undo, v -> {
1817 // Do nothing because everything will be handled by `onDismissed()` below.
1819 .addCallback(new Snackbar.Callback() {
1821 public void onDismissed(Snackbar snackbar, int event) {
1823 // The user pushed the `Undo` button.
1824 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1828 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1830 // `cookieManager.removeAllCookie()` varies by SDK.
1831 if (Build.VERSION.SDK_INT < 21) {
1832 cookieManager.removeAllCookie();
1834 // `null` indicates no callback.
1835 cookieManager.removeAllCookies(null);
1843 case R.id.clear_dom_storage:
1844 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1845 .setAction(R.string.undo, v -> {
1846 // Do nothing because everything will be handled by `onDismissed()` below.
1848 .addCallback(new Snackbar.Callback() {
1850 public void onDismissed(Snackbar snackbar, int event) {
1852 // The user pushed the `Undo` button.
1853 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1857 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1859 // Delete the DOM Storage.
1860 WebStorage webStorage = WebStorage.getInstance();
1861 webStorage.deleteAllData();
1863 // Manually delete the DOM storage files and directories.
1865 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1866 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1868 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1869 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1870 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1871 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1872 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1873 } catch (IOException e) {
1874 // Do nothing if an error is thrown.
1882 case R.id.clear_form_data:
1883 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1884 .setAction(R.string.undo, v -> {
1885 // Do nothing because everything will be handled by `onDismissed()` below.
1887 .addCallback(new Snackbar.Callback() {
1889 public void onDismissed(Snackbar snackbar, int event) {
1891 // The user pushed the `Undo` button.
1892 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1896 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1898 // Delete the form data.
1899 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1900 mainWebViewDatabase.clearFormData();
1907 case R.id.font_size_twenty_five_percent:
1908 mainWebView.getSettings().setTextZoom(25);
1911 case R.id.font_size_fifty_percent:
1912 mainWebView.getSettings().setTextZoom(50);
1915 case R.id.font_size_seventy_five_percent:
1916 mainWebView.getSettings().setTextZoom(75);
1919 case R.id.font_size_one_hundred_percent:
1920 mainWebView.getSettings().setTextZoom(100);
1923 case R.id.font_size_one_hundred_twenty_five_percent:
1924 mainWebView.getSettings().setTextZoom(125);
1927 case R.id.font_size_one_hundred_fifty_percent:
1928 mainWebView.getSettings().setTextZoom(150);
1931 case R.id.font_size_one_hundred_seventy_five_percent:
1932 mainWebView.getSettings().setTextZoom(175);
1935 case R.id.font_size_two_hundred_percent:
1936 mainWebView.getSettings().setTextZoom(200);
1939 case R.id.display_images:
1940 if (mainWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1941 mainWebView.getSettings().setLoadsImagesAutomatically(false);
1942 mainWebView.reload();
1943 } else { // Images are not currently loaded automatically.
1944 mainWebView.getSettings().setLoadsImagesAutomatically(true);
1947 // Set `onTheFlyDisplayImagesSet`.
1948 onTheFlyDisplayImagesSet = true;
1952 // Setup the share string.
1953 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
1955 // Create the share intent.
1956 Intent shareIntent = new Intent();
1957 shareIntent.setAction(Intent.ACTION_SEND);
1958 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1959 shareIntent.setType("text/plain");
1962 startActivity(Intent.createChooser(shareIntent, "Share URL"));
1965 case R.id.find_on_page:
1966 // Hide the URL app bar.
1967 supportAppBar.setVisibility(View.GONE);
1969 // Show the Find on Page `RelativeLayout`.
1970 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1972 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android.
1973 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1974 findOnPageEditText.postDelayed(() -> {
1975 // Set the focus on `findOnPageEditText`.
1976 findOnPageEditText.requestFocus();
1978 // Display the keyboard. `0` sets no input flags.
1979 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1984 // Get a `PrintManager` instance.
1985 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1987 // Convert `mainWebView` to `printDocumentAdapter`.
1988 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
1990 // Remove the lint error below that `printManager` might be `null`.
1991 assert printManager != null;
1993 // Print the document. The print attributes are `null`.
1994 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1997 case R.id.view_source:
1998 // Launch the Vew Source activity.
1999 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
2000 startActivity(viewSourceIntent);
2003 case R.id.add_to_homescreen:
2004 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
2005 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
2006 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2008 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
2012 mainWebView.reload();
2016 // Don't consume the event.
2017 return super.onOptionsItemSelected(menuItem);
2021 // removeAllCookies is deprecated, but it is required for API < 21.
2022 @SuppressWarnings("deprecation")
2024 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2025 int menuItemId = menuItem.getItemId();
2027 switch (menuItemId) {
2033 if (mainWebView.canGoBack()) {
2034 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2035 navigatingHistory = true;
2037 // Load the previous website in the history.
2038 mainWebView.goBack();
2043 if (mainWebView.canGoForward()) {
2044 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2045 navigatingHistory = true;
2047 // Load the next website in the history.
2048 mainWebView.goForward();
2053 // Get the `WebBackForwardList`.
2054 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
2056 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
2057 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
2058 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2061 case R.id.downloads:
2062 // Launch the system Download Manager.
2063 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2065 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2066 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2068 startActivity(downloadManagerIntent);
2072 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2073 reapplyDomainSettingsOnRestart = true;
2074 currentDomainName = "";
2076 // Launch `DomainsActivity`.
2077 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2078 startActivity(domainsIntent);
2082 // Set the flag to reapply app settings on restart when returning from Settings.
2083 reapplyAppSettingsOnRestart = true;
2085 // Set the flag to reapply the domain settings on restart when returning from Settings.
2086 reapplyDomainSettingsOnRestart = true;
2087 currentDomainName = "";
2089 // Launch `SettingsActivity`.
2090 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2091 startActivity(settingsIntent);
2095 // Launch `GuideActivity`.
2096 Intent guideIntent = new Intent(this, GuideActivity.class);
2097 startActivity(guideIntent);
2101 // Launch `AboutActivity`.
2102 Intent aboutIntent = new Intent(this, AboutActivity.class);
2103 startActivity(aboutIntent);
2106 case R.id.clearAndExit:
2107 // Get a handle for `sharedPreferences`. `this` references the current context.
2108 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2110 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2113 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2114 // The command to remove cookies changed slightly in API 21.
2115 if (Build.VERSION.SDK_INT >= 21) {
2116 cookieManager.removeAllCookies(null);
2118 cookieManager.removeAllCookie();
2121 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2123 // We have to use two commands because `Runtime.exec()` does not like `*`.
2124 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2125 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2126 } catch (IOException e) {
2127 // Do nothing if an error is thrown.
2131 // Clear DOM storage.
2132 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2133 // Ask `WebStorage` to clear the DOM storage.
2134 WebStorage webStorage = WebStorage.getInstance();
2135 webStorage.deleteAllData();
2137 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2139 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2140 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2142 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2143 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2144 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2145 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2146 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2147 } catch (IOException e) {
2148 // Do nothing if an error is thrown.
2153 if (clearEverything || sharedPreferences.getBoolean("clear_form_data", true)) {
2154 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
2155 webViewDatabase.clearFormData();
2157 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2159 // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2160 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
2161 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
2162 } catch (IOException e) {
2163 // Do nothing if an error is thrown.
2168 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2169 // `true` includes disk files.
2170 mainWebView.clearCache(true);
2172 // Manually delete the cache directories.
2174 // Delete the main cache directory.
2175 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2176 // Delete the secondary `Service Worker` cache directory.
2177 // We have to use a `String[]` because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2178 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2179 } catch (IOException e) {
2180 // Do nothing if an error is thrown.
2184 // Clear SSL certificate preferences.
2185 mainWebView.clearSslPreferences();
2187 // Clear the back/forward history.
2188 mainWebView.clearHistory();
2190 // Clear `formattedUrlString`.
2191 formattedUrlString = null;
2193 // Clear `customHeaders`.
2194 customHeaders.clear();
2196 // Detach all views from `mainWebViewRelativeLayout`.
2197 mainWebViewRelativeLayout.removeAllViews();
2199 // Destroy the internal state of `mainWebView`.
2200 mainWebView.destroy();
2202 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
2203 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
2204 if (clearEverything) {
2206 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
2207 } catch (IOException e) {
2208 // Do nothing if an error is thrown.
2212 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
2213 if (Build.VERSION.SDK_INT >= 21) {
2214 finishAndRemoveTask();
2219 // Remove the terminated program from RAM. The status code is `0`.
2224 // Close the navigation drawer.
2225 drawerLayout.closeDrawer(GravityCompat.START);
2230 public void onPostCreate(Bundle savedInstanceState) {
2231 super.onPostCreate(savedInstanceState);
2233 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
2234 drawerToggle.syncState();
2238 public void onConfigurationChanged(Configuration newConfig) {
2239 super.onConfigurationChanged(newConfig);
2241 // Reload the ad for the free flavor if we are not in full screen mode.
2242 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2244 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2246 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2247 adView = findViewById(R.id.adview);
2250 // `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:
2251 // https://code.google.com/p/android/issues/detail?id=20493#c8
2252 // ActivityCompat.invalidateOptionsMenu(this);
2256 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2257 // Store the `HitTestResult`.
2258 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
2261 final String imageUrl;
2262 final String linkUrl;
2264 // Get a handle for the `ClipboardManager`.
2265 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2267 // Remove the lint errors below that `clipboardManager` might be `null`.
2268 assert clipboardManager != null;
2270 switch (hitTestResult.getType()) {
2271 // `SRC_ANCHOR_TYPE` is a link.
2272 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2273 // Get the target URL.
2274 linkUrl = hitTestResult.getExtra();
2276 // Set the target URL as the title of the `ContextMenu`.
2277 menu.setHeaderTitle(linkUrl);
2279 // Add a `Load URL` entry.
2280 menu.add(R.string.load_url).setOnMenuItemClickListener(item -> {
2285 // Add a `Copy URL` entry.
2286 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2287 // Save the link URL in a `ClipData`.
2288 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2290 // Set the `ClipData` as the clipboard's primary clip.
2291 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2295 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2296 menu.add(R.string.cancel);
2299 case WebView.HitTestResult.EMAIL_TYPE:
2300 // Get the target URL.
2301 linkUrl = hitTestResult.getExtra();
2303 // Set the target URL as the title of the `ContextMenu`.
2304 menu.setHeaderTitle(linkUrl);
2306 // Add a `Write Email` entry.
2307 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2308 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2309 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2311 // Parse the url and set it as the data for the `Intent`.
2312 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2314 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2315 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2318 startActivity(emailIntent);
2322 // Add a `Copy Email Address` entry.
2323 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2324 // Save the email address in a `ClipData`.
2325 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2327 // Set the `ClipData` as the clipboard's primary clip.
2328 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2332 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2333 menu.add(R.string.cancel);
2336 // `IMAGE_TYPE` is an image.
2337 case WebView.HitTestResult.IMAGE_TYPE:
2338 // Get the image URL.
2339 imageUrl = hitTestResult.getExtra();
2341 // Set the image URL as the title of the `ContextMenu`.
2342 menu.setHeaderTitle(imageUrl);
2344 // Add a `View Image` entry.
2345 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2350 // Add a `Download Image` entry.
2351 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2352 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2353 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2354 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2356 // Store the image URL for use by `onRequestPermissionResult()`.
2357 downloadImageUrl = imageUrl;
2359 // Show a dialog if the user has previously denied the permission.
2360 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2361 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2362 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2364 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
2365 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2366 } else { // Show the permission request directly.
2367 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
2368 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2370 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2371 // Get a handle for the download image alert dialog.
2372 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2374 // Show the download image alert dialog.
2375 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2380 // Add a `Copy URL` entry.
2381 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2382 // Save the image URL in a `ClipData`.
2383 ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2385 // Set the `ClipData` as the clipboard's primary clip.
2386 clipboardManager.setPrimaryClip(srcImageTypeClipData);
2390 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2391 menu.add(R.string.cancel);
2395 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2396 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2397 // Get the image URL.
2398 imageUrl = hitTestResult.getExtra();
2400 // Set the image URL as the title of the `ContextMenu`.
2401 menu.setHeaderTitle(imageUrl);
2403 // Add a `View Image` entry.
2404 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2409 // Add a `Download Image` entry.
2410 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2411 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2412 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2413 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2415 // Store the image URL for use by `onRequestPermissionResult()`.
2416 downloadImageUrl = imageUrl;
2418 // Show a dialog if the user has previously denied the permission.
2419 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2420 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2421 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2423 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
2424 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2425 } else { // Show the permission request directly.
2426 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
2427 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2429 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2430 // Get a handle for the download image alert dialog.
2431 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2433 // Show the download image alert dialog.
2434 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2439 // Add a `Copy URL` entry.
2440 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2441 // Save the image URL in a `ClipData`.
2442 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2444 // Set the `ClipData` as the clipboard's primary clip.
2445 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2449 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2450 menu.add(R.string.cancel);
2456 public void onAddDomain(AppCompatDialogFragment dialogFragment) {
2457 // Reapply the domain settings on returning to `MainWebViewActivity`.
2458 reapplyDomainSettingsOnRestart = true;
2459 currentDomainName = "";
2461 // Get the new domain name `String` from `dialogFragment`.
2462 EditText domainNameEditText = dialogFragment.getDialog().findViewById(R.id.domain_name_edittext);
2463 String domainNameString = domainNameEditText.getText().toString();
2465 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
2466 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2467 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2469 // Create the domain and store the database ID in `currentDomainDatabaseId`.
2470 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(domainNameString);
2472 // Create an intent to launch the domains activity.
2473 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2475 // Put extra information instructing the domains activity to directly load the current domain.
2476 domainsIntent.putExtra("LoadDomain", newDomainDatabaseId);
2479 startActivity(domainsIntent);
2483 public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
2484 // Get the `EditTexts` from the `dialogFragment`.
2485 EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
2486 EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
2488 // Extract the strings from the `EditTexts`.
2489 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2490 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2492 // Convert the favoriteIcon Bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2493 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2494 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2495 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2497 // Display the new bookmark below the current items in the (0 indexed) list.
2498 int newBookmarkDisplayOrder = bookmarksListView.getCount();
2500 // Create the bookmark.
2501 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2503 // Update `bookmarksCursor` with the current contents of this folder.
2504 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2506 // Update the `ListView`.
2507 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2509 // Scroll to the new bookmark.
2510 bookmarksListView.setSelection(newBookmarkDisplayOrder);
2514 public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
2515 // Get handles for the views in `dialogFragment`.
2516 EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
2517 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
2518 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
2520 // Get new folder name string.
2521 String folderNameString = createFolderNameEditText.getText().toString();
2523 // Get the new folder icon `Bitmap`.
2524 Bitmap folderIconBitmap;
2525 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
2526 // Get the default folder icon and convert it to a `Bitmap`.
2527 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2528 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2529 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2530 } else { // Use the `WebView` favorite icon.
2531 folderIconBitmap = favoriteIconBitmap;
2534 // Convert `folderIconBitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
2535 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2536 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2537 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2539 // Move all the bookmarks down one in the display order.
2540 for (int i = 0; i < bookmarksListView.getCount(); i++) {
2541 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2542 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2545 // Create the folder, which will be placed at the top of the `ListView`.
2546 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2548 // Update `bookmarksCursor` with the current contents of this folder.
2549 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2551 // Update the `ListView`.
2552 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2554 // Scroll to the new folder.
2555 bookmarksListView.setSelection(0);
2559 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
2560 // Get the shortcut name.
2561 EditText shortcutNameEditText = dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
2562 String shortcutNameString = shortcutNameEditText.getText().toString();
2564 // Convert the favorite icon bitmap to an `Icon`. `IconCompat` is required until API >= 26.
2565 IconCompat favoriteIcon = IconCompat.createWithBitmap(favoriteIconBitmap);
2567 // Setup the shortcut intent.
2568 Intent shortcutIntent = new Intent();
2569 shortcutIntent.setAction(Intent.ACTION_VIEW);
2570 shortcutIntent.setData(Uri.parse(formattedUrlString));
2572 // Create a shortcut info builder. The shortcut name becomes the shortcut ID.
2573 ShortcutInfoCompat.Builder shortcutInfoBuilder = new ShortcutInfoCompat.Builder(this, shortcutNameString);
2575 // Add the required fields to the shortcut info builder.
2576 shortcutInfoBuilder.setIcon(favoriteIcon);
2577 shortcutInfoBuilder.setIntent(shortcutIntent);
2578 shortcutInfoBuilder.setShortLabel(shortcutNameString);
2580 // Request the pin. `ShortcutManagerCompat` can be switched to `ShortcutManager` once API >= 26.
2581 ShortcutManagerCompat.requestPinShortcut(this, shortcutInfoBuilder.build(), null);
2585 public void onCloseDownloadLocationPermissionDialog(int downloadType) {
2586 switch (downloadType) {
2587 case DownloadLocationPermissionDialog.DOWNLOAD_FILE:
2588 // Request the WRITE_EXTERNAL_STORAGE permission with a file request code.
2589 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2592 case DownloadLocationPermissionDialog.DOWNLOAD_IMAGE:
2593 // Request the WRITE_EXTERNAL_STORAGE permission with an image request code.
2594 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2600 public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
2601 switch (requestCode) {
2602 case DOWNLOAD_FILE_REQUEST_CODE:
2603 // Show the download file alert dialog. When the dialog closes, the correct command will be used based on the permission status.
2604 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(downloadUrl, downloadContentDisposition, downloadContentLength);
2606 // On API 23, displaying the fragment must be delayed or the app will crash.
2607 if (Build.VERSION.SDK_INT == 23) {
2608 new Handler().postDelayed(() -> downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
2610 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2613 // Reset the download variables.
2615 downloadContentDisposition = "";
2616 downloadContentLength = 0;
2619 case DOWNLOAD_IMAGE_REQUEST_CODE:
2620 // Show the download image alert dialog. When the dialog closes, the correct command will be used based on the permission status.
2621 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(downloadImageUrl);
2623 // On API 23, displaying the fragment must be delayed or the app will crash.
2624 if (Build.VERSION.SDK_INT == 23) {
2625 new Handler().postDelayed(() -> downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
2627 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2630 // Reset the image URL variable.
2631 downloadImageUrl = "";
2637 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
2638 // Download the image if it has an HTTP or HTTPS URI.
2639 if (imageUrl.startsWith("http")) {
2640 // Get a handle for the system `DOWNLOAD_SERVICE`.
2641 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2643 // Parse `imageUrl`.
2644 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
2646 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
2647 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2648 if (firstPartyCookiesEnabled) {
2649 // Get the cookies for `imageUrl`.
2650 String cookies = cookieManager.getCookie(imageUrl);
2652 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2653 downloadRequest.addRequestHeader("Cookie", cookies);
2656 // Get the file name from the dialog fragment.
2657 EditText downloadImageNameEditText = dialogFragment.getDialog().findViewById(R.id.download_image_name);
2658 String imageName = downloadImageNameEditText.getText().toString();
2660 // Specify the download location.
2661 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
2662 // Download to the public download directory.
2663 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, imageName);
2664 } else { // External write permission denied.
2665 // Download to the app's external download directory.
2666 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, imageName);
2669 // Allow `MediaScanner` to index the download if it is a media file.
2670 downloadRequest.allowScanningByMediaScanner();
2672 // Add the URL as the description for the download.
2673 downloadRequest.setDescription(imageUrl);
2675 // Show the download notification after the download is completed.
2676 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2678 // Remove the lint warning below that `downloadManager` might be `null`.
2679 assert downloadManager != null;
2681 // Initiate the download.
2682 downloadManager.enqueue(downloadRequest);
2683 } else { // The image is not an HTTP or HTTPS URI.
2684 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
2689 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
2690 // Download the file if it has an HTTP or HTTPS URI.
2691 if (downloadUrl.startsWith("http")) {
2692 // Get a handle for the system `DOWNLOAD_SERVICE`.
2693 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2695 // Parse `downloadUrl`.
2696 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
2698 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
2699 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2700 if (firstPartyCookiesEnabled) {
2701 // Get the cookies for `downloadUrl`.
2702 String cookies = cookieManager.getCookie(downloadUrl);
2704 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2705 downloadRequest.addRequestHeader("Cookie", cookies);
2708 // Get the file name from the dialog fragment.
2709 EditText downloadFileNameEditText = dialogFragment.getDialog().findViewById(R.id.download_file_name);
2710 String fileName = downloadFileNameEditText.getText().toString();
2712 // Specify the download location.
2713 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
2714 // Download to the public download directory.
2715 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
2716 } else { // External write permission denied.
2717 // Download to the app's external download directory.
2718 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, fileName);
2721 // Allow `MediaScanner` to index the download if it is a media file.
2722 downloadRequest.allowScanningByMediaScanner();
2724 // Add the URL as the description for the download.
2725 downloadRequest.setDescription(downloadUrl);
2727 // Show the download notification after the download is completed.
2728 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2730 // Remove the lint warning below that `downloadManager` might be `null`.
2731 assert downloadManager != null;
2733 // Initiate the download.
2734 downloadManager.enqueue(downloadRequest);
2735 } else { // The download is not an HTTP or HTTPS URI.
2736 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
2741 public void onSaveBookmark(AppCompatDialogFragment dialogFragment, int selectedBookmarkDatabaseId) {
2742 // Get handles for the views from `dialogFragment`.
2743 EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
2744 EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
2745 RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
2747 // Store the bookmark strings.
2748 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
2749 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
2751 // Update the bookmark.
2752 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
2753 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
2754 } else { // Update the bookmark using the `WebView` favorite icon.
2755 // Convert the favorite icon to a byte array. `0` is for lossless compression (the only option for a PNG).
2756 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2757 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
2758 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
2760 // Update the bookmark and the favorite icon.
2761 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
2764 // Update `bookmarksCursor` with the current contents of this folder.
2765 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2767 // Update the `ListView`.
2768 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2772 public void onSaveBookmarkFolder(AppCompatDialogFragment dialogFragment, int selectedFolderDatabaseId) {
2773 // Get handles for the views from `dialogFragment`.
2774 EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
2775 RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
2776 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
2777 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
2779 // Get the new folder name.
2780 String newFolderNameString = editFolderNameEditText.getText().toString();
2782 // Check if the favorite icon has changed.
2783 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
2784 // Update the name in the database.
2785 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2786 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
2787 // Get the new folder icon `Bitmap`.
2788 Bitmap folderIconBitmap;
2789 if (defaultFolderIconRadioButton.isChecked()) {
2790 // Get the default folder icon and convert it to a `Bitmap`.
2791 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2792 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2793 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2794 } else { // Use the `WebView` favorite icon.
2795 folderIconBitmap = favoriteIconBitmap;
2798 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
2799 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2800 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2801 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2803 // Update the folder icon in the database.
2804 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, folderIconByteArray);
2805 } else { // The folder icon and the name have changed.
2806 // Get the new folder icon `Bitmap`.
2807 Bitmap folderIconBitmap;
2808 if (defaultFolderIconRadioButton.isChecked()) {
2809 // Get the default folder icon and convert it to a `Bitmap`.
2810 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2811 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2812 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2813 } else { // Use the `WebView` favorite icon.
2814 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
2817 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
2818 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2819 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2820 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2822 // Update the folder name and icon in the database.
2823 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
2826 // Update `bookmarksCursor` with the current contents of this folder.
2827 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2829 // Update the `ListView`.
2830 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2834 public void onHttpAuthenticationCancel() {
2835 // Cancel the `HttpAuthHandler`.
2836 httpAuthHandler.cancel();
2840 public void onHttpAuthenticationProceed(AppCompatDialogFragment dialogFragment) {
2841 // Get handles for the `EditTexts`.
2842 EditText usernameEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_username);
2843 EditText passwordEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_password);
2845 // Proceed with the HTTP authentication.
2846 httpAuthHandler.proceed(usernameEditText.getText().toString(), passwordEditText.getText().toString());
2849 public void viewSslCertificate(View view) {
2850 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
2851 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
2852 viewSslCertificateDialogFragment.show(getFragmentManager(), getString(R.string.view_ssl_certificate));
2856 public void onSslErrorCancel() {
2857 sslErrorHandler.cancel();
2861 public void onSslErrorProceed() {
2862 sslErrorHandler.proceed();
2866 public void onSslMismatchBack() {
2867 if (mainWebView.canGoBack()) { // There is a back page in the history.
2868 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2869 navigatingHistory = true;
2872 mainWebView.goBack();
2873 } else { // There are no pages to go back to.
2874 // Load a blank page
2880 public void onSslMismatchProceed() {
2881 // Do not check the pinned SSL certificate for this domain again until the domain changes.
2882 ignorePinnedSslCertificate = true;
2886 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
2887 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2888 navigatingHistory = true;
2890 // Load the history entry.
2891 mainWebView.goBackOrForward(moveBackOrForwardSteps);
2895 public void onClearHistory() {
2896 // Clear the history.
2897 mainWebView.clearHistory();
2900 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
2902 public void onBackPressed() {
2903 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
2904 // Close the navigation drawer.
2905 drawerLayout.closeDrawer(GravityCompat.START);
2906 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
2907 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
2908 // close the bookmarks drawer.
2909 drawerLayout.closeDrawer(GravityCompat.END);
2910 } else { // A subfolder is displayed.
2911 // Place the former parent folder in `currentFolder`.
2912 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolder(currentBookmarksFolder);
2914 // Load the new folder.
2915 loadBookmarksFolder();
2918 } else if (mainWebView.canGoBack()) { // There is at least one item in the `WebView` history.
2919 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2920 navigatingHistory = true;
2923 mainWebView.goBack();
2924 } else { // There isn't anything to do in Privacy Browser.
2925 // Pass `onBackPressed()` to the system.
2926 super.onBackPressed();
2930 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
2931 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
2932 String unformattedUrlString = urlTextBox.getText().toString().trim();
2934 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
2935 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
2936 // Add `http://` at the beginning if it is missing. Otherwise the app will segfault.
2937 if (!unformattedUrlString.startsWith("http")) {
2938 unformattedUrlString = "http://" + unformattedUrlString;
2941 // Initialize `unformattedUrl`.
2942 URL unformattedUrl = null;
2944 // 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.
2946 unformattedUrl = new URL(unformattedUrlString);
2947 } catch (MalformedURLException e) {
2948 e.printStackTrace();
2951 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2952 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2953 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2954 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2955 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2956 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2959 Uri.Builder formattedUri = new Uri.Builder();
2960 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2962 // Decode `formattedUri` as a `String` in `UTF-8`.
2963 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
2965 // Sanitize the search input and convert it to a search.
2966 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2968 // Add the base search URL.
2969 formattedUrlString = searchURL + encodedUrlString;
2972 // 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.
2973 urlTextBox.clearFocus();
2975 loadUrl(formattedUrlString);
2979 private void loadUrl(String url) {
2980 // Apply any custom domain settings.
2981 applyDomainSettings(url, true);
2984 mainWebView.loadUrl(url, customHeaders);
2986 // Set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
2987 urlIsLoading = true;
2990 public void findPreviousOnPage(View view) {
2991 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
2992 mainWebView.findNext(false);
2995 public void findNextOnPage(View view) {
2996 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2997 mainWebView.findNext(true);
3000 public void closeFindOnPage(View view) {
3001 // Delete the contents of `find_on_page_edittext`.
3002 findOnPageEditText.setText(null);
3004 // Clear the highlighted phrases.
3005 mainWebView.clearMatches();
3007 // Hide the Find on Page `RelativeLayout`.
3008 findOnPageLinearLayout.setVisibility(View.GONE);
3010 // Show the URL app bar.
3011 supportAppBar.setVisibility(View.VISIBLE);
3013 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
3014 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
3017 private void applyAppSettings() {
3018 // Get a handle for the shared preferences.
3019 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3021 // Store the values from the shared preferences in variables.
3022 String homepageString = sharedPreferences.getString("homepage", "https://start.duckduckgo.com");
3023 String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
3024 String torSearchString = sharedPreferences.getString("tor_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
3025 String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
3026 String searchString = sharedPreferences.getString("search", "https://duckduckgo.com/html/?q=");
3027 String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
3028 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3029 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
3030 boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
3031 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3032 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
3033 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
3034 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh", false);
3035 displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
3037 // Set the homepage, search, and proxy options.
3038 if (proxyThroughOrbot) { // Set the Tor options.
3039 // Set `torHomepageString` as `homepage`.
3040 homepage = torHomepageString;
3042 // If formattedUrlString is null assign the homepage to it.
3043 if (formattedUrlString == null) {
3044 formattedUrlString = homepage;
3047 // Set the search URL.
3048 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
3049 searchURL = torSearchCustomURLString;
3050 } else { // Use the string from the pre-built list.
3051 searchURL = torSearchString;
3054 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
3055 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
3057 // Set the `appBar` background to indicate proxying through Orbot is enabled. `this` refers to the context.
3059 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
3061 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
3064 // Display a message to the user if we are waiting on Orbot.
3065 if (!orbotStatus.equals("ON")) {
3066 // Set `waitingForOrbot`.
3067 waitingForOrbot = true;
3069 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
3070 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
3072 } else { // Set the non-Tor options.
3073 // Set `homepageString` as `homepage`.
3074 homepage = homepageString;
3076 // If formattedUrlString is null assign the homepage to it.
3077 if (formattedUrlString == null) {
3078 formattedUrlString = homepage;
3081 // Set the search URL.
3082 if (searchString.equals("Custom URL")) { // Get the custom URL string.
3083 searchURL = searchCustomURLString;
3084 } else { // Use the string from the pre-built list.
3085 searchURL = searchString;
3088 // Reset the proxy to default. The host is `""` and the port is `"0"`.
3089 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
3091 // Set the default `appBar` background. `this` refers to the context.
3093 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
3095 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
3098 // Reset `waitingForOrbot.
3099 waitingForOrbot = false;
3102 // Set swipe to refresh.
3103 swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
3105 // Set Do Not Track status.
3106 if (doNotTrackEnabled) {
3107 customHeaders.put("DNT", "1");
3109 customHeaders.remove("DNT");
3112 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
3113 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
3114 if (hideSystemBarsOnFullscreen) { // Hide everything.
3115 // Remove the translucent navigation setting if it is currently flagged.
3116 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3118 // Remove the translucent status bar overlay.
3119 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3121 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
3122 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
3124 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3125 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3126 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3128 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3129 } else { // Hide everything except the status and navigation bars.
3130 // Add the translucent status flag if it is unset.
3131 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3133 if (translucentNavigationBarOnFullscreen) {
3134 // Set the navigation bar to be translucent.
3135 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3137 // Set the navigation bar to be black.
3138 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3141 } else { // Switch to normal viewing mode.
3142 // Reset `inFullScreenBrowsingMode` to `false`.
3143 inFullScreenBrowsingMode = false;
3145 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
3146 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
3150 // Show the `BannerAd` in the free flavor.
3151 if (BuildConfig.FLAVOR.contentEquals("free")) {
3152 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
3153 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
3155 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
3156 adView = findViewById(R.id.adview);
3159 // Remove the translucent navigation bar flag if it is set.
3160 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3162 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
3163 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3165 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
3166 rootCoordinatorLayout.setSystemUiVisibility(0);
3168 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
3169 rootCoordinatorLayout.setFitsSystemWindows(true);
3174 // The deprecated `.getDrawable()` must be used until the minimum API >= 21.
3175 @SuppressWarnings("deprecation")
3176 private void applyDomainSettings(String url, boolean resetFavoriteIcon) {
3177 // Reset `navigatingHistory`.
3178 navigatingHistory = false;
3180 // Parse the URL into a URI.
3181 Uri uri = Uri.parse(url);
3183 // Extract the domain from `uri`.
3184 String hostName = uri.getHost();
3186 // Initialize `loadingNewDomainName`.
3187 boolean loadingNewDomainName;
3189 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
3190 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
3191 //noinspection SimplifiableIfStatement
3192 if ((hostName == null) || (currentDomainName == null)) {
3193 loadingNewDomainName = true;
3194 } else { // Determine if `hostName` equals `currentDomainName`.
3195 loadingNewDomainName = !hostName.equals(currentDomainName);
3198 // 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.
3199 if (loadingNewDomainName) {
3200 // Set the new `hostname` as the `currentDomainName`.
3201 currentDomainName = hostName;
3203 // Reset `ignorePinnedSslCertificate`.
3204 ignorePinnedSslCertificate = false;
3206 // Reset the favorite icon if specified.
3207 if (resetFavoriteIcon) {
3208 favoriteIconBitmap = favoriteIconDefaultBitmap;
3209 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
3212 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
3213 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3214 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3216 // Get a full cursor from `domainsDatabaseHelper`.
3217 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3219 // Initialize `domainSettingsSet`.
3220 Set<String> domainSettingsSet = new HashSet<>();
3222 // Get the domain name column index.
3223 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3225 // Populate `domainSettingsSet`.
3226 for (int i = 0; i < domainNameCursor.getCount(); i++) {
3227 // Move `domainsCursor` to the current row.
3228 domainNameCursor.moveToPosition(i);
3230 // Store the domain name in `domainSettingsSet`.
3231 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3234 // Close `domainNameCursor.
3235 domainNameCursor.close();
3237 // Initialize variables to track if domain settings will be applied and, if so, under which name.
3238 domainSettingsApplied = false;
3239 String domainNameInDatabase = null;
3241 // Check the hostname.
3242 if (domainSettingsSet.contains(hostName)) {
3243 domainSettingsApplied = true;
3244 domainNameInDatabase = hostName;
3247 // If `hostName` is not `null`, check all the subdomains of `hostName` against wildcard domains in `domainCursor`.
3248 if (hostName != null) {
3249 while (hostName.contains(".") && !domainSettingsApplied) { // Stop checking if we run out of `.` or if we already know that `domainSettingsApplied` is `true`.
3250 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
3251 domainSettingsApplied = true;
3252 domainNameInDatabase = "*." + hostName;
3255 // Strip out the lowest subdomain of `host`.
3256 hostName = hostName.substring(hostName.indexOf(".") + 1);
3260 // Get a handle for the shared preference. `this` references the current context.
3261 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3263 // Store the general preference information.
3264 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
3265 String defaultUserAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
3266 String defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
3267 nightMode = sharedPreferences.getBoolean("night_mode", false);
3269 if (domainSettingsApplied) { // The url we are loading has custom domain settings.
3270 // Get a cursor for the current host and move it to the first position.
3271 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3272 currentHostDomainSettingsCursor.moveToFirst();
3274 // Get the settings from the cursor.
3275 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3276 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3277 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3278 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3279 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3280 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3281 easyListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3282 easyPrivacyEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3283 fanboysAnnoyanceListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3284 fanboysSocialBlockingListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3285 String userAgentString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3286 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3287 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3288 int nightModeInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
3289 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3290 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3291 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3292 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3293 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3294 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3295 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3297 // Set `nightMode` according to `nightModeInt`. If `nightModeInt` is `DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT` the current setting from `sharedPreferences` will be used.
3298 switch (nightModeInt) {
3299 case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
3303 case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
3308 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3310 javaScriptEnabled = true;
3313 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
3314 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
3315 pinnedDomainSslStartDate = null;
3317 pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
3320 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
3321 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
3322 pinnedDomainSslEndDate = null;
3324 pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
3327 // Close `currentHostDomainSettingsCursor`.
3328 currentHostDomainSettingsCursor.close();
3330 // Apply the domain settings.
3331 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3332 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3333 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3334 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3336 // Apply the font size.
3337 if (fontSize == 0) { // Apply the default font size.
3338 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3339 } else { // Apply the specified font size.
3340 mainWebView.getSettings().setTextZoom(fontSize);
3343 // Set third-party cookies status if API >= 21.
3344 if (Build.VERSION.SDK_INT >= 21) {
3345 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3348 // 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.
3349 // <https://redmine.stoutner.com/issues/160>
3350 if (!urlIsLoading) {
3351 switch (userAgentString) {
3352 case "System default user agent":
3353 // Set the user agent according to the system default.
3354 switch (defaultUserAgentString) {
3355 case "WebView default user agent":
3356 // Set the user agent to `""`, which uses the default value.
3357 mainWebView.getSettings().setUserAgentString("");
3360 case "Custom user agent":
3361 // Set the custom user agent.
3362 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3366 // Use the selected user agent.
3367 mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
3371 case "WebView default user agent":
3372 // Set the user agent to `""`, which uses the default value.
3373 mainWebView.getSettings().setUserAgentString("");
3377 // Use the selected user agent.
3378 mainWebView.getSettings().setUserAgentString(userAgentString);
3381 // Store the applied user agent string.
3382 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
3385 // 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.
3387 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
3389 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
3391 } else { // The URL we are loading does not have custom domain settings. Load the defaults.
3392 // Store the values from `sharedPreferences` in variables.
3393 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
3394 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
3395 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
3396 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
3397 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
3398 easyListEnabled = sharedPreferences.getBoolean("easylist", true);
3399 easyPrivacyEnabled = sharedPreferences.getBoolean("easyprivacy", true);
3400 fanboysAnnoyanceListEnabled = sharedPreferences.getBoolean("fanboy_annoyance_list", true);
3401 fanboysSocialBlockingListEnabled = sharedPreferences.getBoolean("fanboy_social_blocking_list", true);
3403 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3405 javaScriptEnabled = true;
3408 // Apply the default settings.
3409 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3410 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3411 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3412 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3413 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3415 // Reset the pinned SSL certificate information.
3416 domainSettingsDatabaseId = -1;
3417 pinnedDomainSslCertificate = false;
3418 pinnedDomainSslIssuedToCNameString = "";
3419 pinnedDomainSslIssuedToONameString = "";
3420 pinnedDomainSslIssuedToUNameString = "";
3421 pinnedDomainSslIssuedByCNameString = "";
3422 pinnedDomainSslIssuedByONameString = "";
3423 pinnedDomainSslIssuedByUNameString = "";
3424 pinnedDomainSslStartDate = null;
3425 pinnedDomainSslEndDate = null;
3427 // Set third-party cookies status if API >= 21.
3428 if (Build.VERSION.SDK_INT >= 21) {
3429 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3432 // 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.
3433 // <https://redmine.stoutner.com/issues/160>
3434 if (!urlIsLoading) {
3435 switch (defaultUserAgentString) {
3436 case "WebView default user agent":
3437 // Set the user agent to `""`, which uses the default value.
3438 mainWebView.getSettings().setUserAgentString("");
3441 case "Custom user agent":
3442 // Set the custom user agent.
3443 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3447 // Use the selected user agent.
3448 mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
3451 // Store the applied user agent string.
3452 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
3455 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
3456 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
3459 // Close `domainsDatabaseHelper`.
3460 domainsDatabaseHelper.close();
3462 // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode. `true` indicates that custom domain settings are applied.
3463 onTheFlyDisplayImagesSet = false;
3464 setDisplayWebpageImages();
3466 // Update the privacy icons, but only if `mainMenu` has already been populated.
3467 if (mainMenu != null) {
3468 updatePrivacyIcons(true);
3473 private void setDisplayWebpageImages() {
3474 if (!onTheFlyDisplayImagesSet) {
3475 if (domainSettingsApplied) { // Custom domain settings are applied.
3476 switch (displayWebpageImagesInt) {
3477 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
3478 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
3481 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
3482 mainWebView.getSettings().setLoadsImagesAutomatically(true);
3485 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
3486 mainWebView.getSettings().setLoadsImagesAutomatically(false);
3489 } else { // Default settings are applied.
3490 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
3495 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
3496 // Get handles for the icons.
3497 MenuItem privacyIconMenuItem = mainMenu.findItem(R.id.toggle_javascript);
3498 MenuItem firstPartyCookiesIconMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
3499 MenuItem domStorageIconMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
3500 MenuItem formDataIconMenuItem = mainMenu.findItem(R.id.toggle_save_form_data);
3502 // Update `privacyIcon`.
3503 if (javaScriptEnabled) { // JavaScript is enabled.
3504 privacyIconMenuItem.setIcon(R.drawable.javascript_enabled);
3505 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
3506 privacyIconMenuItem.setIcon(R.drawable.warning);
3507 } else { // All the dangerous features are disabled.
3508 privacyIconMenuItem.setIcon(R.drawable.privacy_mode);
3511 // Update `firstPartyCookiesIcon`.
3512 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
3513 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_enabled);
3514 } else { // First-party cookies are disabled.
3516 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_dark);
3518 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_light);
3522 // Update `domStorageIcon`.
3523 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
3524 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_enabled);
3525 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
3527 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
3529 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
3531 } else { // JavaScript is disabled, so DOM storage is ghosted.
3533 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
3535 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
3539 // Update `formDataIcon`.
3540 if (saveFormDataEnabled) { // Form data is enabled.
3541 formDataIconMenuItem.setIcon(R.drawable.form_data_enabled);
3542 } else { // Form data is disabled.
3544 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_dark);
3546 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_light);
3550 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
3551 if (runInvalidateOptionsMenu) {
3552 invalidateOptionsMenu();
3556 private void highlightUrlText() {
3557 String urlString = urlTextBox.getText().toString();
3559 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
3560 urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3561 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
3562 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3565 // Get the index of the `/` immediately after the domain name.
3566 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
3568 // De-emphasize the text after the domain name.
3569 if (endOfDomainName > 0) {
3570 urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3574 private void loadBookmarksFolder() {
3575 // Update `bookmarksCursor` with the contents of the bookmarks database for the current folder.
3576 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3578 // Populate the bookmarks cursor adapter. `this` specifies the `Context`. `false` disables `autoRequery`.
3579 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
3581 public View newView(Context context, Cursor cursor, ViewGroup parent) {
3582 // Inflate the individual item layout. `false` does not attach it to the root.
3583 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
3587 public void bindView(View view, Context context, Cursor cursor) {
3588 // Get handles for the views.
3589 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
3590 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
3592 // Get the favorite icon byte array from the `Cursor`.
3593 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
3595 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
3596 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
3598 // Display the bitmap in `bookmarkFavoriteIcon`.
3599 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
3601 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
3602 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
3603 bookmarkNameTextView.setText(bookmarkNameString);
3605 // Make the font bold for folders.
3606 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
3607 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
3608 } else { // Reset the font to default for normal bookmarks.
3609 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
3614 // Populate the `ListView` with the adapter.
3615 bookmarksListView.setAdapter(bookmarksCursorAdapter);
3617 // Set the bookmarks drawer title.
3618 if (currentBookmarksFolder.isEmpty()) {
3619 bookmarksTitleTextView.setText(R.string.bookmarks);
3621 bookmarksTitleTextView.setText(currentBookmarksFolder);